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 helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method). </p>
<p>Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.</p>
<p><strong>Edit:</strong> OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.</p>
|
<p>Virtual static methods don't make sense. If I call <code>HelperClass.HelperMethod();</code>, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of <code>HelperClass</code> - which one would you use?</p>
<p>If you want to have overrideable static-type methods you should probably go with:</p>
<ul>
<li>A singleton, if you want the same subclass to be used globally.</li>
<li>A tradition class hierarchy, with a factory or dependency injection, if you want different behavior in different parts of your application.</li>
</ul>
<p>Choose whichever solution makes more sense in your situation.</p>
|
<p>You will be able to soon, in C# 11!</p>
<p>From <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/static-virtual-interface-members" rel="nofollow noreferrer">Tutorial: Explore C# 11 feature - static virtual members in interfaces</a>:</p>
<blockquote>
<p>C# 11 and .NET 7 include <em>static virtual members in interfaces</em>. This feature enables you to define interfaces that include <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/operator-overloading" rel="nofollow noreferrer">overloaded operators</a> or other static members.</p>
</blockquote>
| 30,847
|
<p><em>Before I start, I know using iisreset is considered bad practice, but this shouldn't happen anyway..</em></p>
<p><strong>What we have:</strong></p>
<ul>
<li><p>Several machines with IIS6 on Windows Server 2003 R2 (both 64 and 32 bits)</p></li>
<li><p>Several WCF webservices (.NET runtime 2.0) deployed in several applications, each with it's own application pool, each application pool running under an other windows account.</p></li>
</ul>
<p><strong>What happens:</strong></p>
<ul>
<li>All appPools are started, all services operational</li>
<li>IISReset is executed (or the machine is rebooted)</li>
<li>IIS comes back up, but not all application pools start properly. Sometimes they all come back up, sometimes one or more pools won't start. They can be started manually however.</li>
</ul>
<p>Is this "normal" iis behavior and should I just avoid using iisreset, or are we doing something wrong in our .NET code?</p>
|
<p>The application pools should restart on an iisreset, but they do run outside of iis (in COM+) for reliability. This mean they may may not come back if the application is misbehaving, but IIS and the other apps will(should) come back. So yes, This is "normal". </p>
<p>P.S.
I would also like to "OUT" myself as a <strong>proud</strong> user of iisreset. Bad practice? <strong>Bah!</strong> ;D </p>
|
<p>Re-setting the identity (auth credentials) via advanced settings of the Application pool worked for me.</p>
<p>Earlier I changed my active directory password and as the app pool was already running, it worked fine until I performed IISRESET.</p>
| 30,610
|
<p>Does anyone know where a log of who connected to my subversion server and what they did with it is? </p>
<p>I'm looking to find out what time and which files were checked out.</p>
<p>I'm assuming that it has something like a webserver log somewhere and I just can't find it.</p>
<p>EDIT: From the response below, I wasn't aware that there are different ways of doing svn server. I am running the svnserve as a service on windows wrapper.</p>
|
<p>You don't say what your SVN server actually is. If it's svnserve, then it doesn't keep logs by default, and I wasn't aware that it could be configured to do so, though I might be out of date on this.</p>
<p>If you're using Apache/mod_svn, then you need to look into Apache logging. </p>
|
<p>This program doesn't do exactly what you've asked for but I think it will give you the insight you're actually looking for: CommitMonitor watches Subversion repositories for new commits and shows a notification to the user when that happens. Essentially it sits in your tray notification area and pops up an alert (like MSN) letting you know about new commits to the repository and giving you a full list of updated files - doubleclick each entry to see the diffs of each individual file.</p>
<p><a href="http://code.google.com/p/commitmonitor/" rel="nofollow noreferrer">Commit Monitor Website</a></p>
| 46,918
|
<p>I have many jobs that have a step to send 1 specific email out to a list of people. That list of reciepients is hardcoded in the step command and I need to remove one person from that list, in all jobs.</p>
<p>How do I loop through ALL the jobs in the Sql Server Agent and modify the command text to find+replace a specific piece of text. </p>
<p>I am using sql server 2005 and have already looked at sp_update_jobStep but doesn't appear to be exactly what i want.</p>
<p>Cheers.</p>
|
<p>You could try to update the System tables that hold the information on jobs of the SQL server directly. The relevant ones for you would be:</p>
<pre><code>msdb.dbo.SysJobs
msdb.dbo.SysJobSteps
</code></pre>
<p>If you have a specific email address to remove, you could update the <strong>Command</strong> field in the <strong>SysJobSteps</strong> table with a single UPDATE statement.</p>
<pre><code>UPDATE SJS SET
Command = REPLACE(Command, 'EmailAddress&TestDomain.Com', '')
FROM msdb.dbo.SysJobs SJ
INNER JOIN msdb.dbo.SysJobSteps SJS
ON SJS.Job_Id = SJ.Job_Id
WHERE SJ.Originating_server = ..... -- Your server here
AND SJS.Command LIKE '%EmailAddress@TestDomain.Com%'
</code></pre>
<p>It would be advisable to run the above query as a SELECT statement first, to test it returns only the job steps your are expecting to update.</p>
|
<p>If anybody still looking for this then below should do. Not the finest code but gets the job done.</p>
<pre><code>/*
Replace the below statement with the actual keyword to be replaced:
INSERT INTO SP_Keyword VALUES
('sys.databases3', 'sys.databases5')
,('sysjobs3', 'sysjobs5')
Here we are replacing sys.databases3 and sysjobs3
with sys.databases5 and sysjobs5 respectively.
Script only searches in 'TSQL', 'Powershell', 'CMDEXEC' job type.
*/
SET NOCOUNT ON
use msdb
GO
DECLARE @OldV VARCHAR(max)
DECLARE @NEWV VARCHAR(max)
DECLARE @job_id2 varchar(max)
DECLARE @step_id2 varchar(10)
DECLARE @command2 varchar(max)
DECLARE @command3 varchar(300)
--CLEANUP TASKS
IF EXISTS(SELECT * FROM sys.tables where name = 'SP_Keyword')
DROP TABLE SP_Keyword
CREATE TABLE SP_Keyword
(
old_keyword varchar(200),
new_keyword varchar(200)
)
--DEBUG STATEMENT
--PRINT 'SP_Keyword TABLE CREATED'
INSERT INTO SP_Keyword VALUES
('sys.databases3', 'sys.databases5')
,('sysjobs3', 'sysjobs5')
--DEBUG STATEMENT
--PRINT 'VALUES INSERTED FOR KEYWORD'
CREATE TABLE #jobs(
[name] [sysname] ,
[step_name] [sysname] ,
[subsystem] [varchar](40) ,
[command] [varchar](max) ,
[keyword] [varchar](200) ,
[database_name] [sysname] ,
[enabled] [tinyint] ,
[description] [varchar](512) ,
[date_created] [datetime] ,
[job_id] [uniqueidentifier] ,
[step_id] [int]
)
DECLARE db_cursor3 CURSOR FOR
SELECT old_keyword FROM SP_Keyword
OPEN db_cursor3
FETCH NEXT FROM db_cursor3 INTO @OldV
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #jobs
SELECT a.name as job_name, b.step_name, b.subsystem,
b.command, @OldV as 'keyword', b.database_name, a.enabled,
a.description, a.date_created, b.job_id, b.step_id
FROM [dbo].[sysjobsteps] as b
INNER JOIN sysjobs as a
ON a.job_id = b.job_id
WHERE [command] LIKE '%'+@OldV+'%'
AND [subsystem] IN ('TSQL', 'Powershell', 'CMDEXEC')
FETCH NEXT FROM db_cursor3 INTO @OldV
END
CLOSE db_cursor3
DEALLOCATE db_cursor3
IF NOT EXISTS(SELECT * FROM #jobs)
BEGIN
PRINT 'NO JOBS FOUND TO BE REPLACED'
GOTO SKIPPER
END
--SELECT name as job_name, step_name, command, keyword, database_name, enabled, description, date_created FROM #jobs
DECLARE db_cursor3 CURSOR FOR
SELECT * FROM SP_Keyword
OPEN db_cursor3
FETCH NEXT FROM db_cursor3 INTO @OldV,@newV
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE #jobs SET command=REPLACE(command,@oldV,@NewV)
WHERE command LIKE '%'+@OldV+'%'
FETCH NEXT FROM db_cursor3 INTO @oldV,@NewV
END
CLOSE db_cursor3
DEALLOCATE db_cursor3
print 'COMMAND TO REPLACE JOB STEPS IS BEING EXECUTED'
DECLARE db_cursor3 CURSOR FOR
SELECT job_id, step_id, command FROM #jobs
OPEN db_cursor3
FETCH NEXT FROM db_cursor3 INTO @job_id2,@step_id2, @command2
WHILE @@FETCH_STATUS = 0
BEGIN
SET @command3 = 'sp_update_jobstep @job_id = '''+@job_id2+''' ,@step_id = '+@step_id2+', @command = '''+@command2+''''
PRINT @command3
EXEC(@command3)
FETCH NEXT FROM db_cursor3 INTO @job_id2,@step_id2, @command2
END
CLOSE db_cursor3
DEALLOCATE db_cursor3
SKIPPER:
DROP TABLE #jobs
DROP TABLE SP_Keyword
PRINT 'CLEANUP DONE'
PRINT 'PROGRAM COMPLETE'
</code></pre>
| 38,211
|
<p>I need the current user and the domain. I am using a VB 6 application. </p>
<p>Thanks</p>
|
<p>One way would be to ask the environment:</p>
<pre><code>Dim UserName As String
Dim UserDomain As String
UserName = Environ("USERNAME")
UserDomain = Environ("USERDOMAIN")
</code></pre>
<p>(Works on Windows NT and up only, obviously.)</p>
|
<p>What about this?</p>
<pre><code>Private Function IsAdmin() As Boolean
Dim groups As Object
Dim user As Object
Set groups = GetObject("WinNT://./administrators")
For Each user In groups.members
If UCase(Environ("USERNAME")) = UCase(user.Name) Then
IsAdmin = True
End If
Next user
End Function
</code></pre>
| 43,756
|
<p>Joomla has a built-in function on its login screen "I've forgotten my user name", so that you can type in your email address and the username is sent to you via email.</p>
<p>I was thinking of changing it so that the username was displayed on screen immediately, without any form of authentication. This would greatly reduce the friction for our users who are returning after a long while, but it would allow anyone to type in any email address and see the associated username (definitely not the other way around though).</p>
<p>Does this create any security risks? Is it a good idea at all?</p>
|
<p>I would say it is a <em>slight</em> security risk for your less savvy users. For a user with a weak password, particularly if it is related to their username or e-mail address, exposing their user name leaves them open to having their account hijacked. Other than that, I can't think of a reason it would be a problem. If the user has good passwords, it shouldn't matter at all.</p>
<p>I guess there is a slight anonymity concern. On a forum for example, I wouldn't want someone who "knows" me to find out my username without me telling them. In this case they could take my e-mail and get it. But whether that is an issue depends on your site and your user base.</p>
|
<p>At first glance, it seems like a "bad idea" because you are allowing anyone to: </p>
<ol>
<li>verify an account exists</li>
<li>confirm the association between a username and an email address</li>
</ol>
<p>If usernames and mail addresses are treated as "private" information on your site and not already shared, then I would not implement the username lookup by email feature. In effect you are lowering the security bar by 1 factor:</p>
<ul>
<li>Currrently, looking up the username requires both email address and the user's full mail credentials (so they can pick up the reply)</li>
<li>After the change, all they need is the mail address.</li>
</ul>
<p>Perhaps more significantly, you create a privacy issue that would need to be addressed (as mentioned by @SoapBox).</p>
<p>But in reality, your site might already employ "username" as a public handle or nickname. And you may already have users publishing their email in their profiles. If this is the case, the username lookup doesn't leak any new information and you could argue no new security or privacy issues are created. </p>
<p>It would make it all a little too easy though, like publishing the script kiddies guide on <em>how to hack my site</em>:</p>
<ol>
<li>Get a list of email addresses from your preferred supplier</li>
<li>Come to my self-service mail-to-username translation page and run the list through (simple script for this)</li>
<li>Launch dictionary attack on the site using the resulting list of usernames</li>
</ol>
<p>Bottom line - I think you are best to leave this feature as-is. </p>
| 38,587
|
<p>Got a class that serializes into xml with XMLEncoder nicely with all the variables there. Except for the one that holds <em>java.util.Locale</em>. What could be the trick?</p>
|
<p>The problem is that java.util.Locale is not a <a href="http://java.sun.com/javase/technologies/desktop/javabeans/docs/spec.html" rel="noreferrer">bean</a>. From the <a href="http://java.sun.com/javase/6/docs/api/index.html?java/beans/XMLEncoder.html" rel="noreferrer">XMLEncoder</a> doc:</p>
<blockquote>
<p>The XMLEncoder class is a
complementary alternative to the
ObjectOutputStream and can used to
generate a textual representation of a
<strong>JavaBean</strong> in the same way that the
ObjectOutputStream can be used to
create binary representation of
Serializable objects.</p>
</blockquote>
<p>However, the API allows you to use PersistenceDelegates to serialize non-bean types:</p>
<p>Sample bean:</p>
<pre><code>public class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
private Locale locale;
private String foo;
public MyBean() {
}
public Locale getLocale() {
return locale;
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
}
</code></pre>
<p>Serializing a data graph that includes a Locale type:</p>
<pre><code>public class MyBeanTest {
public static void main(String[] args) throws Exception {
// quick and dirty test
MyBean c = new MyBean();
c.setLocale(Locale.CHINA);
c.setFoo("foo");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(outputStream);
encoder.setPersistenceDelegate(Locale.class, new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
});
encoder.writeObject(c);
encoder.flush();
encoder.close();
System.out.println(outputStream.toString("UTF-8"));
ByteArrayInputStream bain = new ByteArrayInputStream(outputStream
.toByteArray());
XMLDecoder decoder = new XMLDecoder(bain);
c = (MyBean) decoder.readObject();
System.out.println("===================");
System.out.println(c.getLocale());
System.out.println(c.getFoo());
}
}
</code></pre>
<p>This is the section of code that describes how the object should be instantiated on deserialization - it sets the constructor arguments to three string values:</p>
<pre><code> new PersistenceDelegate() {
protected Expression instantiate(Object oldInstance, Encoder out) {
Locale l = (Locale) oldInstance;
return new Expression(oldInstance, oldInstance.getClass(),
"new", new Object[] { l.getLanguage(), l.getCountry(),
l.getVariant() });
}
}
</code></pre>
<p>Read <a href="http://java.sun.com/products/jfc/tsc/articles/persistence4/" rel="noreferrer">Using XMLEncoder</a> by Philip Milne for more info.</p>
<p>All this aside, it might be smarter to store the locale information in textual form and use it to look up the appropriate Locale object whenever it is needed. That way you don't need special case code when serializing your object and make it more portable.</p>
|
<p>Sorry, don't you mean <em>java.util.Locale</em>? The javadocs say that <em>java.util.Locale</em> implements <em>Serializable</em>, so you should have no problem using the <em>Locale</em> class from the <em>lang</em> package.</p>
| 23,762
|
<p>I don't even know where to go with this. Google wasn't very helpful. As with my previous question. I'm using TextMate's Command+R to compile the project.</p>
<blockquote>
<p>game.h:16:error: declaration of ‘Player* HalfSet::Player() const’</p>
<p>players.h:11:error: changes meaning of ‘Player’ from ‘class Player’</p>
<p>game.h:21:error: ‘Player’ is not a type</p>
</blockquote>
<p>player.h file (partial)</p>
<pre><code>#ifndef PLAYERS_H
#define PLAYERS_H
using namespace std;
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
#include "generics.h"
class Player{ //Line 11
public:
//getters
long Id() const;
string FirstName() const;
string LastName() const;
string Country() const;
//setters
void setId(long id);
void setFirstName(string s);
void setLastName(string s);
void setCountry(string s);
//serializing functions
void display(ostream &out);
void read(istream &in);
void write(ostream &out);
//Initalizers
Player();
Player(istream &in);
Player(string firstName, string lastName);
Player(string firstName, string lastName, string country);
Player(long id, string firstName, string lastName, string country);
~Player();
private:
long _id;
string _firstName;
string _lastName;
string _country;
};
</code></pre>
<p>game.h file (partial)</p>
<pre><code>#ifndef GAME_H
#define GAME_H
#include "generics.h"
#include "players.h"
#include <string>
#include <vector>
#include <istream>
#include <iomanip>
using namespace std;
class HalfSet{
public:
//getters
Player* Player() const; //Line 16
int GamesWon() const;
int TotalPoints() const;
int Errors() const;
//setters
void setPlayer(Player* p);
void setGamesWon(int games);
void setTotalPoints(int points);
void setErrors(int errors);
//Serialization
void display(ostream &out) const;
void read(istream &in) const;
void write(ostream &out) const;
//Initalizers
HalfSet();
~HalfSet();
private:
Player* _player;
int _gamesWon;
int _points;
int _errors;
};
</code></pre>
<p>What is going on here?</p>
|
<p>In C++ you cannot name a function the same name as a class/struct/typedef. You have a class named "Player" and so the HalfSet class has a function named "Player" ("Player *Player()"). You need to rename one of these (probably changing HalfSet's Player() to getPlayer() or somesuch).</p>
|
<p>I had this error on my code I can't comprehend this</p>
<blockquote>
<p>A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.</p>
</blockquote>
<p>But this what I did so it fixed my error</p>
<p>previous code</p>
<pre><code>#include "a.h"
class System {
public:
car car; /*This line is problem, Can't declare object with same name as
class*/
};
</code></pre>
<p>Modified code</p>
<pre><code>#include "a.h"
class System {
public:
car Car; //Here is the difference, Just changed first letter of object
};
</code></pre>
| 35,825
|
<p>I'm using <a href="http://en.wikipedia.org/wiki/Windows_Script_Host#Usage" rel="noreferrer">WScript</a> to automate some tasks, by using WScript.Shell to call external programs.</p>
<p>However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.</p>
<p>I am using code like:</p>
<pre><code>ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
</code></pre>
<p>Is there a way to do this so it blocks until the shell executed program returns?</p>
|
<p>Turns out, that while loop is severe CPU hog :P</p>
<p>I found a better way:</p>
<pre><code>ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.Run ZipCommand,1,1
</code></pre>
<p>The last two arguments are Show window and Block Execution :)</p>
|
<p>If you use the "Exec" method, it returns a reference, so you can poll the "Status" property to determine when it is complete. Here is a sample from <a href="http://msdn.microsoft.com/en-us/library/ateytk4a(VS.85).aspx" rel="noreferrer">msdn</a>:</p>
<pre><code>Dim WshShell, oExec
Set WshShell = CreateObject("WScript.Shell")
Set oExec = WshShell.Exec(ZipCommand)
Do While oExec.Status = 0
WScript.Sleep 100
Loop
</code></pre>
| 7,315
|
<p>I have a table where I'm recording if a user has viewed an object at least once, hence:</p>
<pre><code> HasViewed
ObjectID number (FK to Object table)
UserId number (FK to Users table)
</code></pre>
<p>Both fields are NOT NULL and together form the Primary Key.</p>
<p>My question is, since I don't care how many times someone has viewed an object (after the first), I have two options for handling inserts.</p>
<ul>
<li>Do a SELECT count(*) ... and if no records are found, insert a new record.</li>
<li>Always just insert a record, and if it throws a DUP_VAL_ON_INDEX exceptions (indicating that there already was such a record), just ignore it.</li>
</ul>
<p>What's the downside of choosing the second option?</p>
<p>UPDATE:</p>
<p>I guess the best way to put it is : "Is the overhead caused by the exception worse than the overhead caused by the initial select?"</p>
|
<p>I would normally just insert and trap the DUP_VAL_ON_INDEX exception, as this is the simplest to code. This is more efficient than checking for existence before inserting. I don't consider doing this a "bad smell" (horrible phrase!) because the exception we handle is raised by Oracle - it's not like raising your own exceptions as a flow-control mechanism.</p>
<p>Thanks to Igor's comment I have now run two different benchamrks on this: (1) where all insert attempts except the first are duplicates, (2) where all inserts are not duplicates. Reality will lie somewhere between the two cases.</p>
<p>Note: tests performed on Oracle 10.2.0.3.0.</p>
<p><strong>Case 1: Mostly duplicates</strong></p>
<p>It seems that the most efficient approach (by a significant factor) is to check for existence WHILE inserting:</p>
<pre><code>prompt 1) Check DUP_VAL_ON_INDEX
begin
for i in 1..1000 loop
begin
insert into hasviewed values(7782,20);
exception
when dup_val_on_index then
null;
end;
end loop
rollback;
end;
/
prompt 2) Test if row exists before inserting
declare
dummy integer;
begin
for i in 1..1000 loop
select count(*) into dummy
from hasviewed
where objectid=7782 and userid=20;
if dummy = 0 then
insert into hasviewed values(7782,20);
end if;
end loop;
rollback;
end;
/
prompt 3) Test if row exists while inserting
begin
for i in 1..1000 loop
insert into hasviewed
select 7782,20 from dual
where not exists (select null
from hasviewed
where objectid=7782 and userid=20);
end loop;
rollback;
end;
/
</code></pre>
<p>Results (after running once to avoid parsing overheads):</p>
<pre><code>1) Check DUP_VAL_ON_INDEX
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.54
2) Test if row exists before inserting
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.59
3) Test if row exists while inserting
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.20
</code></pre>
<p><strong>Case 2: no duplicates</strong></p>
<pre><code>prompt 1) Check DUP_VAL_ON_INDEX
begin
for i in 1..1000 loop
begin
insert into hasviewed values(7782,i);
exception
when dup_val_on_index then
null;
end;
end loop
rollback;
end;
/
prompt 2) Test if row exists before inserting
declare
dummy integer;
begin
for i in 1..1000 loop
select count(*) into dummy
from hasviewed
where objectid=7782 and userid=i;
if dummy = 0 then
insert into hasviewed values(7782,i);
end if;
end loop;
rollback;
end;
/
prompt 3) Test if row exists while inserting
begin
for i in 1..1000 loop
insert into hasviewed
select 7782,i from dual
where not exists (select null
from hasviewed
where objectid=7782 and userid=i);
end loop;
rollback;
end;
/
</code></pre>
<p>Results:</p>
<pre><code>1) Check DUP_VAL_ON_INDEX
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.15
2) Test if row exists before inserting
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.76
3) Test if row exists while inserting
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.71
</code></pre>
<p>In this case DUP_VAL_ON_INDEX wins by a mile. Note the "select before insert" is the slowest in both cases.</p>
<p>So it appears that you should choose option 1 or 3 according to the relative likelihood of inserts being or not being duplicates. </p>
|
<p>Usually, exception handling is slower; however if it would happen only seldom, then you would avoid the overhead of the query.<br>
I think it mainly depends on the frequency of the exception, but if performance is important, I would suggest some benchmarking with both approaches.</p>
<p>Generally speaking, treating common events as exception is a bad smell; for this reason you could see also from another point of view.<br>
If it is an exception, then it should be treated as an exception - and your approach is correct.<br>
If it is a common event, then you should try to explicitly handle it - and then checking if the record is already inserted.</p>
| 45,672
|
<p>I'm doing some tests with nhibernate and I'm modifying batch_size to get bulk inserts.</p>
<p>I'm using mssql2005 and using the northwind db.
I created 1000 object and insert them to the database. I've changed the values of batch_size from 5 to 100 but found no change in the performance. I'm getting value of around 300ms. Using the sql profiler, I see that 1000 sql insert statements at the sever side. Please help.</p>
<h2>app.config</h2>
<pre><code> <property name="adonet.batch_size">10</property>
</code></pre>
<h2>Code</h2>
<pre><code> public bool MyTestAddition(IList<Supplier> SupplierList)
{
var SupplierList_ = SupplierList;
var stopwatch = new Stopwatch();
stopwatch.Start();
using (ISession session = dataManager.OpenSession())
{
int counter = 0;
using (ITransaction transaction = session.BeginTransaction())
{
foreach (var supplier in SupplierList_)
{
session.Save(supplier);
}
transaction.Commit();
}
}
stopwatch.Stop();
Console.WriteLine(string.Format("{0} milliseconds. {1} items added",
stopwatch.ElapsedMilliseconds,
SupplierList_.Count));
return true;
}
</code></pre>
|
<p>The following is a great post on batch processing in Hibernate, which is what NHibernate is based upon and closely follows:</p>
<p><a href="http://relation.to/Bloggers/BatchProcessingInHibernate" rel="nofollow noreferrer">http://relation.to/Bloggers/BatchProcessingInHibernate</a></p>
<p>As you can see, the suggested actions are to set a reasonable batch size in the config, which you have done, but to also call <code>session.flush()</code>and <code>session.clear()</code> every 20 or so records. </p>
<p>We have employed this method ourselves and can now create and save 1000+ objects in seconds.</p>
|
<p>A call to ITransaction.Commit will Flush your Session, effectively writing your changes to the database. You are calling Commit after every Save, so there will be an INSERT for each Supplier.</p>
<p>I'd try to call Commit after every 10 Suppliers or so, or maybe even at the end of your 1000 Suppliers!</p>
| 36,451
|
<p>Ok, what I'm trying to do is build a web app that allows students to visually organize their class calendar using drag and drop. but They have to be able to drag and drop to specific locations (when those classes are available), not just anywhere.</p>
<p>This would be a 'fixed week' calendar. I was considering using a table, but was wondering if anyone thought this might be an issue for the drag and drop and if you had suggestions for a better implementation. Would love to hear your thoughts. I'm a very visual thinker and know this sort of app would help me.</p>
<p>Alternatively, if you know of something like this already implemented which I can use, Let me know!</p>
|
<p>How about using <a href="http://dojotoolkit.org/" rel="nofollow noreferrer">Dojo toolkit</a> to implement the heavy lifting? They have a <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/drag-and-drop" rel="nofollow noreferrer">class</a> for it.</p>
<p>From this <a href="http://dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/drag-and-drop/simple-example" rel="nofollow noreferrer">example documentation</a>:</p>
<pre><code><body style="font-size: 12px;">
<h1>A Simple Example</h1>
<table><tbody><tr>
<td>
<!-- Create a source with two nodes -->
<div dojoType="dojo.dnd.Source" jsId="c1" class="source">
SOURCE
<div class="dojoDndItem" dndType="blue">
<div class="bluesquare">BLUE</div>
</div>
<div class="dojoDndItem" dndType="red,darkred">
<div class="redsquare">RED</div>
</div>
</div>
</td>
<td>
<!-- Create a target that accepts nodes of type red and blue. -->
<div dojoType="dojo.dnd.Target" jsId="c2" class="target" accept="blue,darkred">
TARGET
</div>
</td>
</tr><tbody/></table>
</code></pre>
<p>you can see if it fits your problem. Its pretty nice and clean.</p>
|
<p>jQuery has draggable <a href="http://docs.jquery.com/UI/Droppable/droppable#options" rel="nofollow noreferrer">droppable</a> classes to do what you need, haven't used them tho. </p>
<p>However i've built a javascript system to categorize mobile phone content using drag and drop quite successfully using <a href="http://openrico.org/" rel="nofollow noreferrer">openrico</a>, that was several years ago, now i would definately give jQuery a try..</p>
| 45,371
|
<p>I need to check all of my asp code to prevent SQL injection.</p>
<p>Should I check the session object, too?</p>
<p>How might a session be hijacked?</p>
<p>Thank you!!</p>
|
<p>Session can be hijacked. If I remember correctly, Classic ASP only support cookie-based session identifier. If someone were able to steal that cookie (wire-tap) then they can gain the same session as legitimate user.</p>
<p>Should you check Session Object too? that depends. If you can make sure that all the object stored in sessions is "safe" (input has been sanitized), then you can skip session object. If somewhere in your application you get data from unsafe source and put it in Session object, then you must check it as well.</p>
|
<p>Well, you only really need to secure user inputs. So the question you have to ask yourself is: "Did this data came from user input?" If so you must use sql parameters.</p>
<p>On a bigger scale, and considering that you have individual methods & classes to perform the data access, you should you sql parameters for every text parameter you provide to your sql. In this scenario sql parameters is not really necessary because if you receive a number as a method parameter there is no way it could have an sql injection.</p>
<p>However, when in doubt use sql parameters.</p>
| 45,856
|
<p>How do I create an index on a column in MySQL v 5.0 (myisam db engine) based upon the length of its value its a TEXT data type up to 7000 characters, do I have to add another column with the length of the first column?</p>
|
<p>Yes, as MySQL doesn't support function-based indexes (like <code>ADD INDEX myIndex(LENGTH(text)))</code>, you'll need a new int column and define a <a href="http://dev.mysql.com/doc/refman/5.1/en/create-trigger.html" rel="nofollow noreferrer">trigger</a> to auto-update it after inserts and updates.</p>
|
<p>Sounds like a good approach to me (sorry don't know mysql, but in oracle you could set a trigger so that when your main column is updated the "length" column gets automatically updated)</p>
| 10,997
|
<p>What JavaScript keywords (function names, variables, etc) are reserved?</p>
|
<p>Here is my poem, which includes all of the reserved keywords in JavaScript, and is dedicated to those who remain honest in the moment, and not just try to score:</p>
<pre class="lang-none prettyprint-override"><code>Let this long package float,
Goto private class if short.
While protected with debugger case,
Continue volatile interface.
Instanceof super synchronized throw,
Extends final export throws.
Try import double enum?
- False, boolean, abstract function,
Implements typeof transient break!
Void static, default do,
Switch int native new.
Else, delete null public var
In return for const, true, char
…Finally catch byte.
</code></pre>
|
<p>benc's answer is excellent, but for my two cents, I like the w3schools' page on this:</p>
<p><a href="http://www.w3schools.com/js/js_reserved.asp" rel="nofollow">http://www.w3schools.com/js/js_reserved.asp</a></p>
<p>In addition to listing the keywords reserved by the standard, it also has a long list of keywords you <em>should</em> avoid in certain contexts; for example, not using the name <code>alert</code> when writing code to be run in a browser. It helped me figure out why certain words were highlighting as keywords in my editor even though I knew they weren't keywords.</p>
| 4,585
|
<p>We have a 3D application that retrieves keyboard presses via the IDirectInputDevice8. Is there any way, when we retrive keyboard events via the win32 API winproc loop back that we can send these commands to the DirectInputDevice?</p>
|
<p>Windows polls the keyboard hardware behind the scenes. When key events happen, it adds the respective WM_* messages to your Windows message queue (with associated information on keyboard state). The <a href="http://en.wikipedia.org/wiki/Message_loop_in_Microsoft_Windows" rel="nofollow noreferrer">windows message pump</a> pulls those messages off the queue and processes them accordingly. The main benefit of this approach is that you really don't have to do a lot to get hold of the keyboard events (plus knowledge of the keyboard layout/hardware isn't required). The disadvantage is that it really isn't real-time.</p>
<p>Talking to the Keyboard via DirectInput is actually similar, but it's up to you to do the polling. Usually, you use DirectInput to set up a keyboard device, and then every time you run your update loop, you <strong>poll</strong> the state of the keyboard using <a href="http://msdn.microsoft.com/en-us/library/bb205968.aspx" rel="nofollow noreferrer">GetDeviceState()</a>. It is up to you to keep track of the state of the keyboard between polls. The best thing to do is to create an object that wraps up this functionality, and perhaps fires events/callbacks or creates a command entry in a queue at the appropriate times so that it's nicer to work with. The advantage of this method is speed as you're talking to the hardware directly and can invoke updates instantly. The disadvantage is that you have to do this stuff manually which takes a bit of time to set up and get right.</p>
<p>Check out <a href="http://www.gamedev.net/reference/articles/article1607.asp" rel="nofollow noreferrer">this example</a> of how to use DirectInput to query the keyboard.</p>
<p>So there are a few answers to your question:</p>
<ol>
<li>If you have the WM_* messages already, why not just invoke the code that the DirectInput handling would invoke, hence giving you the same functionality?</li>
<li>DirectInput, via polling, gives you the same information that Windows is giving you via WM_* messages. So you don't need to convert, or try to map one to the other. Just check the state of the keys and handle the cases where the state changes.</li>
<li>Choose one method and ditch the other. They both do the same thing. I'd recommend using DirectInput if you want speed and responsiveness. If that's not so important, use the WM_* messages.</li>
</ol>
<p>I hope that helps. Good luck!</p>
|
<p>The wndproc will is sent a combination of these messages on keyboard events:</p>
<pre><code>WM_SYSKEYDOWN
WM_SYSKEYUP
WM_KEYDOWN
WM_KEYUP
WM_CHAR
</code></pre>
| 29,536
|
<p>I have a table in lua with some data.</p>
<pre><code>sometable = {
{name = "bob", something = "foo"},
{name = "greg", something = "bar"}
}
</code></pre>
<p>I then want to loop through the table and assign a number to each name as a variable. New to lua and tried it like this.</p>
<pre><code>for i,t in ipairs(sometable) do
t.name = i
end
</code></pre>
<p>I was then assuming print("name1", bob) would give me name1 = 1. Right now I'm getting nil. So I'm back to my ugly static list of variables till some kind soul tells me how I'm an idiot.</p>
|
<pre class="lang-lua prettyprint-override"><code>> sometable = {{name = "bob", something = "foo"},{name = "greg", something = "bar"}}
> for i,t in ipairs(sometable) do t[t.name] = i end
> for i,t in ipairs(sometable) do for j,u in pairs (t) do print (j,u) end end
name bob
something foo
bob 1
greg 2
something bar
name greg
> return sometable[1].bob
1>
</code></pre>
|
<p>The <a href="http://www.lua.org/manual/5.1/manual.html#5.1" rel="nofollow noreferrer">ipairs</a> function will iterate only through numerically indexed tables in ascending order.</p>
<p>What you want to use is the pairs function. It will iterate over every key in the table, no matter what type it is.</p>
| 34,132
|
<p>I have an application that tracks high scores in a game. </p>
<p>I have a <strong>user_scores</strong> table that maps a user_id to a score.</p>
<p>I need to return the 5 highest scores, but only 1 high score for any <em>specific</em> user.</p>
<p>So if user X has the 5 highest scores on a purely numerical basis, I simply return the highest one and then the next 4 user scores.</p>
<p>I have tried to use:</p>
<pre><code>SELECT user_id, score
FROM user_scores
ORDER BY score DESC
GROUP BY user_id
LIMIT 5
</code></pre>
<p>But it seems that MySQL drops any user_id with more than 1 score. </p>
|
<p>This should work:</p>
<pre><code>SELECT user_id, MAX(score)
FROM user_scores
GROUP BY user_id
ORDER BY MAX(score) DESC
LIMIT 5
</code></pre>
|
<p>You can't group by without a summary-function (SUM, COUNT, etc.)</p>
<p>The GROUP BY clause says how to group the SUMs or COUNTs.</p>
<p>If you simply want to break the long list into bunches with a common value, that's not SQL. That's what your application has to do.</p>
| 14,416
|
<p>I'm interested in grabbing the EPG data from DVB-T streams. Does anyone know of any C libraries or an alternative means of getting the data?</p>
|
<p>tv_grab_dvb can do this. See the <a href="http://www.darkskiez.co.uk/svn/tv_grab_dvb/trunk/" rel="nofollow noreferrer">subversion repository</a> for sources.</p>
<p>tv_grab_dvb is made to work with the stream grabbed from the DVB-T card using <a href="http://sourceforge.net/projects/dvbtools/" rel="nofollow noreferrer">dvbtools</a> on Linux, but it may be portable to other platforms - I think it just works with the raw data from the stream.</p>
|
<p>...a new answer to an old question:</p>
<p>I wrote a utility called <code>dvbtee</code> that can be used as a c++ library, a cross-platform command line utility, or a node.js module.</p>
<p>(despite it being a c++ library, one could still link to it from c code)</p>
<p>The command line utility will parse your streams and output the EPG, depending on the arguments you specify, it can generate plain text or a JSON block of data.</p>
<p><a href="http://mkrufky.github.io/libdvbtee" rel="nofollow noreferrer">dvbtee: a digital television streamer / parser / service information aggregator supporting various interfaces including telnet CLI & http control</a></p>
<p>The node.js module will emit events containing the PSIP table data (along with EPG info)</p>
<p><a href="https://www.npmjs.com/package/dvbtee" rel="nofollow noreferrer">node-dvbtee: MPEG2 transport stream parser for Node.js with support for television broadcast PSIP tables</a></p>
| 8,146
|
<p>When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue.</p>
<p>I'm currently <em>fixing</em> the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that.</p>
<p>I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.</p>
|
<pre><code>chdir(dirname(__FILE__));
</code></pre>
|
<p>You can use <code>__FILE__</code> to get the full absolute path to the executing file itself:</p>
<pre><code><?php
echo "I'm here: ".__FILE__."\n";
?>
</code></pre>
<p>See <a href="http://fi.php.net/language.constants.predefined" rel="nofollow noreferrer">the documentation</a> for more info.</p>
| 23,343
|
<p>I'm interested in finding out what people would consider the most useful data structures to know in programming. What data structure do you find yourself using all the time? </p>
<p>Answers to this post should help new programmers interested in finding a useful data structure for their problem. Answers should probably include the data structure, information about it or a relevant link, the situation it is being used in and why it is a good choice for this problem (e.g ideal computation complexities, simplicity and understanding etc.)</p>
<p>Each answer should be about one data structure only.</p>
<p>Thanks for any pearls of wisdom and experience people can share.</p>
|
<p>One of the data structures I use the most (beyond vectors, of course) is the Hashtable.
Its about the only choise if you need to be able to search large quantities of data in O(1) time, that means the time to search does not grow as the size of the collection grows.</p>
<p>The catch is that the insertion and deletion times are larger than in other data strutures, and you need to have some sort of key with which to search the collection. Every element must have a key.
The algorithm takes the key of each element and computes an hash code that indicates the slot in the hash table in which to search.
Then depending on the implementation it either follows a list of items that fell on that bucket to find your item or it searches nearby buckets.
The size of the hastable is determinant to the efficiency of the hash that is quite affected by the ammount of collisions of hash codes between keys.</p>
<p>Use it whenever you need a map and the expected number of elements of the map exceed about 10. Its a bit more more memory intensive than other structures since it needs lots of unused slots in the table to be efficient.</p>
<p>C# has a great implementation of it with <code>Dictionary<keytype, valuetype></code> and even has a HybridDictionary that decides internally when to use a hashtable or a vector.
Any good programming book describes it but you will be well served by wikipedia:
<a href="http://en.wikipedia.org/wiki/Hashtable" rel="noreferrer">http://en.wikipedia.org/wiki/Hashtable</a></p>
|
<p>This post is way too vague. There are countless data structures: arrays, dictionaries, etc. Each data structure can be used to solve different problems.</p>
<p>It would be much more productive to ask for DS for a specific problem.</p>
| 17,581
|
<p>Is there anything out there that for .NET that can generate UML diagrams from code. Preferably an addin for Visual Studio. Starting work on a mature project that has little architectural documentation can be painful at first. Eventually you get the ins and outs of the code but helping to see how the code all fits together from the get go would be wonderful.</p>
|
<p>Visual Studio 2010 Ultimate supports UML class, sequence, component, use case, and activity diagrams. It also supports creating sequence, dependency graphs, and layer diagrams from code. Regarding your question about generating UML diagrams from code, there's a response here in the VS Architecture & Modeling tools forum: <a href="http://social.msdn.microsoft.com/Forums/en-US/vsarch/thread/a1ee9393-8f9b-45f2-8277-6e49346a119a" rel="nofollow noreferrer">Is it possible to reverse engineer C# code into an UML Class Diagram?</a></p>
<p>Other tools include Architecture Explorer, which lets you browse and explore your solution.</p>
<p>For more info, see the following links:</p>
<p>To download the RC release, visit: <a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=457bab91-5eb2-4b36-b0f4-d6f34683c62a" rel="nofollow noreferrer">Microsoft Visual Studio 2010 Ultimate RC</a> </p>
<p>To see the RC documentation, see <a href="http://msdn.microsoft.com/en-us/library/57b85fsc%28VS.100%29.aspx" rel="nofollow noreferrer">Modeling the Application</a>.</p>
<p>To discuss these tools, visit the <a href="http://social.msdn.microsoft.com/Forums/en-US/vsarch/threads" rel="nofollow noreferrer">Visual Studio 2010 Architectural Discovery & Modeling Tools</a> forum.</p>
|
<p>Class diagram doesn't always work. I often find it wont display the classes for some reason. Pen & pencil or talking with people who work on the project is what I have to rely on.</p>
| 11,752
|
<p>I have looked over the Repository pattern and I recognized some ideas that I was using in the past which made me feel well.</p>
<p>However now I would like to write an application that would use this pattern <strong>BUT I WOULD LIKE TO HAVE THE ENTITY CLASSES DECOUPLED</strong> from the repository provider.</p>
<p>I would create several assemblies :</p>
<ol>
<li>an "Interfaces" assembly which would host common interfaces including the IRepository interface</li>
<li>an "Entities" assembly which would host the entity classes such as Product, User, Order and so on. This assembly would be referenced by the "Interfaces" assembly since some methods would return such types or arrays of them. Also it would be referenced by the main application assembly (such as the Web Application)</li>
<li>one or more Repository provider assembly/assemblies. Each would include (at least) a class that implements the IRepository interface and it would work with a certain Data Store. Data stores could include an SQL Server, an Oracle server, MySQL, XML files, Web / WCF services and so on.</li>
</ol>
<p>Studying LINQ to SQL which looks very productive in terms of time taken to implement all seems well until I discover the deep dependency between the generated classes and the CustomDataContext class.</p>
<p>How can I use LINQ to SQL in such a scenario?</p>
|
<p>I don't know if this is exactly what you want, but you may want to take a look at Rob Conery's MVC Storefront code. He uses a variant of the repository pattern with a linq provider. He maps the LINQ to Sql objects to domain objects and then returns the domain objects from the repository provider to a service layer which wraps the provider allowing him to work some logic on the data returned before it hits the business layer. </p>
<p><a href="http://blog.wekeroad.com/mvc-storefront/" rel="nofollow noreferrer">MVC Storefront Webcasts</a><br>
<a href="http://www.codeplex.com/mvcsamples/SourceControl/ListDownloadableCommits.aspx" rel="nofollow noreferrer">Code</a></p>
<p>To me it sounds like you want the providers to return DTOs and then you want to map the DTOs to the domain objects in the repository/service layer. If this is the case you could map your LINQ to SQL provider to the DTOs, have it return them, then map the DTOs to domain objects in the repository/service layer. This should work just fine, but it may become tedious as you now would have 2 mapping layers.</p>
<p>In this case you would have:
ProductService, which takes an IProductRepository. It evokes methods on the IProductRepository to get back your DTOs. It then maps the DTOs to the real business objects and returns them to the calling code. </p>
|
<p>Not exactly the same scenario, but I'm working to create a custom tool that based on a XML file will generate an OO model. My approach is to use LINQ to SQL behind the scene and since I'm generating the code automatically it would be easy to use another mechanism for let's say MySQL data source. Since it's not supported by LINQ to SQL you will have to write the data access code manually, but the client code that will use the OO model will change in any way.</p>
| 28,425
|
<p>In Team Foundation Server is there a way to have work items in one project linked to other projects so they show up in the reports in both. We are thinking about keeping release engineering items in their own project and want them linked to the project they are actaully for as well. Is this possible? So for instance I would create the item under release engineering assign it to an engineer and then link it to Product X so it showed up as a work item for Project X as well.</p>
|
<p>This is possible in TFS 2010 at least: <a href="https://stackoverflow.com/questions/4410083/link-tfs-work-item-to-different-project">link tfs work item to different project</a></p>
<p>Not sure on the effects on reporting though.</p>
|
<p>Not out of the box as projects are discrete. However there is nothing to stop you from writing against the API to fulfill this need, although this would take some considerable work. </p>
<p>Now for the good news. If you keep your eyes <a href="http://blogs.msdn.com/bharry/" rel="nofollow noreferrer">here</a>, you may find the answer in time. As I see cross project reports are planned in <a href="http://blogs.msdn.com/bharry/archive/2008/09/29/shining-the-light-on-rosario.aspx" rel="nofollow noreferrer">Rosario</a></p>
| 29,867
|
<p>I've found how to sort query results by a given field in a Lucene.Net index instead of by score; all it takes is a field that is indexed but not tokenized. However, what I haven't been able to figure out is how to sort that field while ignoring stop words such as "a" and "the", so that the following book titles, for example, would sort in ascending order like so:</p>
<ol>
<li>The Cat in the Hat</li>
<li>Horton Hears a Who</li>
</ol>
<p>Is such a thing possible, and if yes, how?</p>
<p>I'm using Lucene.Net 2.3.1.2.</p>
|
<p>I wrap the results returned by Lucene into my own collection of custom objects. Then I can populate it with extra info/context information (and use things like the highlighter class to pull out a snippet of the matches), plus add paging. If you took a similar route you could create a "result" class/object, add something like a SortBy property and grab whatever field you wanted to sort by, strip out any stop words, then save it in this property. Now just sort the collection based on that property instead.</p>
|
<p>When you create your index, create a field that only contains the words you wish to sort on, then when retrieving, sort on that field but display the full title.</p>
| 9,173
|
<p>Here's my first question at SO.</p>
<p>I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. </p>
<p>The problem is the applications is <strong>very slow</strong>.</p>
<p>How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code.</p>
<p>I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. </p>
<p>Thoughts?</p>
|
<p>I've used <a href="http://www.xdebug.org/docs/profiler" rel="noreferrer">XDebug profiling</a> recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ). </p>
|
<p>We use Zend Development Environment (windows). We resolved a memory usage spike yesterday by stepping through the debugger while running Process Explorer to watch the memory/cpu/disk activity as each line was executed. </p>
<p>Process Explorer: <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx</a>. </p>
<p>ZDE includes a basic performance profiler that can show time spent in each function call during page requests.</p>
| 7,955
|
<p>To save network traffic I'd like to compress my data. The only trick is that I the client is a c application and the server is php. I'm looking for an open source compression library that's available for both c and php.</p>
<p>I guess I could write an external c application to decompress my data, but I'm trying to avoid spawning extra processes on the server.</p>
<p>If you know of any, please post it!</p>
|
<p><A HREF="http://www.zlib.net/" rel="nofollow noreferrer">Zlib</A> provides C APIs, and is part of the PHP functional API as well.</p>
|
<p><a href="http://www.zlib.net/" rel="nofollow noreferrer">ZLIB</a></p>
<p><a href="http://www.php.net/zlib" rel="nofollow noreferrer">Here's the page</a> on accessing zlib from PHP.</p>
| 15,155
|
<p>I know how to do a regular php mysql search and display the results. However, because of the nature of what I'm trying to accomplish I need to be able to sort by relevancy. Let me explain this better:</p>
<p>Normal Query "apple iphone applications" will search the database using %apple iphone application%, but if there aren't records which display that phrase in that exact order the search will produce nothing.</p>
<p>What I basically need to do is search for 'apple', 'iphone' and 'applications' all separately and then merge the results into one, and then I need to grade the relevancy by how many instances of the word are found in the records. For example if I did what I wanted to do and it returned them following:</p>
<pre><code>Iphone Applications From Apple
Apple Make The Best Apple Iphone Applications
Iphone Applications
</code></pre>
<p>They would rank as follows:</p>
<pre><code>Apple Make The Best Apple Iphone Applications
Iphone Applications From Apple
Iphone Applications
</code></pre>
<p>Because of how many instances of the search terms are found. See highlighted:</p>
<pre><code>[Apple] Make The Best [Apple] [Iphone] [Applications]
[Iphone] [Applications] From [Apple]
[Iphone] [Applications]
</code></pre>
<p>I hope I have explained this well enough and I would be extremely grateful if anyone could give me any pointers.</p>
|
<p>take a look at the <a href="http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html" rel="noreferrer">MySQL FULLTEXT search functions</a>,
These should automatically return results by relevancy, and give you much more control over your searches</p>
<p>The only potential issue with using fulltext indexes is that they aren't supported by InnoDB tables.</p>
|
<p>I Don't What exactly you want but the following code definitely work for you.</p>
<pre><code>SELECT ("some text here" or `column_name`) RLIKE "Apple|Iphone|Application" AS Result ORDER BY Result DESC;
</code></pre>
<p>Separate all words with Bar(|) but results will be 1 or 0 founded or not resp.
If you want to get founded rows see below.</p>
<pre><code>SELECT * FROM "table_name" WHERE `column_name` RLIKE "Apple|Iphone|Application";
</code></pre>
| 44,768
|
<p>I have an existing standalone application which is going to be extended by a 3rd-party, using a network protocol. The capabilities are already implemented, all I need is to expose them to the outside.</p>
<p>Assuming the transport protocol is already chosen (UDP), are there any resources that will help me to design my application protocol?</p>
<p>There seems to be a lot of information about software design, but not on protocol design.
I've already looked at <a href="http://www.faqs.org/docs/artu/ch05s03.html" rel="noreferrer">Application Protocol Design</a>.</p>
|
<p>See <a href="http://xmpp.org/extensions/xep-0134.html#guidelines" rel="nofollow noreferrer">Jabber protocols design guidelines</a> and <a href="https://www.rfc-editor.org/rfc/rfc4101" rel="nofollow noreferrer">RFC 4101</a>. Although it is aimed at making RFCs more easy to understand to reviewers, this RFC provides some interesting advices.</p>
|
<p>If you do not want to build your protocol from ground up, you should take a look at <a href="http://en.wikipedia.org/wiki/SOAP_(protocol)" rel="nofollow noreferrer">SOAP</a>. Support varies for different programming languages, but cross language communication is explicitly encouraged.</p>
<p>Unfortunately UDP and SOAP seem to have stuck in its infancy, HTTP is most commonly used.</p>
| 35,003
|
<p>Do I need to register new extension types with Apple before I release an application that would create them on OS X?</p>
|
<p>No, there's no need to register extensions.</p>
|
<p>As a follow up, there is a little more information in the FAQs at the Apple Developer Connection (ADC) website:</p>
<p><a href="http://developer.apple.com/faq/datatype.html" rel="nofollow noreferrer">http://developer.apple.com/faq/datatype.html</a></p>
| 6,197
|
<p>What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?</p>
<p>Thanks!</p>
|
<p>Nettuts has a great introduction to web-developement for iPhone. You find it <a href="http://nettuts.com/misc/learn-how-to-develop-for-the-iphone/" rel="nofollow noreferrer">here</a></p>
<p>This is the specific code you asked for (taken from that article):</p>
<pre><code><!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->
<!--
place iPhone code in here
-->
<!--#else -->
<!--
place standard code to be used by non iphone browser.
-->
<!--#endif -->
</code></pre>
|
<p>Better Solution:</p>
<pre><code>*
(NSString *)flattenHTML:(NSString *)html {
NSScanner *theScanner; NSString *text = nil;
theScanner = [NSScanner scannerWithString:html];
while ([theScanner isAtEnd] == NO) {
// find start of tag
[theScanner scanUpToString:@"<" intoString:NULL] ;
// find end of tag
[theScanner scanUpToString:@">" intoString:&text] ;
// replace the found tag with a space
//(you can filter multi-spaces out later if you wish)
html = [html stringByReplacingOccurrencesOfString:
[ NSString stringWithFormat:@"%@>", text]
withString:@" "];
} // while //
return html;
</code></pre>
<p>}</p>
| 7,579
|
<p>I'm looking at maybe moving from an older AMD64 to a new Intel dual-core which is 32 bit. Installation isn't a problem but can I transfer all the installed apps? I haven't been
able to find anything so far on Google except where the migration is to a similar platform and file-system. I won't change the filesystem but the platform will be different. Is there something on the lines of the "World" file in Gentoo?</p>
|
<p>You can save your list of packages easily: see "man dpkg" and search for --set-selections and --get-selections.</p>
<p>The basic of it, though is that to save the list of packages:</p>
<p><code>dpkg --get-selections > package_list</code></p>
<p>To restore that list on another system:</p>
<p><code>cat package_list | sudo dpkg --set-selections && sudo apt-get dselect-upgrade</code></p>
<p>Moving across architectures means that there will be some packages unavailable. They will be ignored; for example, <code>ia32-libs</code> will not be installable on a 32-bit system. That selection will be ignored if you're moving from x86-64 to x86.</p>
|
<p>The best way I can think of to go about this is to back up the list of installed packages on your current system and then use that list to set what packages to install on the new system. General instructions on how to backup and restore your package selections:</p>
<h3>Install tools</h3>
<pre><code>sudo apt-get install dselect
</code></pre>
<h3>Backup Package List</h3>
<pre><code>dpkg --get-selections | grep -v deinstall > ubuntu-files
</code></pre>
<h3>Restore Package Selections</h3>
<pre><code>sudo apt-get update
sudo apt-get dist-upgrade
dpkg --set-selections < ubuntu-files
sudo dselect
</code></pre>
<p>This will open up a dselect session. Type ‘I‘ and allow dselect to
install of the the packages listed in your ubuntu-files document.
When it’s finished, type ‘Q‘ and hit the ENTER key to exit dselect.</p>
| 22,735
|
<p>I'm working on a school project and I'm getting some weird errors from Xcode. I'm using TextMate's Command+R function to compile the project. Compilation seems to work okay but linking fails with an error message I don't understand. </p>
<p>ld output:</p>
<blockquote>
<p>ld: duplicate symbol text_field(std::basic_istream >&)in /path/final/build/final.build/Release/final.build/Objects-normal/ppc/generics.o and /path/final/build/final.build/Release/final.build/Objects-normal/ppc/main.o
collect2: ld returned 1 exit status</p>
</blockquote>
<p>Below is my file io_functions.cpp This is the only declaration of text_field in the entire project. </p>
<pre><code>#include <string>
#include <iostream>
#include <iomanip>
using namespace std;
#ifndef ENDF
#define ENDF '|'
#define ENDR '\n'
/**
reads one field from a given input stream
Usage: var = text_field(in)
*/
string text_field(istream &in){
string s;
getline(in, s, ENDF);
return s;
}
long long_field(istream &in){
return atol(text_field(in).c_str());
}
int int_field(istream &in){
return atoi(text_field(in).c_str());
}
double double_field(istream &in){
return atof(text_field(in).c_str());
}
#endif
</code></pre>
<p>What is going wrong? For a number of reasons I don't want to post my project's entire source. </p>
|
<p>My first thought was that you're including it twice on the linker command but it appears to be complaining about having the same function in <code>main.o</code> and <code>generics.o</code>.</p>
<p>So it looks like you're including the <code>io_functions.cpp</code> file into the <code>main.cpp</code> and <code>generics.cpp</code> which is a bad idea at the best of times.</p>
<p>You should have a header file (e.g., <code>io_functions.h</code>) that specifies everything contained in <code>io_functions.cpp</code> and include that <em>header</em> file into the other two.</p>
|
<p>Use "inline" keyword decorate duplicate method </p>
<pre><code>inline string text_field(istream &in)
</code></pre>
<p>Inline functions are actual functions whose copy of the function body are injected directly into each place the function is called.</p>
<p>For details, please see the <a href="https://chunminchang.github.io/blog/post/how-to-avoid-duplicate-symbols-when-compiling" rel="nofollow noreferrer">article</a></p>
| 35,812
|
<p>Once I've created a variable in the immediate window in C# (VS2008), is there any way to delete it so I can create a new variable with the same name but a different type? Apart from restarting the program that is.</p>
<p>The reason would be to keep the immediate window's namespace clean, since it's difficult to keep track of variable declarations once they scroll off the visible part of the window.</p>
|
<p>I don't think it is possible to do what you are asking.</p>
|
<p>You can do something similar to the following:</p>
<pre><code>public void LolFunction() {
{
int main = 0;
Console.Writeline(main);
}
{
string main = "Roflstring";
Console.Writeline(main);
}
}
</code></pre>
| 14,633
|
<p>Is there a way to add an attribute to an xml node (which I have the xpath of) using nant?
Tried xmlpoke but it looks like it can only update existing attributes.</p>
<p>thanks.</p>
|
<p>XmlPoke will definitely not work because the xpath must match something in the first place to be able to replace it.</p>
<p>The only way I know of doing this is to create your own task that would allow you to add data to an xml file. These new tasks can either be build separately and added to NAnt by copying dlls into NAnt\bin folder, or by extending NAnt directly from your build files</p>
<p>The information to get you started is found on <a href="http://nant.sourceforge.net/release/0.85/help/tasks/script.html" rel="nofollow noreferrer"><script/> Task</a></p>
<p>If you happen to make this task generic enough, it might be good to try to submit it to <a href="http://nantcontrib.sourceforge.net/" rel="nofollow noreferrer">NAntContrib</a> so everyone benefits.</p>
|
<p>XmlPoke will definitely not work because the xpath must match something in the first place to be able to replace it.</p>
<p>The only way I know of doing this is to create your own task that would allow you to add data to an xml file. These new tasks can either be build separately and added to NAnt by copying dlls into NAnt\bin folder, or by extending NAnt directly from your build files</p>
<p>The information to get you started is found on <a href="http://nant.sourceforge.net/release/0.85/help/tasks/script.html" rel="nofollow noreferrer"><script/> Task</a></p>
<p>If you happen to make this task generic enough, it might be good to try to submit it to <a href="http://nantcontrib.sourceforge.net/" rel="nofollow noreferrer">NAntContrib</a> so everyone benefits.</p>
| 46,814
|
<p>In an interview for a SQL DBA position a while back, I mentioned I prefer the SQL 2005 Management Studio app vs. the old 2000 versions of Enterprise Manager / Query Analyzer. The DBA who was interviewing me said that they had experienced some sort of database corruption in their 2000 databases when making changes from the 2005 MS, so they always use Enterprise Manager now. </p>
<p>He was a bit vague, but I got the impression he was talking about some sort of corruption experienced when making server-wide or database-level setting changes, and not just routine SQL updates or something.</p>
<p>Anyone heard of anything like this? I didn't end up taking that position, so I can't follow up to get more info.</p>
|
<p>It sounds like he was just was using that as an excuse for lack of experience with SQL 2005 Management Studio. DBAs hate change.</p>
|
<p>I have never encountered this, in almost three years of using SQL Management Studio 2005 to manage SQL 2000 databases. There are a few tasks I still bounce back into EntMan for, but I've never had a database encounter even the minutest bit of corruption. (And background: As a consultant, I'm managing about 45 different databases for both client and internal projects; most are heavily hit, and only about a dozen are SQL2005 databases.)</p>
| 32,444
|
<p>I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.</p>
<p>How can I configure MySQL to store it in the UTC/GMT timezone?</p>
<p>I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...</p>
|
<p>The short answer is:</p>
<ul>
<li>add "default-time-zone=utc" to my.cnf</li>
<li>in your code, always "think" in UTC, except when displaying dates for your users</li>
<li><p>when getting/setting dates or timestamps with JDBC, always use the Calendar parameter, set to UTC:</p>
<p>resultset.getTimestamp("my_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));</p></li>
<li>either synchronize your servers with NTP, or rely only on the database server to tell you what time it is.</li>
</ul>
<hr>
<p>The long answer is this:</p>
<p>When dealing with dates and timezones in any database and with any client code, I usually recommend the following policy:</p>
<ol>
<li><p><strong>Configure your database to use UTC timezone</strong>, instead of using the server's local timezone (unless it is UTC of course).</p>
<ul>
<li><p>How to do so depends on your database server. Instructions for MySQL can be found here: <a href="http://dev.mysql.com/doc/refman/5.0/en/time-zone-support.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/time-zone-support.html</a>. Basically you need to write this in my.cnf: default-time-zone=utc</p></li>
<li><p>This way you can host your database servers anywhere, change your hosting location easily, and more generally manipulate dates on your servers without any ambiguity.</p></li>
<li>If you really prefer to use a local timezone, I recommend at least turning off Daylight Saving Time, because having ambiguous dates in your database can be a real nightmare.
<ul>
<li><em>For example, if you are building a telephony service and you are using Daylight Saving Time on your database server then you are asking for trouble: there will be no way to tell whether a customer who called from "2008-10-26 02:30:00" to "2008-10-26 02:35:00" actually called for 5 minutes or for 1 hour and 5 minutes (supposing Daylight Saving occurred on Oct. 26th at 3am)!</em></li>
</ul></li>
</ul></li>
<li><p><strong>Inside your application code, always use UTC dates, except when displaying dates to your users.</strong></p>
<ul>
<li>In Java, when reading from the database, always use:</li>
</ul>
<p>Timestamp myDate = resultSet.getTimestamp("my_date", Calendar.getInstance(TimeZone.getTimeZone("UTC")));</p>
<ul>
<li>If you do not do this, the timestamp will be assumed to be in your local TimeZone, instead of UTC.</li>
</ul></li>
<li><p><strong>Synchronize your servers or only rely on the database server's time</strong></p>
<ul>
<li><p>If you have your Web server on one server (or more) and your database server on some other server, then I strongly recommend you synchronize their clocks with NTP.</p></li>
<li><p>OR, only rely on one server to tell you what time it is. Usually, the database server is the best one to ask for time. In other words, avoid code such as this:</p></li>
</ul>
<p>preparedStatement = connection.prepareStatement("UPDATE my_table SET my_time = ? WHERE [...]");<br>
java.util.Date now = new java.util.Date(); // local time! :-(<br>
preparedStatement.setTimestamp(1, new Timestamp(now.getTime()));<br>
int result = preparedStatement.execute();</p>
<ul>
<li>Instead, rely on the database server's time:</li>
</ul>
<p>preparedStatement = connection.prepareStatement("UPDATE my_table SET my_time = NOW() WHERE [...]");<br>
int result = preparedStatement.execute();</p></li>
</ol>
<p>Hope this helps! :-)</p>
|
<p>Well, if we're talking about using <code>PreparedStatement</code>s, there's a <a href="http://java.sun.com/javase/6/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date,%20java.util.Calendar)" rel="nofollow noreferrer">form of setDate</a> where you can pass in a Calendar set to a particular time zone.</p>
<p>For instance, if you have a PreparedStatement named stmt, a Date named date, and assuming the date is the second parameter:</p>
<pre><code>stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone("GMT")));
</code></pre>
<p>The best part is, even if GMT is an invalid time zone name, it still returns the GMT time zone because of the default behavior of getTimeZone.</p>
| 39,839
|
<p>As a follow-up to <a href="https://stackoverflow.com/questions/199518/how-to-programatically-add-mapped-network-passwords-winxp">this</a> question I am hoping someone can help with the <a href="http://msdn.microsoft.com/en-us/library/aa374794(VS.85).aspx" rel="nofollow noreferrer">CredEnumerate</a> API. </p>
<p>As I understand from the documentation the PCREDENTIALS out parameter is a "pointer to an array of pointers to credentials". I am able to successfully call the CredEnumerate API using C# but I am not sure of how to convert the PCREDENTIALS into something useful (like a list of credentials).</p>
<p>Edit: Here's the code I am using:</p>
<pre><code> int count = 0;
IntPtr pCredentials = IntPtr.Zero;
bool ret = false;
ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
IntPtr[] credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int i = 0; i < count; i++)
{
p = new IntPtr(p.ToInt32() + i);
credentials[i] = Marshal.ReadIntPtr(p);
}
List<Credential> creds = new List<Credential>(credentials.Length);
foreach (IntPtr ptr in credentials)
{
creds.Add((Credential)Marshal.PtrToStructure(ptr, typeof(Credential)));
}
}
</code></pre>
<p>Unfortunately, while this works for the first credential in the array—it gets generated and added to the list correctly—subsequent array items bomb at Marshal.PtrToStructure with the following error:</p>
<p><em>Attempted to read or write protected memory. This is often an indication that other memory is corrupt.</em></p>
<p>Any ideas? Anyone? Bueller?</p>
|
<p>You need to dereference the pointer to the array to get the array, then for each item in the array you will need to dereference the item to get the <code>PCREDENTIALS</code> instance.</p>
<p>I found <a href="http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic33651.aspx" rel="nofollow noreferrer">this post with some example code</a> for performing what you want to do:</p>
<pre><code>[DllImport("advapi32", SetLastError = true, CharSet=CharSet.Unicode)]
static extern bool CredEnumerate(string filter, int flag, out int count, out IntPtr
pCredentials);
</code></pre>
<p>...</p>
<pre><code>int count = 0;
IntPtr pCredentials = IntPtr.Zero;
IntPtr[] credentials = null;
bool ret = CredEnumerate(null, 0, out count, out pCredentials);
if (ret != false)
{
credentials = new IntPtr[count];
IntPtr p = pCredentials;
for (int n = 0; n < count; n++)
{
credentials[n] = Marshal.ReadIntPtr(pCredentials,
n * Marshal.SizeOf(typeof(IntPtr)));
}
}
else
// failed....
</code></pre>
<p>Then for each pointer you'll need to use <code>Marshal.PtrToStructure</code> to dereference the pointer into a <code>PCREDENTIALS</code> struct instance (sorry I cannot find the typedef for <code>PCREDENTIALS</code> anywhere, I'll assume you have it - and if you do don't forget the correct MarshalAs attributes and StructLayout attribute when you do define it):</p>
<pre><code>// assuming you have declared struct PCREDENTIALS
var creds = new List<PCREDENTIALS>(credentials.Length);
foreach (var ptr in credentials)
{
creds.Add((PCREDENTIALS)Marshal.PtrToStructure(ptr, typeof(PCREDENTIALS)));
}
</code></pre>
<p>You would obviously want to combine the example and <code>PtrToStructure</code> code for optimal results but I wanted to leave the integrity of the example intact.</p>
|
<p>You also need to calculate 'IntPtr p' correctly the code above is missing that and it will only fetch the 1st structure.</p>
<p>Th following code will get all structures in 'IntPtr pCredentials'</p>
<pre><code>int count;
IntPtr pCredentials;
if (CredEnumerate(filter, 0, out count, out pCredentials) != 0)
{
m_list = new List<PCREDENTIALS >(count);
int sz = Marshal.SizeOf(pCredentials);
for (int index = 0; index < count; index++)
{
IntPtr p = new IntPtr((sz == 4 ? pCredentials.ToInt32() : pCredentials.ToInt64()) + index * sz);
m_list.Add((PCREDENTIALS)Marshal.PtrToStructure(p, typeof(PCREDENTIALS)));
}
}
</code></pre>
| 31,813
|
<p>I have a <strong>MS Access</strong> form with a <strong>Datasheet</strong> subform.<br>
Using code, I change the <strong>ColumnHidden</strong> property of various of its columns.
But, when I close the form, I'm asked whether to save the table layout of the Datasheet's table.</p>
<ul>
<li>How can I stop the form from asking the user to same the table layout continually?</li>
<li>Do I have no choice but to change the Datasheet to a regular subform?</li>
</ul>
|
<p>If you are always hiding the same columns - create a query that only has the columns you want displayed and use that as the source of your subform.</p>
<p>If you still need some hidden fields (child keys, etc.) you will have to create a regular form. It's not too bad:</p>
<ul>
<li>just base it on your table, </li>
<li>drag your columns onto the form (formatting, and placement doesn't matter)</li>
<li>set it to datasheet view</li>
<li>edit labels (these become column headings)</li>
<li>change the tab order (this controls the order the columns are displayed)</li>
<li>view the datasheet and hide the columns you want</li>
<li>save the form</li>
<li>add this form as a subform to the main form</li>
</ul>
|
<p>I'm not sure there's an easy way to do this because Access saves a lot of properties with forms. If you were not using Datasheet view, you could hide the CLOSE button on the form and replace it with a command button to close the form with this code:</p>
<pre><code> DoCmd.Close acForm, Me.Name, acSaveNo
</code></pre>
<p>But since it's a datasheet, you can't do that. </p>
<p>You might try embedding your datasheet as a subform in an unbound parent form, but I don't know if using the code above behind a command button on the parent form will or will not save the column widths to the embedded subform.</p>
<p>One solution would be to re-initialize the column widths in the OnLoad event of your datasheet. You could then open the form with acHidden, and in the OnLoad event, set the column widths to their correct values (you'll want to multiply inches times 1440 to get the twips value to assign to the column width properties), and at the end of the OnLoad, set Me.Hidden to False.</p>
<p>But that is, indeed, something of a pain in the butt.</p>
<p>I'm afraid it's one of the downsides of using datasheets, since there's no way to define a close command button that won't save end-user UI data.</p>
| 33,394
|
<p>I have a database field that contains a raw date field (stored as character data), such as </p>
<blockquote>
<p>Friday, September 26, 2008 8:30 PM Eastern Daylight Time</p>
</blockquote>
<p>I can parse this as a Date easily, with SimpleDateFormat</p>
<pre><code>DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz");
Date scheduledDate = dbFormatter.parse(rawDate);
</code></pre>
<p>What I'd like to do is extract a TimeZone object from this string. The default TimeZone in the JVM that this application runs in is GMT, so I can't use <code>.getTimezoneOffset()</code> from the <code>Date</code> parsed above (because it will return the default TimeZone).</p>
<p>Besides tokenizing the raw string and finding the start position of the Timezone string (since I know the format will always be <code>EEEE, MMMM dd, yyyy hh:mm aa zzzz</code>) is there a way using the DateFormat/SimpleDateFormat/Date/Calendar API to extract a TimeZone object - which will have the same TimeZone as the String I've parsed apart with <code>DateFormat.parse()</code>?</p>
<p>One thing that bugs me about <code>Date</code> vs <code>Calendar</code> in the Java API is that <code>Calendar</code> is supposed to replace <code>Date</code> in all places... but then they decided, oh hey let's still use <code>Date</code>'s in the <code>DateFormat</code> classes.</p>
|
<p>I found that the following:</p>
<pre><code> DateFormat dbFormatter = new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aa zzzz");
dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
Date scheduledDate = dbFormatter.parse("Friday, September 26, 2008 8:30 PM Eastern Daylight Time");
System.out.println(scheduledDate);
System.out.println(dbFormatter.format(scheduledDate));
TimeZone tz = dbFormatter.getTimeZone();
System.out.println(tz.getDisplayName());
dbFormatter.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(dbFormatter.format(scheduledDate));
</code></pre>
<p>Produces the following:</p>
<pre><code>Fri Sep 26 20:30:00 CDT 2008
Friday, September 26, 2008 08:30 PM Eastern Standard Time
Eastern Standard Time
Friday, September 26, 2008 08:30 PM Central Daylight Time
</code></pre>
<p>I actually found this to be somewhat surprising. But, I guess that shows that the answer to your question is to simply call getTimeZone on the formatter after you've parsed.</p>
<p>Edit:
The above was run with Sun's JDK 1.6. </p>
|
<p>Well as a partial solution you could use a RegEx match to get the timezone since you will always have the same text before it. AM or PM.</p>
<p>I don't know enough about Java timezones to get you the last part of it.</p>
| 11,123
|
<pre><code>std::vector<int> ints;
// ... fill ints with random values
for(std::vector<int>::iterator it = ints.begin(); it != ints.end(); )
{
if(*it < 10)
{
*it = ints.back();
ints.pop_back();
continue;
}
it++;
}
</code></pre>
<p>This code is not working because when <code>pop_back()</code> is called, <code>it</code> is invalidated. But I don't find any doc talking about invalidation of iterators in <code>std::vector::pop_back()</code>.</p>
<p>Do you have some links about that?</p>
|
<p>The call to <a href="http://en.cppreference.com/w/cpp/container/vector/pop_back" rel="noreferrer"><code>pop_back()</code></a> removes the last element in the vector and so the iterator to that element is invalidated. The <code>pop_back()</code> call does <em>not</em> invalidate iterators to items before the last element, only reallocation will do that. From Josuttis' "C++ Standard Library Reference":</p>
<blockquote>
<p>Inserting or removing elements
invalidates references, pointers, and
iterators that refer to the following
element. If an insertion causes
reallocation, it invalidates all
references, iterators, and pointers.</p>
</blockquote>
|
<p>Check out the information <a href="http://www.cplusplus.com/reference/stl/vector/pop_back.html" rel="nofollow noreferrer">here (cplusplus.com)</a>:</p>
<blockquote>
<p><strong>Delete last element</strong></p>
<p>Removes the last element in the vector, effectively reducing the vector size by one and invalidating all iterators and references to it.</p>
</blockquote>
| 8,773
|
<p>I've been using NUnit for a few years. I've tried MBUnit for a short while as well as Zenebug and XUnit but I keep coming back to NUnit.</p>
<p>What is your favorite/most used Unit test Framework? Can you explain why you're using it?</p>
|
<p>Nunit for the win!! It is simple and easy to implement. No mess, no fuss.</p>
|
<p>I used to use NUnit, but now I prefer the framework that comes with Visual Studio 2008, simply because it has tighter integration and is easier to set up to test private methods.</p>
<p>We also had problems with keeping the versions of NUnit synchronized with the rest of the team. It was a minor annoyance (go and upgrade, or fix the project references), but it went away with the switch.</p>
| 15,540
|
<p>I am planning to move my vmWare's Virtual Machines from a Windows host to a Linux host (Ubuntu). It is possible to run vmWare Server in a Linux host that does not have the graphical environment (does not have X)?</p>
<p>I just wonder how the graphical setup of Windows/Linux guest work in this case.</p>
<p>Thanks in advance for your time.</p>
<p>Victor Marquez</p>
|
<p>Just install it on Ubuntu Server and install it via apt-get. Here's a good walkthrough</p>
<p><a href="http://users.piuha.net/martti/comp/ubuntu/en/server.html" rel="nofollow noreferrer">http://users.piuha.net/martti/comp/ubuntu/en/server.html</a></p>
<p>I did this on my development server and connect to it using the graphical client on my Windows machine. I have no gui installed.</p>
|
<p>the X libraries are required during the compilation and installation of VMware Server on Linux.</p>
| 24,327
|
<p>It's been ratling in my brain for a while.</p>
<p>I've had some investigation on Compilers/Flex/Byson and stuff but I never found a good reference that talked in detail about the "parsing stack", or how to go about implementing one.</p>
<p>Does anyone know of good references where I could catch up?</p>
<p><strong>Edit</strong>: I do appreciate all the compiler references, and I'm going to get some of the books listed, but my main focus was on the Parsing itself and not what you do with it after.</p>
|
<p>The <a href="https://rads.stackoverflow.com/amzn/click/com/0321486811" rel="noreferrer" rel="nofollow noreferrer">Dragon book</a>! I used it quite recently to write a compiler (in PHP!) for a processing language for template files written in RTF...</p>
|
<p>try <a href="http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Dstripbooks&field-keywords=compiler+construction&x=20&y=16" rel="nofollow noreferrer">amazon</a></p>
<p><em>Compiler Construction</em> is just one good example</p>
| 18,198
|
<p>We're writing an asp.net web app on IIS 6 and are planning on storing our user login variables in a session. Will this be removed when the worker process recycles?</p>
|
<p>If session is stored in-proc then YES worker process recycle will remove it. Use Out-of-proc model or sql server to store session value if you want to keep it stored.</p>
|
<p>yes, unless you are using out of process session state.</p>
| 10,981
|
<p>We've been asked by a client to give us a time estimate on each and every bug we have.</p>
<p>Though we do have a set schedule for bug fixing and have allocated time for it, we don't have a time allocation on each of the bugs we have. Simply, we have prioritized our bugs and have ensured that Highest priority bugs will be fixed in the time allotted.</p>
<p>I'm not a fan of allocating time to bugs, simply because:</p>
<ol>
<li>It usually is inaccurate. It's very difficult to figure out how long it would take to fix.</li>
<li>Waste of time.</li>
<li>Affects code quality</li>
<li>Creates more bugs in the long run (We may miss certain things in our attempt to complete it by the deadline).</li>
</ol>
<p>How should we tackle this issue where we don't want to provide the number of hours per bug, but just a time frame as to what bugs will be fixed?</p>
<p>How do you allocate time to your bugs? Is it effective? Worth the time and effort?</p>
|
<p>The only answer I can give is to be extremely conservative. Guess how long it will take, and multiple your guess by four. Use that as your estimate. As you said, it's very difficult to figure out how long things will take to fix, and it's better to say it will take longer than it actually does than to be caught "breaking your deadline" because you weren't conservative enough.</p>
|
<p>It should be the same as estimating any other task you have. Split it up into the smallest tasks possible and estimate those as accurately as you can with padding for the unexpected. Then give them a range so you're not pinned down to a specific date on tasks that are not well-defined. There is no difference between estimating time to fix a bug and estimating time to implement a feature with nebulous requirements.</p>
| 16,325
|
<p>I went to school for programming years ago and when I got out I found a job in system administration and that is the direction my career took. I'd like to get back into development of some sort and have been 'playing' with C# and ASP.NET, but I've been hearing lots of buzz for other 'new' languages (by new I mean that they are new to me) like Ruby and F#. I guess I'm wondering if I'm wasting my time with learning largely MS languages instead of being more of a generalist. Having not been apart of the development community for a long time (if ever I was) has me floundering with trends and I'd like not to be left behind the times.</p>
<p>Any thoughts to if it's better to follow the "latest" languages or stick with what is more tried and true technologies?</p>
|
<p>You should learn at least 1 compiled language (like C# or Java) and 1 Script Language (Python, Ruby, etc). This is usually enough to help most developers succeed at what they do, regardless of the age of the language.</p>
<p>As for new vs old, I'd stick with C# for now as it's pretty popular. Learning a new language wouldn't be too bad though.</p>
|
<p>This is a bit of a loaded question, but you'll find that folks here are passionate about their tool choice while believing in flexibility that a choice provides.</p>
<p>That said, if you don't mind "vendor lockin," the Microsoft stack is an excellent way to get into programming and find gainful employment for years to come. Microsoft is both "tried and true" and "latest." The Microsoft stack is traditionally geared toward building business applications, but you're not limited to that (ASP.NET MVC, for example, was used to build this site).</p>
<p>I don't know a whole lot about the world of Ruby on Rails and such, so I'll defer to a more knowledgable person.</p>
<p>My real advice is to go with what you like. Learn C# <strong>and</strong> F# if that's what you're into. </p>
| 18,497
|
<p>If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases? </p>
<p>I know it is possible to use <a href="http://www.sqlite.org/lang_attach.html" rel="noreferrer">ATTACH</a> to do this but it has <a href="http://www.sqlite.org/limits.html#max_attached" rel="noreferrer">a limit</a> of 32 and 64 databases depending on the memory system on the machine.</p>
|
<p>To summarize from the <a href="https://web.archive.org/web/20120615034014/http://sqlite.1065341.n5.nabble.com/Attempting-to-merge-large-databases-td39548.html" rel="noreferrer">Nabble post</a> in DavidM's answer:</p>
<pre><code>attach 'c:\test\b.db3' as toMerge;
BEGIN;
insert into AuditRecords select * from toMerge.AuditRecords;
COMMIT;
detach toMerge;
</code></pre>
<p>Repeat as needed.</p>
<p><em>Note: added <code>detach toMerge;</code> as per mike's comment.</em></p>
|
<p>With no offense, just as one developer to another, I'm afraid that your idea seems terribly inefficient.
It seems to me that instead of uniting SQLite databases you should probably be storing several tables within the same Database file.</p>
<p>However if I'm mistaken I guess you could ATTACH the databases and then use a VIEW to simplify your queries. Or make an in-memory table and copy over all the data (but that's even worse performance wise, especially if you have large databases)</p>
| 10,635
|
<p>The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="#" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
<p>or</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function myJsFunc() {
alert("myJsFunc");
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a></code></pre>
</div>
</div>
</p>
|
<p>I use <code>javascript:void(0)</code>.</p>
<p>Three reasons. Encouraging the use of <code>#</code> amongst a team of developers inevitably leads to some using the return value of the function called like this:</p>
<pre><code>function doSomething() {
//Some code
return false;
}
</code></pre>
<p>But then they forget to use <code>return doSomething()</code> in the onclick and just use <code>doSomething()</code>.</p>
<p>A second reason for avoiding <code>#</code> is that the final <code>return false;</code> will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function.</p>
<p>A third reason is that there are cases where the <code>onclick</code> event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my <code>onclick</code> (or on anything) in HTML markup look like this:</p>
<pre><code>onclick="someFunc.call(this)"
</code></pre>
<p>OR</p>
<pre><code>onclick="someFunc.apply(this, arguments)"
</code></pre>
<p>Using <code>javascript:void(0)</code> avoids all of the above headaches, and I haven't found any examples of a downside.</p>
<p>So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state:</p>
<p>Use <code>href="#"</code>, make sure <code>onclick</code> always contains <code>return false;</code> at the end, that any called function does not throw an error and if you attach a function dynamically to the <code>onclick</code> property make sure that as well as not throwing an error it returns <code>false</code>.</p>
<p>OR</p>
<p>Use <code>href="javascript:void(0)"</code></p>
<p>The second is clearly much easier to communicate.</p>
|
<p>Bootstrap modals from before 4.0 have a basically undocumented behavior that they will load <code>href</code>s from <code>a</code> elements using AJAX unless they are exactly <code>#</code>. If you are using Bootstrap 3, <code>javascript:void(0);</code> hrefs will cause javascript errors:</p>
<p><code>AJAX Error: error GET javascript:void(0);</code></p>
<p>In these cases you would need to upgrade to bootstrap 4 or change the href.</p>
| 16,329
|
<p>I'm programming a file transfer handler with speed limit feature, the rate based on user level. How do I control/calculate transfer rate in HttpHandler?.</p>
<p>Some asp.net resource tell me that use Thread.Sleep will block asp.net thread pool.</p>
|
<p>It is generally a bad idea to Sleep any thread from ASP .NET, because those threads could be used otherwise to service requests from the pool. If there were say, 10 threads in the pool, sleeping 10 threads that were processing downloads would cause all other requests to pile up in the queue until a download had finished.</p>
<p>You are perhaps best served by creating an IHttpAsyncHandler instead of an IHttpHandler, as perscribed in:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms227433.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms227433.aspx</a></p>
<p>You can use a timer to periodically pump x bytes of data to the client (but be sure to periodically pool for a closed connection using IsClientConnected or some such). </p>
|
<p>You might want to try using timers and a timer callback to do this. The idea would be to have a timer (or maybe two) that triggers when your handler can run and for how long. Every time the "go" timer expires, it starts a thread which writes your data to the response until the "stop" timer expires (or the same timer expires again), then that thread finishes what it was doing, does the housekeeping for the next thread, resets the "go" timer, and exits. Your main thread justs sets up the initial timer, the data for the transfer, then invokes the timer and exits. Presumably you'd need to keep a handle to the response somewhere so that you could get access to it again. By varying the length of time that the handler has to wait/execute you can control how many resources it uses.</p>
| 44,995
|
<p>VS 2008 crashes whilst opening a solution file when it reaches the stage of "Loading project files 'Solution Items'". </p>
<p>Is there any way of either stopping the virtual folder of solution items from opening or a workaround for this? The solution is coming from TFS 2005 and source control.</p>
<p>Thanks</p>
|
<p>Another thing you could try is removing the .suo file of your solution. This files contains your personal settings and can get corrupted sometimes. It also contains which documents where open when you exited, so removing this file also clears that list.</p>
|
<p>.sln (and .csproj) files are just text files. So you could open the solution fle in a text editor and remove the entry for the offending project or item.</p>
| 40,980
|
<p>What is the differences and similarities between Domain Specific Languages (DSL) and Domain Driven Design (DDD)?</p>
|
<p>Domain Driven Design (DDD) is a way of thinking and communicating about the problems and its solutions. </p>
<p>Domain Specific Language (DSL) is a way of writing code.</p>
<p>They're similar because they both start with the word "domain". That's it, I guess. :-)</p>
|
<p>Wikipedia has a pretty clear definition for <a href="http://en.wikipedia.org/wiki/Domain_Specific_Language" rel="nofollow noreferrer">DSL</a>:</p>
<blockquote>
<p>The term domain-specific language
(DSL) has become popular in recent
years in software development to
indicate a programming language or
specification language dedicated to a
particular problem domain, a
particular problem representation
technique, and/or a particular
solution technique.</p>
</blockquote>
<p>This can be implemented as a set of classes following some consistent pattern, some fancy C++ template magic, or a compiler/parser that interprets free text input to do what you want.</p>
| 21,401
|
<p>When have you ever personally come upon the <strong><a href="https://en.wikipedia.org/wiki/Halting_problem" rel="nofollow noreferrer">halting problem</a></strong> in the field? This can be when a co-worker / boss suggested a solution which would violate the fundamental limits of computation, or when you realized yourself that a problem you were trying to solve was, in fact, impossible to solve.</p>
<p>The most recent time I came up with it was when studying type checkers. Our class realized that it would be impossible to write a perfect type checker (one that would accept all programs that would run without type errors, and reject all programs that would run with type errors) because this would, in fact, solve the halting problem. Another was when we realized, in the same class, that it would be impossible to determine whether a division would ever occur by zero, in the type-checking stage, because checking whether a number, at run-time, is zero, is also a version of the halting problem.</p>
|
<p>I <em>literally</em> got assigned the halting problem, as in "write a monitor plugin to determine whether a host is permanently down". Seriously? OK, so I'll just give it a threshold. "No, because it might come back up afterward."</p>
<p>Much theoretical exposition ensued.</p>
|
<p>"How can you assure me your code is 100% free of bugs?"</p>
| 29,204
|
<p>Of the two methods below, which do you prefer to read?<br>
Is there another (better?) way to check if a flag is set?</p>
<pre><code> bool CheckFlag(FooFlag fooFlag)
{
return fooFlag == (this.Foo & fooFlag);
}
</code></pre>
<p>And</p>
<pre><code> bool CheckFlag(FooFlag fooFlag)
{
return (this.Foo & fooFlag) != 0;
}
</code></pre>
<p><hr/>
Please vote up the method you prefer.</p>
|
<p>The two expressions do different things (if fooFlag has more than one bit set), so which one is better really depends on the behavior you want:</p>
<pre><code>fooFlag == (this.Foo & fooFlag) // result is true iff all bits in fooFlag are set
(this.Foo & fooFlag) != 0 // result is true if any bits in fooFlag are set
</code></pre>
|
<p>I'm a positive thinker:</p>
<pre><code>bool CheckFlag(FooFlag fooFlag)
{
return this.Foo & fooFlag == 1;
}
</code></pre>
| 25,065
|
<p>If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:</p>
<blockquote>
<p>HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA.............................................................................................................................................</p>
</blockquote>
<p>I've tried just using <code>wordwrap()</code> in PHP, but the problem with that is if there is a link or some other valid HTML, it breaks.</p>
<p>There seems to be a few options in CSS, but none of them work in all browsers. See word-wrap in IE.</p>
<p>How do you solve this problem?</p>
|
<p>in CSS3: </p>
<pre><code>word-wrap:break-word
</code></pre>
|
<p>I have posted a solution which uses JavaScript and a simple Regular Expression to break long word so that it can be wrapped without breaking your website layout.</p>
<p><a href="http://www.hemanshubhojak.com/Home/Post?postId=8" rel="nofollow noreferrer">Wrap long lines using CSS and JavaScript</a></p>
| 47,453
|
<p>I'm trying to get this:</p>
<pre><code>//C.h
#ifndef C_H
#define C_H
#include "c.h"
class C
{
public:
C();
int function(int, int);
};
#endif
</code></pre>
<p>which is defined in this:</p>
<pre><code>//c.cpp
#include "c.h"
C::C()
{
}
int C::function(int a, int b)
{
return a * b;
}
</code></pre>
<p>to work in this:</p>
<pre><code>//crp.cpp
#include <iostream>
#include "c.h"
void main(void)
{
C a;
std::cout << a.function(1, 2);
}
</code></pre>
<p>but I get two errors</p>
<p>Error: Unresolved external 'C::C()' referenced from C:\C++\CRP.OBJ</p>
<p>Error: Unresolved external 'C::function(int, int)' referenced from C:\C++\CRP.OBJ</p>
<p>I'm really stuck. Help v. much appreciated! </p>
<p>EDIT:</p>
<p>Thank you for your replies,</p>
<p>I'm using Borland C++ 5.5.1 for Win32, via the command line, I'm not actually sure what a linker is, this is the first time I've tried doing this.</p>
|
<p>It looks like your link phase is trying to create an executable from just crp.obj, <strong>NOT</strong> crp.obj and c.obj.</p>
<p>How are you compling it? It should be something like (in the case of Borland, as mentioned in edit):</p>
<pre><code>bcc32 -ecrp.exe crp.cpp c.cpp
</code></pre>
<p>You also don't need the include line within c.h, the only thing stopping an infinite include loop there is the include guard.</p>
|
<p>Which compiler / development environment are you using? Is this from the command line or an IDE?</p>
<p>You need to make sure you compile c.cpp and tell the linker to include c.obj together with crp.obj to create your executable.</p>
| 39,555
|
<p>I've got a number of WebService methods that all include some very boilerplate code of wrapping the actual work in a try/catch/finally and performing the same tasks in the catch/finally. So as a way to encapsulate all of the shared catch/finally stuff I wrote a simple generic.</p>
<p>This works and really eliminates a bunch of repetitive code but feels klunky, and the syntax is very obtuse. Every time I come back to this my brain gets twisted trying to figure it out (a clear sign it is not a good design). I'm looking for feedback on whether this is a crazy thing to do, and if there is a better way to approach it.</p>
<p>Here is my template:</p>
<pre><code>public delegate T2 RestfulServiceRequest<T1, T2>(T1 req);
static class RestfulService
{
public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req)
{
if (req == null)
throw new BadRequestException(new ArgumentNullException("Invalid or missing request object"));
try
{
return serviceCall(req);
}
catch (RestfulException e)
{
// log it and rethrow
Logger.Write(e);
throw;
}
catch (Exception e)
{
Logger.Error(e);
// wrap in a consistent exception for propagation back to caller
throw new InternalServerException(e);
}
finally
{
Logger.Debug("Complete");
}
}
}
</code></pre>
<p>}</p>
<p>And here is a usage of it:</p>
<pre><code>public class Initialization : IInitialization
{
// MyMethod thas uses the template
public ApplianceInitResp CreateApplianceServer(ApplianceInitReq req)
{
return RestfulService.ExceptionHandler<ApplianceInitReq, ApplianceInitResp>(delegate(ApplianceInitReq x)
{
// do some work
return new ApplianceInitResp();
}, req);
}
}
</code></pre>
<p>}</p>
|
<p>I would change</p>
<pre><code>public static T2 ExceptionHandler<T1, T2>(RestfulServiceRequest<T1, T2> serviceCall, T1 req)
</code></pre>
<p>to</p>
<pre><code>public static T2 Invoke<T1, T2>( this T1 req, RestfulServiceRequest<T1, T2> serviceCall)
</code></pre>
<p>This will change the call to </p>
<pre><code>public class Initialization :IInitialization {
public ApplianceInitResp CreateApplianceServer( ApplianceInitReq req ) {
return req.Invoke( r => {
// do some work
return new ApplianceInitResp();
});
}
}
</code></pre>
|
<p>I would agree that this feels a bit clunky to accomplish, however, I am not right away seeing the "pefect" way to re-work this to minimize duplication.</p>
<p>THe only thing I'm thinking is that if you can somehow use interfaces or break it up a bit, I'm not sure exactly how I'd do it, but I can say that for on going changes I don't think I would leave this, at least not without really good documentation.</p>
| 44,555
|
<p>I have some code for starting a thread on the .NET CF 2.0:</p>
<pre><code>ThreadStart tStart = new ThreadStart(MyMethod);
Thread t = new Thread(tStart);
t.Start();
</code></pre>
<p>If I call this inside a loop the items completely out of order. How do introduce a wait after <code>t.Start()</code>, so that the work on the thread completes before the code continues? Will BeginInvoke/EndInvoke be a better option for this than manually creating threads?</p>
|
<p>How much order do you need to impose on the threads? If you just need all of the work started in the loop to finish before the code continues, but you don't care about the order the work within the loop finishes, then calling Join is the answer. To add more detail to <a href="https://stackoverflow.com/questions/6890/compact-framework-how-to-wait-for-thread-complete-before-continuing#6935">Kevin Kenny's answer,</a> you should call Join <em>outside</em> the loop. This means you will need a collection to hold references to the threads you started:</p>
<pre><code>// Start all of the threads.
List<Thread> startedThreads = new List<Thread>();
foreach (...) {
Thread thread = new Thread(new ThreadStart(MyMethod));
thread.Start();
startedThreads.Add(thread);
}
// Wait for all of the threads to finish.
foreach (Thread thread in startedThreads) {
thread.Join();
}
</code></pre>
<p>In contrast, if you called Join inside the loop, the result would basically be the same as not using threads at all. Each iteration of the loop body would create and start a thread but then immediately Join it and wait for it to finish.</p>
<p>If the individual threads produce some result (write a message in a log, for example) then the messages may still appear out of order because there's no coordination between the threads. It is possible to get the threads to output their results in order by coordinating them with a Monitor.</p>
|
<p>If I'm reading this properly, you're starting work items on bunch of threads but you're concerned that the threads are completing out of order, and, would prefer to wait until each thread completes in the order they were started ? </p>
<p>If this is the case then I'm not sure why you're creating a thread per work item. Maybe you could expand?</p>
<p>If you did need to wait for a thread to complete the you could just do:</p>
<pre><code>t.Join();
</code></pre>
| 2,856
|
<p>What Firefox add-ons do you use that are useful for programmers?</p>
|
<p>I guess it's silly to mention Firebug -- doubt any of us could live without it. Other than that I use the following (only listing dev-related):</p>
<ul>
<li>Console<sup>2</sup>: next-generation error console</li>
<li>DOM inspector: as the title might indicate, allows you to browse the DOM</li>
<li>Edit Cookies: change cookies on the fly</li>
<li>Execute JS: ad-hoc Javascript execution</li>
<li>IE Tab: render a page in IE</li>
<li>Inspect This: brings the selected object into the DOM inspector</li>
<li>JSView: display linked javascript and CSS</li>
<li>LORI (Life of Request Info): shows how long it takes to render a page</li>
<li>Measure IT: a popup ruler. </li>
<li>URL Params: shows GET and POST variables</li>
<li>Web Developer: a myriad of tools for the web developer</li>
</ul>
|
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/60" rel="nofollow noreferrer">Web Developer</a> for web development. <a href="https://addons.mozilla.org/en-US/firefox/addon/1730" rel="nofollow noreferrer">Scribefire</a> if you're a blogger-progammer</p>
| 5,702
|
<p>Is contract to interface as object is to class?</p>
<p>What is the need to differentiate identical things like this, from the code to the executing code? I sort of get the idea behind naming a class a class and the instantiated executing class an object, but overall, is that the only reason for these semi-redundant terms?</p>
|
<p>Not really. There are four terms here, so I'll go over each of them:</p>
<h2>Interface</h2>
<p>An interface is an abstract class (in languages like Java where there is no multiple inheritance, sometimes there are other restrictions, such as a separate data type) that is intended to be used as a common base to access a number of similarly-behaving objects. Conceptually, there is no requirement for abstractness, but usually, an interface will have at least one abstract method. An interface is a method for your program to communicate with a number of similar classes, each with different semantics but the same general purpose.</p>
<h2>Contract</h2>
<p>A contract is the implicit agreement you make between users and implementers of a class or interface. For instance, preconditions and postconditions (invariants are usually a contract within the class' implementation - generally, things like the relation between internal members don't need to be exposed). The specification for a return value or an argument can also be part of the contract. It basically represents how to use the function/class/interface, and isn't generally fully representable in any language (some languages, like Eiffel, allow you to put explicit contracts in, but even these can't always fully flesh out the requirements). When you implement an interface or derive from a class, you are always having to meet the interface requirements, or, when overriding a non-abstract class, to behave similar enough that an external viewer doesn't notice the difference (this is the Liskov Substitution Principle; a derived object should be capable of replacing the base with no difference in behavior from the outside perspective).</p>
<h2>Class</h2>
<p>A class doesn't need a lot of going over, since you clearly have used them before. A class is the data type, and in some languages is a superset of interfaces (which have no formal definition, as in C++), and in others is independent (such as in Java).</p>
<h2>Object</h2>
<p>An object is an instance of a class type (or of any non-class type, usually). The exact definition of an object is very specific to a language, but the general definition is the actual thing referred to by multiple references/pointers to the same thing - for instance, in some languages like Java, == compares whether two variables are the same object, not necessarily whether they are semantically the same. Objects are independent from classes or interfaces - they represent a single instance. Another way of thinking of it is that class or interface is the mold, and the object is the physical object that comes out of the mold (a rather bad analogy, but it's the best I can come up with right now).</p>
|
<p>"Class" and "Object" represent two different things; they are related, but what they represent IS different, quite strongly.</p>
<p>The best way to describe this is to look at Static. A class can have static members, which are completely separate from any INSTANCE of that class. Objects of that class may or may not use those static members; but the instance of the object of that class is completely separate from any static uses of that class (or should be, at the very least).</p>
<p>Or think of the singleton pattern. Storing an instance of the class object in a static class accessor is a common practice, and shows the difference. You refer to the <strong>class static accessor</strong> to get the <strong>object instance</strong> of a singleton class; if the <strong>class static member</strong> does not have an <strong>object instance</strong> to refer to, the <strong>class</strong> creates the <strong>instance</strong> of the <strong>object</strong>.</p>
<p>Put another way; an object <strong>is</strong> an instance of a class; but a class can be <strong>more</strong> than just a template from which objects are instantiated. Static members of classes have a representation in memory that is completely independent of object instances of those classes.</p>
| 27,010
|
<p>I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around Lucene anyway, so I imagine there must be a way to do it!</p>
<p>I've looked into using EdgeNGramFilter, and I realise that I'd have to run the filter on the index fields and get the tokens out and then compare them against the inputted Query... I'm just struggling to make the connection between the two into a bit of code, so help is much appreciated!</p>
<p>To be clear on what I'm looking for (I realised I wasn't being overly clear, sorry) - I'm looking for a solution where when searching for a term, it'd return a list of suggested queries. When typing 'inter' into the search field, it'll come back with a list of suggested queries, such as 'internet', 'international', etc.</p>
|
<p>Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want.</p>
<p>This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sorted by the number of matching documents with that term in the original index, so more popular terms appear first. Seems to work pretty well :)</p>
<pre><code>import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.ISOLatin1AccentFilter;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter;
import org.apache.lucene.analysis.ngram.EdgeNGramTokenFilter.Side;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.spell.LuceneDictionary;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* Search term auto-completer, works for single terms (so use on the last term
* of the query).
* <p>
* Returns more popular terms first.
*
* @author Mat Mannion, M.Mannion@warwick.ac.uk
*/
public final class Autocompleter {
private static final String GRAMMED_WORDS_FIELD = "words";
private static final String SOURCE_WORD_FIELD = "sourceWord";
private static final String COUNT_FIELD = "count";
private static final String[] ENGLISH_STOP_WORDS = {
"a", "an", "and", "are", "as", "at", "be", "but", "by",
"for", "i", "if", "in", "into", "is",
"no", "not", "of", "on", "or", "s", "such",
"t", "that", "the", "their", "then", "there", "these",
"they", "this", "to", "was", "will", "with"
};
private final Directory autoCompleteDirectory;
private IndexReader autoCompleteReader;
private IndexSearcher autoCompleteSearcher;
public Autocompleter(String autoCompleteDir) throws IOException {
this.autoCompleteDirectory = FSDirectory.getDirectory(autoCompleteDir,
null);
reOpenReader();
}
public List<String> suggestTermsFor(String term) throws IOException {
// get the top 5 terms for query
Query query = new TermQuery(new Term(GRAMMED_WORDS_FIELD, term));
Sort sort = new Sort(COUNT_FIELD, true);
TopDocs docs = autoCompleteSearcher.search(query, null, 5, sort);
List<String> suggestions = new ArrayList<String>();
for (ScoreDoc doc : docs.scoreDocs) {
suggestions.add(autoCompleteReader.document(doc.doc).get(
SOURCE_WORD_FIELD));
}
return suggestions;
}
@SuppressWarnings("unchecked")
public void reIndex(Directory sourceDirectory, String fieldToAutocomplete)
throws CorruptIndexException, IOException {
// build a dictionary (from the spell package)
IndexReader sourceReader = IndexReader.open(sourceDirectory);
LuceneDictionary dict = new LuceneDictionary(sourceReader,
fieldToAutocomplete);
// code from
// org.apache.lucene.search.spell.SpellChecker.indexDictionary(
// Dictionary)
IndexReader.unlock(autoCompleteDirectory);
// use a custom analyzer so we can do EdgeNGramFiltering
IndexWriter writer = new IndexWriter(autoCompleteDirectory,
new Analyzer() {
public TokenStream tokenStream(String fieldName,
Reader reader) {
TokenStream result = new StandardTokenizer(reader);
result = new StandardFilter(result);
result = new LowerCaseFilter(result);
result = new ISOLatin1AccentFilter(result);
result = new StopFilter(result,
ENGLISH_STOP_WORDS);
result = new EdgeNGramTokenFilter(
result, Side.FRONT,1, 20);
return result;
}
}, true);
writer.setMergeFactor(300);
writer.setMaxBufferedDocs(150);
// go through every word, storing the original word (incl. n-grams)
// and the number of times it occurs
Map<String, Integer> wordsMap = new HashMap<String, Integer>();
Iterator<String> iter = (Iterator<String>) dict.getWordsIterator();
while (iter.hasNext()) {
String word = iter.next();
int len = word.length();
if (len < 3) {
continue; // too short we bail but "too long" is fine...
}
if (wordsMap.containsKey(word)) {
throw new IllegalStateException(
"This should never happen in Lucene 2.3.2");
// wordsMap.put(word, wordsMap.get(word) + 1);
} else {
// use the number of documents this word appears in
wordsMap.put(word, sourceReader.docFreq(new Term(
fieldToAutocomplete, word)));
}
}
for (String word : wordsMap.keySet()) {
// ok index the word
Document doc = new Document();
doc.add(new Field(SOURCE_WORD_FIELD, word, Field.Store.YES,
Field.Index.UN_TOKENIZED)); // orig term
doc.add(new Field(GRAMMED_WORDS_FIELD, word, Field.Store.YES,
Field.Index.TOKENIZED)); // grammed
doc.add(new Field(COUNT_FIELD,
Integer.toString(wordsMap.get(word)), Field.Store.NO,
Field.Index.UN_TOKENIZED)); // count
writer.addDocument(doc);
}
sourceReader.close();
// close writer
writer.optimize();
writer.close();
// re-open our reader
reOpenReader();
}
private void reOpenReader() throws CorruptIndexException, IOException {
if (autoCompleteReader == null) {
autoCompleteReader = IndexReader.open(autoCompleteDirectory);
} else {
autoCompleteReader.reopen();
}
autoCompleteSearcher = new IndexSearcher(autoCompleteReader);
}
public static void main(String[] args) throws Exception {
Autocompleter autocomplete = new Autocompleter("/index/autocomplete");
// run this to re-index from the current index, shouldn't need to do
// this very often
// autocomplete.reIndex(FSDirectory.getDirectory("/index/live", null),
// "content");
String term = "steve";
System.out.println(autocomplete.suggestTermsFor(term));
// prints [steve, steven, stevens, stevenson, stevenage]
}
}
</code></pre>
|
<p>You can use the class <strong>PrefixQuery</strong> on a "dictionary" index. The class <strong>LuceneDictionary</strong> could be helpful too.</p>
<p>Take a look at this article linked below. It explains how to implement the feature "Did you mean ?" available in modern search engine such as Google. You may not need something as complex as described in the article. However the article explains how to use the Lucene spell package.</p>
<p>One way to build a "dictionary" index would be to iterate on a LuceneDictionary.</p>
<p>Hope it helps</p>
<p><a href="https://web.archive.org/web/20050811022737/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html" rel="nofollow noreferrer">Did You Mean: Lucene? (page 1)</a></p>
<p><a href="https://web.archive.org/web/20061103220620/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html%3Fpage%3D2" rel="nofollow noreferrer">Did You Mean: Lucene? (page 2)</a></p>
<p><a href="https://web.archive.org/web/20061103220620/http://today.java.net/pub/a/today/2005/08/09/didyoumean.html%3Fpage%3D3" rel="nofollow noreferrer">Did You Mean: Lucene? (page 3)</a></p>
| 14,617
|
<p>I've got an application that uses a hibernate(annotations)/mysql combination for ORM. In that application, I got an entity with a Date field. I'm looking for a way to select on that date within a time range (so <code>hh:mm:ss</code> without the date part). </p>
<p>In MySQL there's a function <code>TIME(expression)</code> that can extract the time part and use that in the where clause, but that does not seem to be available in Hibernate without switching to native queries. Is there an option in hibernate to do this, or should I loop through the results in java and do the comparison there? Would this be much slower as the MySQL solution, since that would not use indexes anyway?</p>
|
<p>The following functions are available in HQL, maybe you could use them:</p>
<p><code>second(...), minute(...), hour(...), day(...), month(...), year(...)</code></p>
|
<p>Add the expression as a SQL restriction rather than having a full native query. I don't know MySQL specifically, but imagine something like this:</p>
<pre><code>Criteria criteria = session.createCriteria(MyTable.class);
criteria.add(
Expression.sql(
"TIME( {alias}.my_date, 'hh:mm:ss') >= :1",
dateRangeMin,
new StringType()
)
);
</code></pre>
| 12,704
|
<p>Is there any way to have a look at signatures of anonymous functions in ActionScript 3 during runtime?</p>
<p>I would like to validate <code>Function</code> objects passed in as arguments to other functions and make sure that they accept the correct number of arguments (with the correct types) and return a value of the correct type.</p>
<p><code>flash.utils.describeType()</code> doesn't seem to return this info for anonymous functions.</p>
|
<p>It doesn't look like the runtime allows you to reflect on anonymous functions, which is a shame.</p>
<p>Anonymous functions are (perhaps by definition) marked as <code>dynamic</code>. If you pass an incompatible type into an anonymous function, <em>no error is thrown</em>. Any type mismatches will be silently cast as best they can. Passing something like <code>"minotaur"</code> as a <code>uint</code> parameter will yield <code>0</code> (zero), for example.</p>
<p>If you REALLY want to over-engineer it, you could get all OO on it. Instead of accepting anonymous functions, you could declare an interface which contains the appropriate function signature, and accept objects that implement that interface.</p>
<pre><code>public interface IFancyCallback {
public function fancyFunction(frog:Frog, princess:Girl):UsefulReturnType;
}
</code></pre>
<p>And your function would just have to be packaged up in an object:</p>
<pre><code>public class ConcreteCallback implements IFancyCallback {
public function fancyFunction(frog:Frog, princess:Girl):UsefulReturnType {
princess.kiss(frog);
return new UsefulReturnType("jabberwocky");
}
}
</code></pre>
<p>Could have the potential to create a lot of code overhead. Depends how many callbacks you intend to have, who's going to be making them, and what how serious it would be if the anon function's signature was incorrect.</p>
<p>Can you share any more about the problem you're trying to solve?</p>
|
<p>As a rough approximation you can check the number of parameters using length property, e.g.:</p>
<pre><code>function doStuff(callback:Function) {
trace(callback.length);
}
</code></pre>
<p>I'm not aware of any way to enumerate the arguments of an anonymous functions; you can of course validate ex-post catching ArgumentError.</p>
| 43,279
|
<p>I need to find 2 elements in an unsorted array such that the difference between them is less than or equal to (Maximum - Minimum)/(number of elements in the array).</p>
<p>In O(n).</p>
<p>I know the max and min values.</p>
<p>Can anyone think of something?</p>
<p>Thank you!</p>
|
<p>Step 1: Use <a href="http://en.wikipedia.org/wiki/Bucket_sort" rel="nofollow noreferrer">Bucket Sort</a>. Don't sort the individual buckets.</p>
<p>Should be pretty obvious what to do from here, and how to size the buckets.</p>
|
<ol>
<li><p>Number of buckets = <code>2n</code>.</p>
<p>values in each bucket = <code>(min + k((max-min)/2n)) <= value < (min + (k+1)((max-min)/2n)).</code> </p>
<p>0 <= k < 2n</p>
<p>Range of each bucket = <code>((max-min)/2n)</code></p></li>
<li><p>Assign each element into buckets. Dont sort inside buckets.</p></li>
<li><p>If any bucket has more than 1 element, the maximum possible difference between them is <code>((max-min)/2n)</code> . Hence you have your answer.</p></li>
<li><p>If any two consecutive buckets have more than zero elements each, maximum difference between them is <code>((max-min)/2n)*2 = ((max-min)/n)</code> . Hence you have your answer.</p></li>
</ol>
| 48,064
|
<p>I'm looking for a suite of plugins that can help me finally switch over to vim full-time.</p>
<p>Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it.</p>
<p>What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance).</p>
<ul>
<li>Code completion, meaning: the ability to code complete modules/functions/etc. in <em>any</em> module that's on the pythonpath, <strong>not just system modules</strong>. Bonus points for showing docstrings when completing.</li>
<li>Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files?</li>
<li>Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open.</li>
<li>Bzr integration. Not super important, since most of it I can just drop to the shell to do.</li>
</ul>
|
<p><a href="http://www.sontek.net/python-with-a-modular-ide-vim" rel="nofollow noreferrer">Here you can find some info</a> about this.</p>
<p>It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim in a better Python IDE.</p>
<p><strong>Edit:</strong> The original site is down, so found it <a href="https://web.archive.org/web/20110106042207/http://sontek.net/python-with-a-modular-ide-vim" rel="nofollow noreferrer">saved on the web archive</a>.</p>
|
<p><strong>Code completion:</strong> <a href="http://github.com/orestis/pysmell/tree/master" rel="nofollow noreferrer">PySmell</a> looks promising. It's work-in-progress, but alredy useful.</p>
| 17,392
|
<p>After reading "<a href="http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity" rel="noreferrer">What’s your/a good limit for cyclomatic complexity?</a>", I realize many of my colleagues were quite annoyed with this new <a href="http://en.wikipedia.org/wiki/Quality_assurance" rel="noreferrer">QA</a> policy on our project: no more 10 <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">cyclomatic complexity</a> per function.</p>
<p>Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '<a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105114">Do you test private method?</a>', such a policy has many good side-effects.</p>
<p>But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '<a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="noreferrer">Aspect-oriented programming</a>' approach for logs).</p>
<pre><code>myLogger.info("A String");
myLogger.fine("A more complicated String");
...
</code></pre>
<p>And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the <em>log parameters</em> (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!</p>
<p>So QA came back and urged our programmers to do conditional logging. Always.</p>
<pre><code>if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String");
if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String");
...
</code></pre>
<p>But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!</p>
<p>So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be <em>really</em> part of said complexity of that function...</p>
<p>How would you address this situation ?<br>
I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.</p>
<hr>
<p>Thank you for all the answers.<br>
I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)<br>
So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the <em>obligation</em> to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)</p>
<p>I now get the '<a href="http://en.wikipedia.org/wiki/Variadic_function" rel="noreferrer">variadic</a> function' point advanced by some of you (thank you John).<br>
Note: a quick test in java6 shows that my <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">varargs function</a> does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.</p>
<p>I have now posted my experience on this topic.<br>
I will leave it there until next Tuesday for voting, then I will select one of your answers.<br>
Again, thank you for all the suggestions :)</p>
|
<h3>With current logging frameworks, the question is moot</h3>
<p>Current logging frameworks like slf4j or log4j 2 don't require guard statements in most cases. They use a parameterized log statement so that an event can be logged unconditionally, but message formatting only occurs if the event is enabled. Message construction is performed as needed by the logger, rather than pre-emptively by the application.</p>
<p>If you have to use an antique logging library, you can read on to get more background and a way to retrofit the old library with parameterized messages.</p>
<h3>Are guard statements really adding complexity?</h3>
<p>Consider excluding logging guards statements from the cyclomatic complexity calculation.</p>
<p>It could be argued that, due to their predictable form, conditional logging checks really don't contribute to the complexity of the code.</p>
<p>Inflexible metrics can make an otherwise good programmer turn bad. Be careful!</p>
<p>Assuming that your tools for calculating complexity can't be tailored to that degree, the following approach may offer a work-around.</p>
<h3>The need for conditional logging</h3>
<p>I assume that your guard statements were introduced because you had code like this:</p>
<pre><code>private static final Logger log = Logger.getLogger(MyClass.class);
Connection connect(Widget w, Dongle d, Dongle alt)
throws ConnectionException
{
log.debug("Attempting connection of dongle " + d + " to widget " + w);
Connection c;
try {
c = w.connect(d);
} catch(ConnectionException ex) {
log.warn("Connection failed; attempting alternate dongle " + d, ex);
c = w.connect(alt);
}
log.debug("Connection succeeded: " + c);
return c;
}
</code></pre>
<p>In Java, each of the log statements creates a new <code>StringBuilder</code>, and invokes the <code>toString()</code> method on each object concatenated to the string. These <code>toString()</code> methods, in turn, are likely to create <code>StringBuilder</code> instances of their own, and invoke the <code>toString()</code> methods of their members, and so on, across a potentially large object graph. (Before Java 5, it was even more expensive, since <code>StringBuffer</code> was used, and all of its operations are synchronized.)</p>
<p>This can be relatively costly, especially if the log statement is in some heavily-executed code path. And, written as above, that expensive message formatting occurs even if the logger is bound to discard the result because the log level is too high.</p>
<p>This leads to the introduction of guard statements of the form:</p>
<pre><code> if (log.isDebugEnabled())
log.debug("Attempting connection of dongle " + d + " to widget " + w);
</code></pre>
<p>With this guard, the evaluation of arguments <code>d</code> and <code>w</code> and the string concatenation is performed only when necessary.</p>
<h3>A solution for simple, efficient logging</h3>
<p>However, if the logger (or a wrapper that you write around your chosen logging package) takes a formatter and arguments for the formatter, the message construction can be delayed until it is certain that it will be used, while eliminating the guard statements and their cyclomatic complexity.</p>
<pre><code>public final class FormatLogger
{
private final Logger log;
public FormatLogger(Logger log)
{
this.log = log;
}
public void debug(String formatter, Object... args)
{
log(Level.DEBUG, formatter, args);
}
… &c. for info, warn; also add overloads to log an exception …
public void log(Level level, String formatter, Object... args)
{
if (log.isEnabled(level)) {
/*
* Only now is the message constructed, and each "arg"
* evaluated by having its toString() method invoked.
*/
log.log(level, String.format(formatter, args));
}
}
}
class MyClass
{
private static final FormatLogger log =
new FormatLogger(Logger.getLogger(MyClass.class));
Connection connect(Widget w, Dongle d, Dongle alt)
throws ConnectionException
{
log.debug("Attempting connection of dongle %s to widget %s.", d, w);
Connection c;
try {
c = w.connect(d);
} catch(ConnectionException ex) {
log.warn("Connection failed; attempting alternate dongle %s.", d);
c = w.connect(alt);
}
log.debug("Connection succeeded: %s", c);
return c;
}
}
</code></pre>
<p>Now, <strong>none of the cascading <code>toString()</code> calls with their buffer allocations will occur</strong> unless they are necessary! This effectively eliminates the performance hit that led to the guard statements. One small penalty, in Java, would be auto-boxing of any primitive type arguments you pass to the logger.</p>
<p>The code doing the logging is arguably even cleaner than ever, since untidy string concatenation is gone. It can be even cleaner if the format strings are externalized (using a <code>ResourceBundle</code>), which could also assist in maintenance or localization of the software. </p>
<h3>Further enhancements</h3>
<p>Also note that, in Java, a <code>MessageFormat</code> object could be used in place of a "format" <code>String</code>, which gives you additional capabilities such as a choice format to handle cardinal numbers more neatly. Another alternative would be to implement your own formatting capability that invokes some interface that you define for "evaluation", rather than the basic <code>toString()</code> method.</p>
|
<p>As much as I hate macros in C/C++, at work we have #defines for the if part, which if false ignores (does not evaluate) the following expressions, but if true returns a stream into which stuff can be piped using the '<<' operator.
Like this:</p>
<pre><code>LOGGER(LEVEL_INFO) << "A String";
</code></pre>
<p>I assume this would eliminate the extra 'complexity' that your tool sees, and also eliminates any calculating of the string, or any expressions to be logged if the level was not reached.</p>
| 13,139
|
<p>I recently bought a Windows Mobile device and since I'm a developer I want to use it as a development platform. Yes, it's not supposed to be used like that but it's always with me and my laptop isn't. I know <a href="http://www.animaniak.com/cke/cke_main.asp" rel="nofollow noreferrer">cke</a> is a good editor for code but how can I run JavaScript/Ruby code without too much of a headache?</p>
<p>I probably could write a web application, send code to it and get the results back but maybe there's better solutions?</p>
|
<p>There is a possibility to run <a href="http://uema2.s8.xrea.com/ruby-mswince/" rel="nofollow noreferrer"><strong>Ruby on Windows Mobile</strong></a></p>
<p>Check this article for steps: <a href="http://andryshuzain.com/journal/ruby-on-windows-mobile-5" rel="nofollow noreferrer"><strong>Human vs Machine</strong></a> </p>
<p>Javascript is bit crippled on Windows Mobile.
Follow up the discussions here: <a href="http://blogs.msdn.com/iemobile/archive/2006/04/06/570375.aspx" rel="nofollow noreferrer"><strong>Windows Mobile IE Team Blog</strong></a>
Hopefully the next version if Pocket Internet Explorer supports better!</p>
|
<p>This is n old port of Ruby to WinCE, but from what I've read it doesn't work all that well - who knows, give it a try, YMMV</p>
<p><a href="http://uema2.s8.xrea.com/ruby-mswince/" rel="nofollow noreferrer">http://uema2.s8.xrea.com/ruby-mswince/</a></p>
<p>As for Javascript, WinMo devices have Pocket Internet Explorer - it isn't very good, but runs some Javascript. If you want something that is a bit closer to a desktop you could install Opera.</p>
| 8,539
|
<p>When using <code>before_filter :login_required</code> to protect a particular page, the <code>link_to_unless_current</code> method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text.</p>
<p>The "Login" text/link problem only occurs when redirected to the Login Page via the <code>before_filter</code> machinery, otherwise, the <code>link_to_unless_current</code> method operates as expected.</p>
<p>It seems that <code>link_to_unless_current</code> is using the old page data as the "current" instead of the login page (when redirecting).</p>
|
<p>You can use a route helper method to perform the page redirection:</p>
<pre><code> redirect_to login_url
</code></pre>
<p>If a "named route" for login is defined (which is done by adding an explicit path to "/login" in your "config/routes.rb" file).</p>
<p>This path is actually the same as that generated by:</p>
<p>new_session_url</p>
<p>For a detailed look at routing, I suggest the <a href="http://guides.rubyonrails.org/routing_outside_in.html" rel="nofollow noreferrer"><strong>Rails Routing Guide</strong></a>.</p>
|
<p>Appreciate the responses and you can tell by the nature of the question that we're new to rails. By the way, we posted the same question on this site: <a href="http://railsforum.com" rel="nofollow noreferrer">http://railsforum.com</a> (not sure if it's the official rails forum) with no response yet. StackOverflow so far seems to be creating a great community of helpers willing to reach out to the programmatically challenged.</p>
<p>I think part of the problem is that we were mixing restful urls with standard routes. The login page is mapped to the restful route "/login" but the page redirection was using "/sessions/new" (Rick Olson's restful authentication module)</p>
<p>In application.rb, we forced the filter to "/login" and that solved the problem:</p>
<pre>
before_filter :login_required
protected
def login_required
return true if logged_in?
session[:return_to] = request.request_uri
flash[:error] = "Please log in first"
redirect_to "/login" and return false
end
</pre>
<p>Comments on the technical merits of this approach appreciated as it may be helpful to other newbs.</p>
<p>Thanks,
Joe</p>
| 23,381
|
<p>I'm trying to learn about trees by implementing one from scratch.
In this case I'd like to do it in C# Java or C++. (without using built in methods)</p>
<p>So each node will store a character and there will be a maximum of 26 nodes per node.</p>
<p>What data structure would I use to contain the pointers to each of the nodes?</p>
<p>Basically I'm trying to implement a radix tree from scratch.</p>
<p>Thanks,</p>
|
<blockquote>
<blockquote>
<p>What data structure would I use to contain the pointers to each of the nodes?</p>
</blockquote>
</blockquote>
<p>A Node. Each Node should have references to (up to) 26 other Nodes in the Tree. Within the Node you can store them in an array, LinkedList, ArrayList, or just about any other collection you can think of.</p>
|
<p>It doesn't really matter. You can use a linked list, an array (but this will have a fixed size), or a List type from the standard library of your language.</p>
<p>Using a List/array will mean doing some index book-keeping to traverse the tree, so it might be easiest to use just keep references to the children in the parent.</p>
| 44,828
|
<p><strong>Caveat:</strong>
I try all the posibilities listed here: <a href="https://stackoverflow.com/questions/254002/how-can-i-ignore-everything-under-a-folder-in-mercurial">How can I ignore everything under a folder in Mercurial</a>.<br>
None works as I hope. </p>
<p>I want to ignore every thing under the folder <code>test</code>. But not ignore <code>srcProject\test\TestManager</code> </p>
<p>I try</p>
<pre><code>syntax: glob
test/**
</code></pre>
<p>And it ignores <code>test</code> and <code>srcProject\test\TestManager</code></p>
<p>With:</p>
<pre><code>syntax: regexp
^/test/
</code></pre>
<p>It's the same thing.</p>
<p>Also with:</p>
<pre><code>syntax: regexp
test\\*
</code></pre>
<p>I have install TortoiseHG 0.4rc2 with Mercurial-626cb86a6523+tortoisehg, Python-2.5.1, PyGTK-2.10.6, GTK-2.10.11 in Windows</p>
|
<p>Try it without the slash after the caret in the regexp version.</p>
<pre><code>^test/
</code></pre>
<p>Here's a test:</p>
<pre><code>~$ mkdir hg-folder-ignore
~$ cd hg-folder-ignore
~/hg-folder-ignore$ echo '^test/' > .hgignore
~/hg-folder-ignore$ hg init
~/hg-folder-ignore$ mkdir test
~/hg-folder-ignore$ touch test/ignoreme
~/hg-folder-ignore$ mkdir -p srcProject/test/TestManager
~/hg-folder-ignore$ touch srcProject/test/TestManager/dont-ignore
~/hg-folder-ignore$ hg stat
? .hgignore
? srcProject/test/TestManager/dont-ignore
</code></pre>
<p>Notice that ignoreme isn't showing up and dont-ignore is.</p>
|
<p>Create .hgignore file under root directory of the repository </p>
<p>Now add the following contents in the file . </p>
<blockquote>
<p>syntax: glob</p>
<p>bin/**</p>
<p>*.DS_Store</p>
</blockquote>
<p>This will remove the bin directory and all the *.DS_Store files from the repository</p>
| 39,958
|
<p>I have some code that raises <code>PropertyChanged</code> events and I would like to be able to unit test that the events are being raised correctly.</p>
<p>The code that is raising the events is like</p>
<pre><code>public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string MyProperty
{
set
{
if (_myProperty != value)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}
}
</code></pre>
<p>I get a nice green test from the following code in my unit tests, that uses delegates:</p>
<pre><code>[TestMethod]
public void Test_ThatMyEventIsRaised()
{
string actual = null;
MyClass myClass = new MyClass();
myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
actual = e.PropertyName;
};
myClass.MyProperty = "testing";
Assert.IsNotNull(actual);
Assert.AreEqual("MyProperty", actual);
}
</code></pre>
<p>However, if I then try and chain the setting of properties together like so:</p>
<pre><code>public string MyProperty
{
set
{
if (_myProperty != value)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
MyOtherProperty = "SomeValue";
}
}
}
public string MyOtherProperty
{
set
{
if (_myOtherProperty != value)
{
_myOtherProperty = value;
NotifyPropertyChanged("MyOtherProperty");
}
}
}
</code></pre>
<p>My test for the event fails - the event that it captures is the event for the MyOtherProperty.</p>
<p>I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.</p>
<p>So I'm wondering:<br>
1. Is my method of testing events correct?<br>
2. Is my method of raising <em>chained</em> events correct? </p>
|
<p>Everything you've done is correct, providing you want your test to ask "What is the last event that was raised?"</p>
<p>Your code is firing these two events, in this order </p>
<ul>
<li>Property Changed (... "My Property" ...)</li>
<li>Property Changed (... "MyOtherProperty" ...)</li>
</ul>
<p>Whether this is "correct" or not depends upon the purpose of these events.</p>
<p>If you want to test the number of events that gets raised, and the order they get raised in, you can easily extend your existing test:</p>
<pre><code>[TestMethod]
public void Test_ThatMyEventIsRaised()
{
List<string> receivedEvents = new List<string>();
MyClass myClass = new MyClass();
myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
receivedEvents.Add(e.PropertyName);
};
myClass.MyProperty = "testing";
Assert.AreEqual(2, receivedEvents.Count);
Assert.AreEqual("MyProperty", receivedEvents[0]);
Assert.AreEqual("MyOtherProperty", receivedEvents[1]);
}
</code></pre>
|
<p>I've made an extension here:</p>
<pre><code>public static class NotifyPropertyChangedExtensions
{
private static bool _isFired = false;
private static string _propertyName;
public static void NotifyPropertyChangedVerificationSettingUp(this INotifyPropertyChanged notifyPropertyChanged,
string propertyName)
{
_isFired = false;
_propertyName = propertyName;
notifyPropertyChanged.PropertyChanged += OnPropertyChanged;
}
private static void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == _propertyName)
{
_isFired = true;
}
}
public static bool IsNotifyPropertyChangedFired(this INotifyPropertyChanged notifyPropertyChanged)
{
_propertyName = null;
notifyPropertyChanged.PropertyChanged -= OnPropertyChanged;
return _isFired;
}
}
</code></pre>
<p>There is the usage:</p>
<pre><code> [Fact]
public void FilesRenameViewModel_Rename_Apply_Execute_Verify_NotifyPropertyChanged_If_Succeeded_Through_Extension_Test()
{
// Arrange
_filesViewModel.FolderPath = ConstFolderFakeName;
_filesViewModel.OldNameToReplace = "Testing";
//After the command's execution OnPropertyChanged for _filesViewModel.AllFilesFiltered should be raised
_filesViewModel.NotifyPropertyChangedVerificationSettingUp(nameof(_filesViewModel.AllFilesFiltered));
//Act
_filesViewModel.ApplyRenamingCommand.Execute(null);
// Assert
Assert.True(_filesViewModel.IsNotifyPropertyChangedFired());
}
</code></pre>
| 30,946
|
<p>I have a few model classes with basic one-to-many relationships. For example, a book has many recipes, and each recipe has many ingredients:</p>
<pre><code>class Book(models.Model):
name = models.CharField(max_length=64)
class Recipe(models.Model):
book = models.ForeignKey(Book)
name = models.CharField(max_length=64)
class Ingredient(models.Model):
text = models.CharField(max_length=128)
recipe = models.ForeignKey(Recipe)
</code></pre>
<p>I'd like a flat list of all ingredients in all recipes from a particular book. What's the best way to express this in Python?</p>
<p>If I was using LINQ, I might write something like this:</p>
<pre><code>var allIngredients = from recipe in book.Recipes
from ingredient in recipe.Ingredients
select ingredient;
</code></pre>
|
<p>Actually, it looks like there's a better approach using filter:</p>
<pre><code>my_book = Book.objects.get(pk=1)
all_ingredients = Ingredient.objects.filter(recipe__book=my_book)
</code></pre>
|
<p>To print each recipe and its ingredients:</p>
<pre><code>mybook = Book.objects.get(name="Jason's Cookbook")
for recipe in mybook.recipe_set.all():
print recipe.name
for ingredient in recipe.ingredients:
print ingredient.text
</code></pre>
<p>And if you just want to get a list of all ingredient objects:</p>
<pre><code>mybook = Book.objects.get(name="Jason's Cookbook")
ingredient_list = []
for recipe in mybook.recipe_set.all():
for ingredient in recipe.ingredients:
ingredient_list.append(ingredient)
</code></pre>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects" rel="nofollow noreferrer">Documentation</a>.</p>
| 37,624
|
<p>What's the best way to pass data from one Windows Forms app (an office plugin) to another (exe written in C#) in C#? </p>
|
<p>I'll take a wild stab at this and say you probably want the office app to <em>phone home</em> to your exe? In this context, the "exe" is the server and the office app is the client.</p>
<p>If you're using .NET 3.0, WCF is likely your best bet. I would structure the solution into three parts:</p>
<ol>
<li>"Shared Contracts". These are interfaces that describe your services. If you have custom data objects that will be passed between the applications, they should be defined in this assembly as well. This assembly is shared between the client and the server. See "<a href="https://learn.microsoft.com/en-us/dotnet/framework/wcf/designing-service-contracts" rel="nofollow noreferrer">Designing Service Contracts</a>" for more info.</li>
<li>"Service". This assembly is your "exe" and it will reference the contracts and define the classes based on your service contracts. Your app will also host a ServiceClient for your service. The configuration file for this app will define how your ServiceClient will be exposed to the client (available as a web service, tcp, etc). See "<a href="https://learn.microsoft.com/en-us/dotnet/framework/wcf/implementing-service-contracts" rel="nofollow noreferrer">Implementing Service Contracts</a>" for more info.</li>
<li>"Client". Your plugin will reference the "Shared Contracts" assembly and will contain service-clients based on the contracts. The client can be auto-generated using the svcutil.exe tool.</li>
</ol>
<p>Both the "exe" and the "plugin" will require configuration files that define the bindings.</p>
<p>When you want to pass data between client and server, your client will create an object from the "Shared Contracts" assembly and pass it to the service-client. The client's configuration file will figure out where to send the data.</p>
<p>For a step-by-step tutorial on how to create a basic WCF service, <a href="https://learn.microsoft.com/en-us/dotnet/framework/wcf/getting-started-tutorial" rel="nofollow noreferrer">check out this Tutorial</a>.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx" rel="nofollow noreferrer">WCF</a> is one of the easiest ways to do this. You can register a service endpoint in each app, or if one is the service and another is the client you can just use a single service host.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms734712.aspx" rel="nofollow noreferrer">Check out the getting started tutorials.</a></p>
| 28,758
|
<p>We are considering switching from Adobe Flex to Silverlight because Flex is just too slow.</p>
<p>I'm interested not in graphical performance, but computational performance and the speed at which it executes code.</p>
<p>Does anyone have any anecdotes to share about their experience of Silverlight performance?</p>
|
<p>Unlike Flex, Silverlight is multi-threaded. Which if used properly gives you the ability to write highly performant apps. There are many articles and blog posts on this. Here's a sample...</p>
<p><a href="http://www.silverlighthack.com/post/2008/09/07/Silverlight-MultiThreading-with-a-Computational-Process-(Counting-Primes).aspx" rel="nofollow noreferrer">http://www.silverlighthack.com/post/2008/09/07/Silverlight-MultiThreading-with-a-Computational-Process-(Counting-Primes).aspx
</a></p>
|
<p>I've found that Silverlight handles the computational performance quite well. I've been disapointed by some of the graphical performance. Since that isn't you problem, I'd suggest some test with a few complex processes. I haven't used Flex, so I don't have a my own test for the difference.</p>
| 47,524
|
<p>I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.</p>
<p>I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it <em>does</em> show the symbol.</p>
<p>I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.</p>
<p>What else could it be, and how can I try to fix?</p>
<p>Here's the excerpt from running make test:</p>
<pre><code>PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/01basic...........1/4
# Failed test 'use SGML::Parser::OpenSP;'
# at t/01basic.t line 14.
# Tried to use 'SGML::Parser::OpenSP'.
# Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication
# Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle
# Expected in: dynamic lookup
# at (eval 3) line 2
# Compilation failed in require at (eval 3) line 2.
# BEGIN failed--compilation aborted at (eval 3) line 2.
</code></pre>
|
<p>If you use the Settings for the project, you can mark each setting as either application or user.</p>
<p>If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user.</p>
<p>Code project has a really detailed <a href="http://www.codeproject.com/KB/dotnet/user_settings.aspx" rel="nofollow noreferrer">article</a> on saving all types of settings.</p>
|
<p>app.config isn't what you want to use for user-tweakable data, as it'll be stored somewhere in Program Files (which the user shouldn't have write permissions to). Instead, settings marked with <code>a UserScopedSettingAttribute</code> will end up in a user-scoped .config file somewhere in %LocalAppData%.</p>
<p>I found the best way to learn this stuff was to mess with the Visual Studio "Settings" tab (on your project's property pages), then look at the code that it generates and look in %LocalAppData% to see the file that it generates.</p>
| 5,699
|
<p>In a <a href="https://stackoverflow.com/questions/9033#9099">question answer</a> I find the following coding tip:-</p>
<p>2) simple lambdas with one parameter:</p>
<pre><code>x => x.ToString() //simplify so many calls
</code></pre>
<p>As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.</p>
<p>I've researched lambdas so I <strong>think</strong> I know what they do, however I <strong>may</strong> not fully understand so a <strong>little</strong> unpacking might also be in order.</p>
|
<p>When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name:</p>
<pre><code>List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(p => p.Name == "Jon");
</code></pre>
<p>In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not <em>too</em> bad:</p>
<pre><code>List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(delegate(Person p) { return p.Name == "Jon"; });
</code></pre>
<p>In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures:</p>
<pre><code>public Person FindByName(List<Person> list, String name)
{
return list.Find(p => p.Name == name); // The "name" variable is captured
}
</code></pre>
<p>There's more about this in <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="nofollow noreferrer">my article about closures</a>.</p>
<p>While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5.</p>
|
<pre><code>string delegate(TypeOfX x)
{
return x.ToString();
}
</code></pre>
| 18,978
|
<p>I printed a lot of models in last month. I spent 2 kg filament in total. I want to know how many hours have been passed while printing. As far as I read, 1 kg PLA (1.75 mm) is about 110 meters long. My default print speed is 70 mm/s. The nozzle diameter is 0.4 mm. The nozzle multiplier in the simplify3d is 0.9 .</p>
<p>In a very basic math,
220÷(0.7×0.04÷0.0175×0.9)=~ 153 hours.</p>
<p>Is this correct?</p>
|
<p>Your formula doesn't seem to take into account two important factors: layer height and average speed.</p>
<p>Do the math differently:</p>
<p>voumetric flow rate [mm^3/s] = layer height [mm] * line width [mm] * speed [mm/s]</p>
<p>For example, 0.2 * 0.45 * 70 = 6.3 mm^3/s</p>
<p>which is realistic, the extruder on the Ender 3 cannot go much faster than that reliably.</p>
<p>PLA weighs 1.24 g/cm^3 = 0.00124 g/mm^3</p>
<p>To extrude 1 kg you need 1000/(0.00124 * 6.3) = 35 hours (70 for 2 kg).</p>
<p>However the printer does not reach 70 mm except on straight long moves, the average speed may be lower or much lower depending on what you print.</p>
<p>If you print technical parts with straight edges, maybe you can multiply by 1.5 (50 hours/kg), but if you print models and small statues or similar you may need to double it (70 hours/kg).</p>
<p>I use Klipper as firmware and I have a macro which keeps track of printing time and filament length used.</p>
|
<p>Your math looks correct, and is also a good approximation for what I've seen in the first few weeks with my own Ender 3.</p>
<p>Another way to calculate (to check yourself) is to calculate the volume extruded (nozzle area times extrusion percentage times print speed -- be sure you convert everything to the same units!) in a given second, multiply by the density of your filament (common PLA runs about 1.2 g/cm^3), and get a rough figure for how long it takes to print a kilogram of filament. Your actual print time will always be higher than this approximation, because there are moves during which the extruder isn't running, infill is often set to lower extrusion level, and of course there's setup and cleanup time to account for.</p>
| 1,950
|
<p>How can I make a Facebook RSS application that autoupdates from the provided RSS feeds.
Of course doing this is trivial for canvas applications, but I need this for showing on the Facebook Page. All the RSS apps I've taken a look at either dont update or dont work on Facebook Pages. </p>
<p>Especially now that infinite session keys are deprecated (and maybe even forbidden). </p>
|
<p>I specifically said I do not need this for canvas applications (as that is trivial to do), but on Facebook Pages!
This is done with <a href="http://wiki.developers.facebook.com/index.php/Profile.setFBML" rel="nofollow noreferrer">profile.setFBML</a> and data published that way does reside on the facebook servers. </p>
|
<p>You have two options. </p>
<ol>
<li><p>Convert your user session (when the user accesses your app manually) to infinite session, then periodically update the profile information for a user. There is some information on how to do this (and what API calls you can make without sessions) <a href="http://wiki.developers.facebook.com/index.php/Authorizing_Applications#About_Session_Keys" rel="nofollow noreferrer">here</a>.</p></li>
<li><p>Create a new "handle" (see <a href="http://wiki.developers.facebook.com/index.php/Fb:ref" rel="nofollow noreferrer"><code>fb:ref</code></a>) for each unique feed and update that handle whenever the feed changes. Handles are key-values pairs that are associated with your app, that you can include inline through FBML. This allows you to do a single call to the API that will update all users subscribed to a given feed.</p></li>
</ol>
<p>The second option is probably the best in the long run.</p>
| 12,521
|
<p>Are there any good programs for dealing with reading large CSV files? Some of the datafiles I deal with are in the 1 GB range. They have too many lines for Excel to even deal with. Using Access can be a little slow, as you have to actually import them into a database to work with them directly. Is there a program that can open large CSV files and give you a simple spreadsheet layout to help you easily and quickly scan through the data?</p>
|
<p>MySQL can import CSV files very quickly onto tables using the <a href="http://dev.mysql.com/doc/refman/5.0/en/load-data.html" rel="noreferrer"><code>LOAD DATA INFILE</code></a> command. It can also read from CSV files directly, bypassing any import procedures, by using the <a href="http://dev.mysql.com/doc/refman/5.0/en/csv-storage-engine.html" rel="noreferrer">CSV storage engine</a>.</p>
<p>Importing it onto native tables with <code>LOAD DATA INFILE</code> has a start up cost, but after that you can <code>INSERT/UPDATE</code> much faster, as well as index fields. Using the CSV storage engine is almost instantaneous at first, but only sequential scan will be fast.</p>
<p><strong>Update</strong>: <a href="http://dev.mysql.com/tech-resources/articles/csv-storage-engine.html" rel="noreferrer">This article</a> (scroll down to the section titled <em>Instant Data Loads</em>) talks about using both approaches to loading CSV data onto MySQL, and gives examples.</p>
|
<p>vEdit is great but don't forget you can always go back to "basics" check out <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a> and start greping.</p>
<p>Helpfull commands</p>
<ul>
<li>grep </li>
<li>head</li>
<li>tail</li>
<li>of course perl!</li>
</ul>
| 6,602
|
<p>How would I disable and later enable all indexes in a given schema/database in Oracle?</p>
<p>Note: This is to make sqlldr run faster.</p>
|
<p>Here's making the indexes unusable without the file:</p>
<pre><code>DECLARE
CURSOR usr_idxs IS select * from user_indexes;
cur_idx usr_idxs% ROWTYPE;
v_sql VARCHAR2(1024);
BEGIN
OPEN usr_idxs;
LOOP
FETCH usr_idxs INTO cur_idx;
EXIT WHEN NOT usr_idxs%FOUND;
v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE';
EXECUTE IMMEDIATE v_sql;
END LOOP;
CLOSE usr_idxs;
END;
</code></pre>
<p>The rebuild would be similiar.</p>
|
<p>You should try sqlldr's SKIP_INDEX_MAINTENANCE parameter.</p>
| 15,692
|
<p>The documentation indicates that the error: option function will make available: XHR instance, a status message string (in this case always error) and an optional exception object returned from the XHR instance (Book: JQuery in Action)</p>
<p>Using the following (in the $.ajax call) I was able to determine I had a "parsererror" and a "timeout" (since I added the timeout: option) error</p>
<pre><code>error: function(request, error){}
</code></pre>
<p>What are other things you evaluate in the error option? do you include the optional exception object?</p>
<p><strong>EDIT:</strong> one of the answers indicates all the return errors...learning more about what is of value (for debugging) in the XHR instance and exception object would be helpful</p>
<p>This is a complete $.ajax call:</p>
<pre><code>$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
dataType: "text",
data: {
'_service' : 'myService',
'_program' : 'myProgram',
'start' : start,
'end' : end
},
beforeSend: function() {
$("#loading").removeClass("hide");
},
timeout: 5000,
error: function(request,error) {
$("#loading").addClass("hide");
if (error == "timeout") {
$("#error").append("The request timed out, please resubmit");
}
else {
$("#error").append("ERROR: " + error);
}
},
success: function(request) {
$("#loading").addClass("hide");
var t = eval( "(" + request + ")" ) ;
} // End success
}); // End ajax method
</code></pre>
<p>Thanks for the input</p>
|
<p>Looking at the jQuery source code, there are four returned statuses, in additon to <strong>success</strong>:</p>
<ul>
<li><strong>timeout</strong> - when your specified
timeout is exceeded</li>
<li><strong>error</strong> - http error, like 404</li>
<li><strong>notmodified</strong> - when requested
resource was not modified since last
request</li>
<li><strong>parsererror</strong> - when an xml/json response is
bad</li>
</ul>
|
<p>Are you sure that response is correct? Parse error mean that there is sth wrong with data being evaluted in line
<code>var t = eval( "(" + request + ")" ) ;</code></p>
| 12,114
|
<p>I'm trying to install a site under an alternative port on a server, but the port may be closed by a firewall. Is there a way to ping out or in, on a specific port, to see if it is open?</p>
|
<p>Assuming that it's a TCP (rather than UDP) port that you're trying to use:</p>
<ol>
<li><p>On the server itself, use <code>netstat -an</code> to check to see which ports are listening.</p></li>
<li><p>From outside, just use <code>telnet host port</code> (or <code>telnet host:port</code> on Unix systems) to see if the connection is refused, accepted, or timeouts.</p></li>
</ol>
<p>On that latter test, then in general:</p>
<ul>
<li><em>connection refused</em> means that nothing is running on that port</li>
<li><em>accepted</em> means that something is running on that port</li>
<li><em>timeout</em> means that a firewall is blocking access</li>
</ul>
<p>On Windows 7 or Windows Vista the default option 'telnet' is not recognized as an internal or external command, operable program or batch file. To solve this, just enable it: Click *Start** → <strong>Control Panel</strong> → <em>Programs</em> → <em>Turn Windows Features</em> on or off. In the list, scroll down and select <em>Telnet Client</em> and click <kbd>OK</kbd>.</p>
|
<p>Another utility that I found and is good and small as well, is <a href="https://www.microsoft.com/en-us/download/details.aspx?id=17148" rel="nofollow noreferrer">PortQry Command Line Port Scanner version 2.0</a>.</p>
<p>You can ping a server and a port and it will tell you the state of the port. There is a command-line utility and a UI for it.</p>
| 34,403
|
<p>This has been a problem that I haven't been able to figure out for sometime. Preventing the second instance is trivial and has many methods, however, bringing back the already running process isn't. I would like to:</p>
<ul>
<li>Minimized: Undo the minimize and bring the running instance to the front.</li>
<li>Behind other windows: Bring the application to the front.</li>
</ul>
<p>The language I am using this in is VB.NET and C#.</p>
|
<p>I found this code to be useful. It does the detection and optional activation of an existing application:</p>
<p><a href="http://www.codeproject.com/KB/cs/cssingprocess.aspx" rel="noreferrer">http://www.codeproject.com/KB/cs/cssingprocess.aspx</a></p>
|
<p>Here is a simple and easily understandable method for preventing duplicate concurrent execution (written in c#).</p>
<pre><code>public static void StopProgramOnSecondRun()
{
string
//Get the full filename and path
FullEXEPath = System.Reflection.Assembly.GetEntryAssembly().Location,
//Isolate just the filename with no extension
FilenameWithNoExtension = System.IO.Path.GetFileNameWithoutExtension(FullEXEPath);
//Retrieve a list of processes that have the same name as this one wich is FilenameWithNoExtension
Process[] processes = System.Diagnostics.Process.GetProcessesByName(FilenameWithNoExtension);
//There should always be at least one process returned. If the number is greater than one. Than this is the clone and we must kill it.
if (processes.Length > 1)
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
</code></pre>
| 11,993
|
<p>I've heard powershell 2.0 CTP has modules, but I can't find much example code or instructions. I've read what little help there seems to be online...</p>
<p>But I just keep getting "The term 'Add-Module' is not recognized as a cmdlet..." when I try and load a module.</p>
<p>Any help would be gratefully received!</p>
<p><strong><em>Edit</em></strong> (July 2010)
Please note this question is based on powershell 2.0 CTP and is therefore a year and half out of date! Please see Samuel Jack's answer for help with the powershell 2.0 RTM.</p>
|
<p>With the Win7 build, Add-Module is gone. The new cmdlet is Import-Module. The easiest way to create a module is rename a PS1 file to a PSM1 file. From there you can do all sorts of things including the module manifest.</p>
|
<p>Windows PowerShell v2.0: TFM (sapienpress.com) has information and samples in one of the chapters. It's available as an ebook which is updated as new CTPs are released. I also blogged about them on ConcentratedTech.com, and there's been discussion on them at PowerShellCommunity.org in the forums.</p>
| 44,367
|
<p>What is the best way to read and/or set Internet Explorer options from a web page in Javascript? I know that these are in registry settings.</p>
<p>For example, I'm using the <a href="http://www.lutanho.net/diagram/" rel="nofollow noreferrer">JavaScript Diagram Builder</a> to dynamically generate bar charts within a web page. This uses the background color in floating DIVs to generate the bars. I would like to be able to read the browser setting for printing background colors, and if not checked, either warn the user that the colors won't print, or programatically select this option.</p>
<p>EDIT: As I think about the products that do something similar, I think they mostly just test whether Java or JavaScript or Cookies are disabled, which can be done without reading the registry.</p>
<p>So I guess the consensus is that what I want to do shouldn't be attempted.</p>
|
<p>Web pages have no business reading users' settings, therefore there is no interface for this.</p>
|
<p>This sounds like it would be a big security hole, one that the IE team would keep nailed very shut</p>
| 31,353
|
<p>I have many different branches/checkouts of the same project code on my development machine. Each one is virtually the same except for various maintenance bug fixes or improvements I'm working on within each project.</p>
<p>The problem comes when I use Find in Files inside Visual Studio to search through my code. VS2005 stores the last search directory that was used in its Find in Files dialog ... this may or may not be the project directory I'm working on. Since my projects are so similar, it's easy to accidentally search through a similar project, change some code, and only realize later that I've edited the wrong project. (Argh!!)</p>
<p>Is there a way to make VS default its Find in Files search to the project directory? Obviously a properties setting would be wonderful, but an add-in would be fine too.</p>
|
<p>This drives me nuts too. But in "Look In:" dropdown on the find in files dlg you will find items for Solution and project. I think that should work for you.</p>
|
<p>In VS2008, with no files open, when I select 'Current Project' it searches whatever project is currently selected in the Solution Explorer. When I switch between files in different projects, it correctly searches the project of the currently selected file. I don't see any options for changing this behavior.</p>
| 44,486
|
<p>I am trying to migrate a part of an SVN repository using <code>svnadmin dump</code>.</p>
<p>The provided svndumpfilter tool doesn't manage copy/move/rename dependencies from directories not included in the export.</p>
<p>Is there a tool which can manage these dependencies?</p>
|
<p>I found a Python script by Simon Tatham called <a href="http://svn.tartarus.org/sgt/svn-tools/svndumpfilter2?view=markup" rel="nofollow noreferrer">svndumpfilter2</a>, which tries to cope with simple dependencies (I found some limitations, though).</p>
<p>You can also check an <a href="http://www.chiark.greenend.org.uk/~sgtatham/svn.html" rel="nofollow noreferrer">article</a> about his migration to Subversion and the motivation for the script.</p>
|
<p>With dependencies you mean those specified by the property svn:external?</p>
<p>If yes, I think you should pass to svndumpfilter also the paths referrend in the property.
For example, if your project is in <code>http://host/project</code> and the svn:external property is set to <code>http://host/dependencies</code> you can do something like</p>
<pre><code>svndumpfilter include http://host/project http://host/dependencies < total.dump > project.dump
</code></pre>
| 32,269
|
<p>During navigation of the <code>java.lang.reflect.Method</code> class I came across the method <code>isBridge</code>. Its Javadoc says that it returns true only if the Java spec declares the method as true.</p>
<p>Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?</p>
|
<p>A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments. </p>
<p>You can find in this class <a href="https://fisheye.springsource.org/browse/spring-framework/spring-core/src/main/java/org/springframework/core/BridgeMethodResolver.java?r=02a4473c62d8240837bec297f0a1f3cb67ef8a7b" rel="noreferrer">BridgeMethodResolver</a> a way to get the actual Method referred by a 'bridge method'.</p>
<p>See <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5" rel="noreferrer">Create Frame, Synchronize, Transfer Control</a>:</p>
<p>As an example of such a situation, consider the declarations:</p>
<pre><code>class C<T> { abstract T id(T x); }
class D extends C<String> { String id(String x) { return x; } }
</code></pre>
<p>Now, given an invocation</p>
<pre><code>C c = new D();
c.id(new Object()); // fails with a ClassCastException
</code></pre>
<p>The erasure of the actual method being invoked, <code>D.id(String)</code> differs in its signature from that of the compile-time method declaration, <code>C.id(Object)</code>. The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed.</p>
<p>Such situations can only arise if the program gives rise to an unchecked warning (<a href="http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190772" rel="noreferrer">§5.1.9</a>).</p>
<p>Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D:</p>
<pre><code>Object id(Object x) { return id((String) x); }
</code></pre>
<p>This is the method that would actually be invoked by the Java virtual machine in response to the call <code>c.id(new Object())</code> shown above, and it will execute the cast and fail, as required.</p>
<p>See also <strong><a href="http://books.google.com/books?id=zaoK0%5A2STlkC&pg=PA50&lpg=PA50&dq=java+bridge+%22covariant+return+types%22&source=web&ots=6WoofeXYFM&sig=8bS5Y0sw%5ApBu%5ACuf1EkIR_L4Ddo&hl=en&sa=X&oi=book_result&resnum=4&ct=result#PPA48,M1" rel="noreferrer">Bridge</a></strong>:</p>
<p>as mentioned in the comment, bridge methods are also needed for <strong>covariant overriding</strong>:</p>
<ul>
<li>In Java 1.4, and earlier, one method can override another if the signatures match
exactly.</li>
<li>In Java 5, a method can override another if the arguments match exactly <em>but the return type</em> of the overriding method, if it is a <em>subtype</em> of the return type of the other method.</li>
</ul>
<p>Typically, a method <code>Object clone()</code> can be overridden by a <code>MyObject clone()</code>, but a bridge method will be generated by the compiler:</p>
<pre><code>public bridge Object MyObject.clone();
</code></pre>
|
<p>Another case I stumbled across has nothing to do with generics:</p>
<pre><code>protected abstract class Super {
public void m() {}
}
public class Sub extends Super {}
assert Sub.class.getMethod("m").isBridge();
</code></pre>
| 36,908
|
<p>The client has asked for a number of tables to be extracted into csv's, all done no problem. They've just asked we make sure the files are always in UTF 8 format.</p>
<p>How do I check this is actually the case. Or even better force it to be so, is it something i can set in a procedure before running a query perhaps?</p>
<p>The data is extracted from an Oracle 10g database.</p>
<p>What should I be checking?</p>
<p>Thanks</p>
|
<p>You can check the database character set with the following query:</p>
<pre><code>select value from nls_database_parameters
where parameter='NLS_CHARACTERSET'
</code></pre>
<p>If it says AL32UTF8 then your database is in the format what you need and if the export does not impair it then your are done.</p>
<p>You may read about Oracle globalization support <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch6unicode.htm" rel="noreferrer">here</a>, and <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14225/ch3globenv.htm" rel="noreferrer">here</a> about NLS parameters like the above.</p>
|
<p>What you have to look for is the eight-bit ascii characters in hte input (if any) are translated into double byte utf-8 characters.</p>
<p>This is highly dependant on your local ASCII code page but typically:-
ASCII "£" should be x'A3' in ascii magically becomes x'C2A3' in utf-8.</p>
| 46,341
|
<p>I have an app which consists of several different assemblies, one of which holds the various interfaces which the classes obey, and by which the classes communicate across assembly boundaries. There are several classes firing events, and several which are interested in these events. </p>
<p>My question is as follows: is it good practice to implement a central EventConsolidator of some kind? This would be highly coupled, as it would need to know every class (or at least interface) throwing an event, and every consumer of an event would need to have a reference to EventConsolidator in order to subscribe. </p>
<p>Currently I have the situation where class A knows class B (but not C), class B knows class C, etc. Then if C fires an event B needs to pick it up and fire its own event in order for A to respond. These kinds of chains can get quite long, and it may be that B is only interested in the event in order to pass it along. I don't want A to know about C though, as that would break encapsulation. </p>
<p>What is good practice in this situation? Centralise the events, or grin and bear it and define events in each intermediate class? Or what are the criteria by which to make the decision? Thanks!</p>
<p>Edit: <a href="https://stackoverflow.com/questions/217233/bubbling-up-events">Here</a> is another question asking essentially the same thing.</p>
|
<p>You could put the event itself in an interface, so that A didn't need to know about C directly, but only that it has the relevant event. However, perhaps you mean that the instance of A doesn't have sight of an instance of C...</p>
<p>I would try to steer clear of a centralised event system. It's likely to make testing harder, and introduced tight coupling as you said.</p>
<p>One pattern which is worth knowing about is making event proxying simple. If B only exposes an event to proxy it to C, you can do:</p>
<pre><code>public event FooHandler Foo
{
add
{
c.Foo += value;
}
remove
{
c.Foo -= value;
}
}
</code></pre>
<p>That way it's proxying the subscription/unsubscription rather than the act of raising the event. This has an impact on GC eligibility, of course - which may be beneficial or not, depending on the situation. Worth thinking about though.</p>
|
<p>we have our own event broker implementation (open source)
Tutorial at: <a href="http://sourceforge.net/apps/mediawiki/bbvcommon/index.php?title=Event_Broker" rel="nofollow noreferrer">http://sourceforge.net/apps/mediawiki/bbvcommon/index.php?title=Event_Broker</a></p>
<p>And a performance analysis at: www.planetgeek.ch/2009/07/12/event-broker-performance/</p>
<p>Advantages compared to CAB:
- better logging
- extension support
- better error handling
- extendable handlers (UI, Background Thread, ...)
and some more I cannot recall right now.</p>
<p>Cheers,
Urs</p>
| 37,703
|
<p>I have a string that is like below.</p>
<pre><code>,liger, unicorn, snipe
</code></pre>
<p>in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?</p>
<p>Thanks.</p>
<hr>
<p><em>There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.</em></p>
|
<pre><code>string sample = ",liger, unicorn, snipe";
sample = sample.TrimStart(','); // to remove just the first comma
</code></pre>
<p>Or perhaps:</p>
<pre><code>sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma
</code></pre>
|
<pre><code>if (s.StartsWith(",")) {
s = s.Substring(1, s.Length - 1);
}
</code></pre>
| 9,935
|
<p>If you have a web application that will run inside a network, it makes sense for it to support windows authentication (active directory?).</p>
<p>Would it make sense to use AD security model as well, or would I make my own roles/security module that some admin would have to configure for each user?</p>
<p>I've never dealt with windows security before, so I am very confused as to how I should be handling security for a web application that runs within a windows network.</p>
<p>I guess there are 2 major points I have to tackle:</p>
<pre><code>1. authentication
2. authorization
</code></pre>
<p>I have a feeling that best-practice would say to handle authorization myself, but use AD authentication right?</p>
|
<p>Basically windows handles everything, you never store usernames or passwords, AD and IIS do all the work for you</p>
<p>add this to your <code>web.config</code></p>
<pre><code> <system.web>
...
<authentication mode="Windows"/>
...
</system.web>
</code></pre>
<p>To configure Windows authentication</p>
<ol>
<li>Start Internet Information Services
(IIS). </li>
<li>Right-click your
application's virtual directory, and
then click Properties. </li>
<li>Click the
Directory Security tab. </li>
<li>Under
Anonymous access and authentication
control, click Edit. </li>
<li><strong>Make sure the
Anonymous access check box is not
selected</strong> and that <strong>Integrated Windows
authentication is the only selected
check box</strong>.</li>
</ol>
<p>You can then deal with the business or authorization using <code>web.config</code> again. for example</p>
<pre><code><authorization>
<deny users="DomainName\UserName" />
<allow roles="DomainName\WindowsGroup" />
</authorization>
</code></pre>
<p>Read more here: <a href="http://msdn.microsoft.com/en-us/library/ms998358.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms998358.aspx</a></p>
|
<p>I used windows security on some of my internal sites.</p>
<p>Basically the way I set it up is I remove anonymous access in IIS, then assign permissions on the sites files though the standard windows security model.</p>
<p>I'm not sure if this is the best practices, but it has always worked well for me.</p>
| 47,073
|
<p>Please post a working source code example (or link) of how to search string in another process memory and getting offset of match if found. The similar way its done in game cheating utils which search for values in game memory using ReadProcessMemory.</p>
|
<p>Internationalization is hard, here's a few things I've learned from working with 2 websites that were in over 20 different languages:</p>
<ul>
<li>Use UTF-8 everywhere. No exceptions. HTML, server-side language (watch out for PHP especially), database, etc.</li>
<li>No text in images unless you want a ton of work. Use CSS to put text over images if necessary.</li>
<li>Separate configuration from localization. That way localizers can translate the text and you can deal with different configurations per locale (features, layout, etc). You don't want localizers to have the ability to mess with your app.</li>
<li>Make sure your layouts can deal with text that is 2-3 times longer than English. And also 50% less than English (Japanese and Chinese are often shorter).</li>
<li>Some languages need larger font sizes (Japanese, Chinese)</li>
<li>Colors are locale-specific also. Red and green don't mean the same thing everywhere!</li>
<li>Add a classname that is the locale name to the body tag of your documents. That way you can specify a specific locale's layout in your CSS file easily. </li>
<li>Watch out for variable substitution. Don't split your strings. Leave them whole like this: "You have X new messages" and replace the 'X' with the #. </li>
<li>Different languages have different pluralization. 0, 1, 2-4, 5-7, 7-infinity. Hard to deal with. </li>
<li>Context is difficult. Sometimes localizers need to know where/how a string is used to make sure it's translated correctly.</li>
</ul>
<p>Resources:</p>
<ul>
<li><a href="http://interglacial.com/~sburke/tpj/as_html/tpj13.html" rel="noreferrer">http://interglacial.com/~sburke/tpj/as_html/tpj13.html</a></li>
<li><a href="http://www.ryandoherty.net/2008/05/26/quick-tips-for-localizing-web-apps/" rel="noreferrer">http://www.ryandoherty.net/2008/05/26/quick-tips-for-localizing-web-apps/</a></li>
<li><a href="http://ed.agadak.net/2007/12/one-potato-two-potato-three-potato-four" rel="noreferrer">http://ed.agadak.net/2007/12/one-potato-two-potato-three-potato-four</a></li>
</ul>
|
<p>I have a couple apps that are "bilingual"
I used resource files in ASP.NET1.1</p>
<p>There is also something called the String Resource Tool
Basically you put all your strings in a .RES file for both languages and then determine what file to read from based on Culture or whether someone clicked a Link for the language</p>
<p>The biggest gotcha is making sure the Translations are done correctly</p>
| 18,837
|
<p>Often, I find myself wanting to write a unit test for a portion of code that accesses HTTP resources as part of its normal function. Have you found any good ways to write these kinds of tests?</p>
|
<p>Extract the part that accesses the HTTP resources out of your main code. Create an interface for that new component, In your test, mock the interface and return data that you can control reliably.</p>
<p>You can test the HTTP access as an integration test.</p>
|
<p>This is typically a function I would mock out for the tests... I don't like my tests depending on anything external... even worse if it is an external resource I have no control over (such as a 3rd party website).</p>
<p>Databases is one of the few external resources I often won't mock... I use DBUnit instead.</p>
| 9,411
|
<p>I am searching for a good system for PHP, which does UnitTesting, Subversion, Coding Standards.</p>
<p>I would love to hear your suggestions and which one is the best and why.
I will be running it on a debian server so anything which runs on mac or windows servers would be out of the question.</p>
|
<p>I second Hudson for CI and PHP. I have written a tutorial on setting it up if you are interested.</p>
<p>Edit:</p>
<p>My tutorial is out of date.</p>
<p>I highly recommend: <a href="http://jenkins-php.org/" rel="nofollow noreferrer">http://jenkins-php.org/</a></p>
|
<p>If it's continuous integration that you're looking for have you checked out <a href="http://www.jetbrains.com/teamcity/" rel="nofollow noreferrer">TeamCity</a>? It's not specifically for PHP but it's <em>very</em> easy to set up and manage. It's also free for the <a href="http://www.jetbrains.com/teamcity/buy/buy.jsp#professional" rel="nofollow noreferrer">professional licence</a> (20 build configs) and for <a href="http://www.jetbrains.com/teamcity/buy/buy.jsp#openSource" rel="nofollow noreferrer">open source projects</a>.</p>
| 17,402
|
<p>So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.</p>
<p>As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance. </p>
<p>So, I have device functions that want to access a device allocated array.</p>
<p>Ideally, I could do something like:</p>
<pre><code>__device__ float* global_data;
main()
{
cudaMalloc(global_data);
kernel1<<<blah>>>(blah); //access global data
kernel2<<<blah>>>(blah); //access global data again
}
</code></pre>
<p>However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:</p>
<pre><code>__device__ float global_data[REALLY_LARGE_NUMBER];
</code></pre>
<p>And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach.</p>
|
<p>Something like this should probably work.</p>
<pre><code>#include <algorithm>
#define NDEBUG
#define CUT_CHECK_ERROR(errorMessage) do { \
cudaThreadSynchronize(); \
cudaError_t err = cudaGetLastError(); \
if( cudaSuccess != err) { \
fprintf(stderr, "Cuda error: %s in file '%s' in line %i : %s.\n", \
errorMessage, __FILE__, __LINE__, cudaGetErrorString( err) );\
exit(EXIT_FAILURE); \
} } while (0)
__device__ float *devPtr;
__global__
void kernel1(float *some_neat_data)
{
devPtr = some_neat_data;
}
__global__
void kernel2(void)
{
devPtr[threadIdx.x] *= .3f;
}
int main(int argc, char *argv[])
{
float* otherDevPtr;
cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));
cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));
kernel1<<<1,128>>>(otherDevPtr);
CUT_CHECK_ERROR("kernel1");
kernel2<<<1,128>>>();
CUT_CHECK_ERROR("kernel2");
return 0;
}
</code></pre>
<p>Give it a whirl.</p>
|
<p>Erm, it was exactly that problem of moving devPtr to global scope that was my problem.</p>
<p>I have an implementation that does exactly that, with the two kernels having a pointer to data passed in. I explicitly don't want to pass in those pointers.</p>
<p>I have read the documentation fairly closely, and hit up the nvidia forums (and google searched for an hour or so), but I haven't found an implementation of a global dynamic device array that actually runs (i have tried several that compile and then fail in new and interesting ways).</p>
| 10,449
|
<ol>
<li>Is it possible to secure only the Login.aspx page (and the postback) and not the whole site in IIS?</li>
<li>We are looking to do this specifically with a SharePoint site running Forms Based Authentication against our Active Directory.</li>
<li>Links to this will be helpful.</li>
</ol>
<p>This is what we have done so far:<br>
1. Setup SharePoint to use FBA against AD.<br>
2. Moved Login Page to Secure/Login.aspx<br>
3. Set the appropriate Login url in web.config as <code>https://..../Secure/Login.aspx</code></p>
<p>This is not working and help is needed here.
However even if this works, how do we get the user back to http from https?</p>
|
<p>There's not a whole lot of point. If the only thing that's encrypted is the Login.aspx page, that would mean that someone could sniff all the traffic that was not sent through the login page.</p>
<p>Which might prevent people from getting user:pass, but all your other data is exposed.</p>
|
<p>Besides all the data which is exposed, and the user's operation which can be changed en route, the user's session id (or other authentication data) is sent in the clear. This means that an attacker can steal your cookie (...) and impersonate you to the system, even without getting your password. (If I remember correctly SPSv.3 also supports builtin password changing module...)<br>
So I would say that this is not a Great Idea, unless you dont care about that system very much anyway.... But then, why bother with authentication at all? just make it anonymous?</p>
| 16,351
|
<p>I have a table with the following columns:</p>
<pre>
A B C
---------
1 10 X
1 11 X
2 15 X
3 20 Y
4 15 Y
4 20 Y
</pre>
<p>I want to group the data based on the B and C columns and count the distinct values of the A column. But if there are two ore more rows where the value on the A column is the same I want to get the maximum value from the B column.</p>
<p>If I do a simple group by the result would be:</p>
<pre>
B C Count
--------------
10 X 1
11 X 1
15 X 1
20 Y 2
15 Y 1
</pre>
<p>What I want is this result:</p>
<pre>
B C Count
--------------
11 X 1
15 X 1
20 Y 2
</pre>
<p>Is there any query that can return this result. Server is SQL Server 2005.</p>
|
<p>I like to work in steps: first get rid of duplicate A records, then group. Not the most efficient, but it works on your example.</p>
<pre><code>with t1 as (
select A, max(B) as B, C
from YourTable
group by A, C
)
select count(A) as CountA, B, C
from t1
group by B, C
</code></pre>
|
<p>Check this out. This should work in Oracle, although I haven't tested it;</p>
<pre><code>select count(a), BB, CC from
(
select a, max(B) BB, Max(C) CC
from yourtable
group by a
)
group by BB,CC
</code></pre>
| 39,715
|
<p>I have several databases for my applications that use SQL Server 2005 mirroring to keep a nice copy of the data somewhere else. Works like a charm, however, the log file just seems to be growing and growing, one is at 15GB for a 3GB database. </p>
<p>Normally, I can just shrink it - however an error pops up that this specifically cannot be done. But, it seems eventually if unchecked would just expand to use all the space on the drive.</p>
<p>I see that I can set a maximum file size for the log file, is that the answer here? Will the log just roll when it hits the max, or will the DB just stop functioning?</p>
<p>Thanks</p>
|
<p>I would look at why your logfile is growing, then you can define a strategy for solving your issue.
It might be worth checking your mirroring state</p>
<p>When a principal database is exposed, it is active with user connections and processing transactions. However, no log records are being sent to the mirror database, and if the principal should fail, the mirror will not have any of the transactions from the principal from the point the principal entered the exposed state. Also, the principal's transaction log cannot be truncated, so the log file will be growing indefinitely.
ref <a href="http://www.microsoft.com/technet/prodtechnol/sql/2005/dbmirror.mspx" rel="nofollow noreferrer">http://www.microsoft.com/technet/prodtechnol/sql/2005/dbmirror.mspx</a></p>
|
<p>Please make sure to perform a full backup after performing log backup with TRUNCATE_ONLY. This breaks the log backup chain.</p>
| 31,323
|
<p>My organization is using CppUnit and I am trying to run the same test using different parameters. Running a loop inside the test is not a good option as any failure will abort the test. I have looked at <code>TestDecorator</code> and <code>TestCaller</code> but neither seems to really fit. Code samples would be helpful.</p>
|
<p>It does not appear possible in CppUnit to parameterize a test case directly (see <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=1090757&group_id=11795&atid=361795" rel="noreferrer">here</a> and <a href="http://sourceforge.net/forum/forum.php?thread_id=1560616&forum_id=37107" rel="noreferrer">here</a>). However, you do have a few options:</p>
<h2>Use a <code>RepeatedTest</code></h2>
<p>You may be able to make some clever use of the built-in <a href="http://cppunit.sourceforge.net/doc/1.11.6/class_repeated_test.html" rel="noreferrer"><code>RepeatedTest</code></a> decorator. This allows a test case to be run multiple times (though without parameterization). </p>
<p>I'll admit to never having used this myself, but perhaps you could have the <code>RepeatedTest</code> drive some gatekeeper function, which would (using a class static variable, perhaps?) pick a different input with every run. It would in turn call the true function you'd like to test with that value as input.</p>
<h2>Use a <code>TestCase</code> subclass</h2>
<p><a href="http://sourceforge.net/forum/forum.php?thread_id=887311&forum_id=37107" rel="noreferrer">One person</a> on CppUnit's SourceForge page claims to have written a subclass of <code>TestCase</code> that will run a particular test an arbitrary number of times, although in a slightly different manner than the <code>RepeatedTest</code> class offers. Sadly, the poster simply described the motivation for creating the class, but did not provide the source code. There was, however, an offer to contact the individual for more details.</p>
<h2>Use a simple helper function</h2>
<p>The most straight-forward (but least automated) way to do this is to create a helper function that takes the parameter you'd like to pass on to your "real" function, and then have lots of individual test cases. Each test case would call your helper function with a different value.</p>
<hr>
<p>If you choose either of the first two options listed above, I'd be interested in hearing about your experience.</p>
|
<p>I'm not a C++ programmer but I can help with the unit-test concept:</p>
<p>Test-cases are meant to run isolated and with no dependency on external parameters. Additionally you should keep the number of test-cases down to the minimum which covers most of your code. There are cases, however (and I have already dealt with some), where some tests look the same, differing only by some minor parameters. The best bet then is to write a <em>fixture</em> which takes the parameter you're talking about, and then have one test-case for each of the parameters, calling the fixture with it. A generic example follows:</p>
<pre><code>class MyTestCase
# this is your fixture
def check_special_condition(param)
some
complex
tests
end
# these are your test-cases
def test_1
check_special_condition("value_1")
end
def test_2
check_special_condition("value_2")
end
end
</code></pre>
<p>Otherwise you're not writing true test-cases, because they're supposed to be reproducible without much knowledge from the one who is executing them. I imagine there are a handful of parameters which are all important as input to the tests. Then why not make each one explicit inside its own test-case? That's also the best way to document then, instead of writing a separate document to guide the programmer which will read the code years later.</p>
| 36,969
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.