text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Is there a free/pay web service that I can query to get MLS data? Given an MLS#, I'd like to get an XML document with details about the listing, like address, price and such. Not a NAR or CREA member. Mostly interested in North American rental property listing data.
A: If you're an NAR member, you can utilize their Internet Data Exchange (IDX) system, but it isn't available to non-members.
A: The best free source at the moment is Oodle.com's API - http://developer.oodle.com/oodle-api. It will give you both for sale and for rent homes.
You can see what their listings look like here: http://realestate.oodle.com/
The MLS' don't typically give their data out. The big rental sites (rent.com, apartments.com, etc.) don't have an API, but do give out data feeds if you contact them and work out a business relationship with them.
A: Multiple Listing Service (MLS) - a system in the USA and Canada for real estate
For mls.ca (Canadian system), here's an interesting perspective (posted 2008-08-21) on it's availability to the public:
Canadian Realtor Data Cartel excerpt:
Realtors as consultants would also mean they could relax their data cartel, also known as the Multiple Listings Service. This database of sale listings has two faces. Firstly, a private view for realtors only, which shows real-time listings with full details about the homes. The MLS also provides a public view of the data but listings there are time-delayed (often by days) and don't provide all useful details such as direction house is facing, wether the basement is developed, etc in a searchable format. Only recently, due to repeated better offerings that were sued out of existence by the cartel, has the MLS even added interactive maps. They still time-delay public listings and hide many useful details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: IE TextRange select method not working properly I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed.
https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995
I've written a test case to demonstrate the effect:
<html>
<body>
<iframe id="editable">
<html>
<body>
<div id="test">
Click to the right of this line ->
<p id="par">Block Element</p>
</div>
</body>
</html>
</iframe>
<input id="mytrigger" type="button" value="Then Click here to Save and Restore" />
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
// An IFRAME without a source points to a blank document. Here we'll
// copy the content we stored in between the IFRAME tags into that
// document. It's a hack to allow us to use only one HTML file for this
// test.
doc.body.innerHTML = iframe.textContent || iframe.innerHTML;
// Marke the IFRAME as an editable document
if (doc.body.contentEditable) {
doc.body.contentEditable = true;
} else {
var mydoc = doc;
doc.designMode = 'On';
}
// A function to demonstrate the bug.
var myhandler = function() {
// Step 1 Get the current selection
var selection = doc.selection || iframe.contentWindow.getSelection();
var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0);
// Step 2 Restore the selection
if (range.select) {
range.select();
} else {
selection.removeAllRanges();
selection.addRange(range);
doc.body.focus();
}
}
// Set up the button to perform the test code.
var button = document.getElementById('mytrigger');
if (button.addEventListener) {
button.addEventListener('click', myhandler, false);
} else {
button.attachEvent('onclick', myhandler);
}
}
</script>
</body>
</html>
The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node.
It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement.
How do I work around this and consistently save and restore the selection in internet explorer?
A: I've figured out a few methods for dealing with IE ranges like this.
If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again:
// Save position of cursor
range.pasteHTML('<span id="caret"></span>')
...
// Create new cursor and put it in the old position
var caretSpan = iframe.contentWindow.document.getElementById("caret");
var selection = iframe.contentWindow.document.selection;
newRange = selection.createRange();
newRange.moveToElementText(caretSpan);
Alternatively, you can count how many characters precede the current cursor position and save that number:
var selection = iframe.contentWindow.document.selection;
var range = selection.createRange().duplicate();
range.moveStart('sentence', -1000000);
var cursorPosition = range.text.length;
To restore the cursor, you set it to the beginning and then move it that number of characters:
var newRange = selection.createRange();
newRange.move('sentence', -1000000);
newRange.move('character', cursorPosition);
Hope this helps.
A: I've had a bit of a dig & unfortunately can't see a workaround... Although one thing I noticed while debugging the javascript, it seems like the problem is actually with the range object itself rather than with the subsequent range.select(). If you look at the values on the range object that selection.createRange() returns, yes the parent dom object may be correct, but the positioning info is already referring to the start of the next line (i.e. offsetLeft/Top, boundingLeft/Top, etc are already wrong).
Based on the info here, here and here, I think you're out of luck with IE, since you only have access to Microsoft's TextRange object, which appears to be broken. From my experimentation, you can move the range around and position it exactly where it should be, but once you do so, the range object automatically shifts down to the next line even before you've tried to .select() it. For example, you can see the problem by putting this code in between your Step 1 & Step 2:
if (range.boundingWidth == 0)
{
//looks like its already at the start of the next line down...
alert('default position: ' + range.offsetLeft + ', ' + range.offsetTop);
//lets move the start of the range one character back
//(i.e. select the last char on the line)
range.moveStart("character", -1);
//now the range looks good (except that its width will be one char);
alert('one char back: ' + range.offsetLeft + ', ' + range.offsetTop);
//calculate the true end of the line...
var left = range.offsetLeft + range.boundingWidth;
var top = range.offsetTop;
//now we can collapse back down to 0 width range
range.collapse();
//the position looks right
alert('moving to: ' + left + ', ' + top);
//move there.
range.moveToPoint(left, top);
//oops... on the next line again... stupid IE.
alert('moved to: ' + range.offsetLeft + ', ' + range.offsetTop);
}
So, unfortunately it doesn't look like there's any way to ensure that the range is in the right spot when you select it again.
Obviously there's the trivial fix to your code above, by changing Step 2 it to this:
// Step 2 Restore the selection
if (range.select) {
if (range.boundingWidth > 0) {
range.select();
}
} else {
selection.removeAllRanges();
selection.addRange(range);
doc.body.focus();
}
But presumably, you actually want to do something between Step 1 & Step 2 in your actual which involves moving the selection, hence the need to re-set it. But just in case. :)
So, the best I can do is go & vote for the bug you created... Hopefully they'll fix it.
A: I recently worked at a site which used Microsoft CMS with the "MSIB+ pack" of controls which included a WYSIWYG editor which ran in Internet Explorer.
I seem to remember some comments in the editor client-side Javascript which were specifically related to this bug in IE and the Range.Select() method.
Unfortunately, I'm not working there anymore so I can't access the Javascript files, but perhaps you may be able to get them from elsewhere?
Good luck
A: Maybe I misunderstand, but if I click to the right of that first line, my cursor already immediately appears at the start of the second line, so that's not a TextRange issue, right?
Adding a doctype so the test page is rendered in standards mode instead of quirks mode fixes that for me.
And I can't reproduce what your myhandler function does, because clicking that button moves the focus away to the button so I can no longer see the cursor and can't get it back either. Finding the cursor position in a contentEditable area seems to be a different problem altogether.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: how can i change this view? I want to index this view but because it has subquery i cant index. Can anyone suggest how to change this view so that i can index it.
ALTER VIEW [dbo].[Recon2]
WITH SCHEMABINDING
AS
SELECT
dbo.Transactions.CustomerCode,
dbo.Customer_Master.CustomerName,
dbo.Transactions.TransDate,
dbo.Transactions.PubCode,
dbo.Transactions.TransType,
dbo.Transactions.Copies,
SUM(dbo.Transactions.TotalAmount) AS TotalAmount,
'0' AS ReceiptNo,
'2008-01-01' AS PaymentDate,
0 AS Amount,
dbo.Transactions.Period,
dbo.Transactions.Year,
dbo.Publication_Master.PubName,
dbo.Customer_Master.SalesCode,
COUNT_BIG(*) AS COUNT
FROM
dbo.Publication_Master INNER JOIN
dbo.Customer_Master INNER JOIN
dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON
dbo.Publication_Master.PubCode = dbo.Transactions.PubCode
WHERE
(dbo.Customer_Master.CustomerCode NOT IN
(SELECT CustomerCode
FROM dbo.StreetSaleRcpt
WHERE (PubCode = dbo.Transactions.PubCode) AND
(TransactionDate = dbo.Transactions.TransDate) AND
(Updated = 1) AND
(PeriodMonth = dbo.Transactions.Period) AND
(PeriodYear = dbo.Transactions.Year)))
GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode,
dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType,
dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount
A: I can't run it (obviously) but what about this?:
SELECT
dbo.Transactions.CustomerCode,
dbo.Customer_Master.CustomerName,
dbo.Transactions.TransDate,
dbo.Transactions.PubCode,
dbo.Transactions.TransType,
dbo.Transactions.Copies,
'0' AS ReceiptNo,
'2008-01-01' AS PaymentDate,
0 AS Amount,
dbo.Transactions.Period,
dbo.Transactions.Year,
dbo.Publication_Master.PubName,
dbo.Customer_Master.SalesCode,
dbo.StreetSaleRcpt.CustomerCode,
SUM(dbo.Transactions.TotalAmount) AS TotalAmount,
COUNT_BIG(*) AS COUNT
FROM dbo.Publication_Master
INNER JOIN dbo.Customer_Master ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode
INNER JOIN dbo.Transactions ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode
LEFT OUTER JOIN dbo.StreetSaleRcpt ON (
dbo.StreetSaleRcpt.PubCode = dbo.Transactions.PubCode
AND dbo.StreetSaleRcpt.TransactionDate = dbo.Transactions.TransDate
AND dbo.StreetSaleRcpt.PeriodMonth = dbo.Transactions.Period
AND dbo.StreetSaleRcpt.PeriodYear = dbo.Transactions.Year
AND dbo.StreetSaleRcpt.Updated = 1
AND dbo.StreetSaleRcpt.CustomerCode = dbo.Customer_Master.CustomerCode
)
WHERE dbo.StreetSaleRcpt.CustomerCode IS NULL
GROUP BY
dbo.Transactions.CustomerCode,
dbo.Customer_Master.CustomerName,
dbo.Transactions.TransDate,
dbo.Transactions.PubCode,
dbo.Publication_Master.PubName,
dbo.Customer_Master.SalesCode,
dbo.Transactions.[Update],
dbo.Transactions.TransType,
dbo.Transactions.Copies,
dbo.Transactions.Period,
dbo.Transactions.Year,
dbo.Transactions.TotalAmount,
dbo.StreetSaleRcpt.CustomerCode
Make your correlated sub-query a left join and test for its absence ('WHERE dbo.StreetSaleRcpt.CustomerCode IS NULL') versus 'NOT IN'.
Good luck.
A: At least in Oracle, you can change from VIEW to MATERIALIZED VIEW. There will be a few other issues like table space and methods of synchronization to consider but it might be worth exploring.
Depending on your application, another option would be to create a normal table based on the select of this view and either update it at an acceptable interval or use a lot of foreign keys.
What's most practical depends on a number of factors -- table size, frequency of updates, need for most current data, etc.
A: This form would allow use of an index on StreetSaleRcpt for each Publication_Master row:
ALTER VIEW [dbo].[Recon2] WITH SCHEMABINDING AS SELECT
dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Transactions.TransType, dbo.Transactions.Copies, SUM(dbo.Transactions.TotalAmount) AS TotalAmount, '0' AS ReceiptNo, '2008-01-01' AS PaymentDate, 0 AS Amount, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, COUNT_BIG(*) AS COUNT
FROM dbo.Publication_Master
INNER JOIN dbo.Customer_Master
INNER JOIN dbo.Transactions ON dbo.Customer_Master.CustomerCode = dbo.Transactions.CustomerCode ON dbo.Publication_Master.PubCode = dbo.Transactions.PubCode
WHERE
(NOT EXISTS
(SELECT NULL FROM dbo.StreetSaleRcpt
WHERE (PubCode = dbo.Transactions.PubCode)
AND (TransactionDate = dbo.Transactions.TransDate)
AND (Updated = 1)
AND (PeriodMonth = dbo.Transactions.Period)
AND (PeriodYear = dbo.Transactions.Year)
ANMD (CustomerCode = dbo.Customer_Master.CustomerCode)
)
) GROUP BY dbo.Transactions.CustomerCode, dbo.Customer_Master.CustomerName, dbo.Transactions.TransDate, dbo.Transactions.PubCode, dbo.Publication_Master.PubName, dbo.Customer_Master.SalesCode, dbo.Transactions.[Update], dbo.Transactions.TransType, dbo.Transactions.Copies, dbo.Transactions.Period, dbo.Transactions.Year, dbo.Transactions.TotalAmount
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Expressing an is-a relationship in a relational database I was wondering if there is a clean way to represent an is-a relationship as illustrated by this example:
This DB stores recording times for three types of programs: movies, game shows, drama. In an object oriented sense each of these is-a program. Each of these subclasses have different properties. Here are the tables (fk prefix indicates a foreign key):
movie
id
name
fkDirector
gameShow
id
name
fkHost
fkContestant
drama
id
name
In OO terms the record table would in sense look like this:
record
id
fkProgram
startTime
endTime
The only way I can think of doing this without violating the normal forms is to have three record tables namely recordMovie, recordGameShow, and recordDrama.
Is there a way to consolidate these tables into one without violating the principles of database normalization?
Here are some non-working examples to illustrate the idea:
program
id
fkMovie
fkGameShow
fkDrama
This table violates the first normal form because it will contain nulls. For each row only one of the 3 entries will be non null.
program
id
fkSpecific ← fkMovie OR fkGameShow OR fkDrama
fkType ← would indicate what table to look into
Here I will not be able to enforce referential integrity because the fkSpecific could potentially point to one of three tables.
I'm just trying to save the overhead of having 3 tables here instead of one. Maybe this simply isn't applicable to an RDB.
A: Yes, that should be one table like
Programs:
id,
name,
type_id,
length,
etc...
with a reference table for the type of program if there are
other bits of data associated with the type:
ProgramType
type_id,
type_name,
etc...
Like that.
A: Why do you want to store all the data on a single table? They are clearly different entities. Your idea of a main Record table, with auxiliary recordMovie, recordGameShow, and RecordDrama.
To enforce the "is-a" relationship between the auxiliary tables and the main one, you need to do declare Record.id to be a foreign key in all these tables, and also add a constraint to it so it's unique - this enforces a one-to-one relationship which would convert these tables in extensions of the main one.
You'd also need to add a new field in the main Record table to indicate what kind of record it is (movie, game show, drama, something else?). This could be either a foreign key reference to yet another table (RecordTypes?) or a string (with a constraint defined over the values it can accept).
A: Do a google search on "generalization specialization relational modeling".
The "gen-spec" model follows the same pattern as the "is-a" relationship.
For example, a car is a specialized vehicle. A truck is a different kind of specialized vehicle. A motorcycle is a third kind of specialized vehicle.
You should find plenty of articles.
Interestingly, if you just do a google search on "gen-spec" one of the top links is to a description of gen-spec modeling in Smalltalk.
A: This is a pretty standard problem faced by many people before, and all of the approaches you may consider have probably been done at one point.
A simple Google search comes up with some pretty good explanations of the pros and cons of each.
A: My first idea was also to use one Program table for movies, shows & drama's. Then add a ProgramType table and use a foreign key to it just like the parent post.
Other columns can be added such as fkDirector, fkMovie. Then add a constraint that when the ProgramType is a movie, fkDirector can not be null or when it's a show, fkHost can not be null.
This allows for easy lookup of all movies/shows/... recorded between start and enddate. Also makes sure all the data is filled in and the references are correct.
Anyone has a better idea?
A: These are both good articles on the subject:
http://www.ibm.com/developerworks/library/ws-mapping-to-rdb/
http://www.agiledata.org/essays/mappingObjects.html
This what I will end up doing. My program table will simply be:
program
id
and then I will add fkProgram to each of the subclasses (drama, gameshow, and movie). This way the Program table will be an intermediate table between the subclasses. I can use a foreign key to the Program table to refer to an instance any of the sub-classes. This will allow me to have a single Record table and not violate any normal forms.
movie
id
fkProgram
name
fkDirector
record
id
fkProgram
startTime
endTime
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to modify a registry entry via a .bat/.cmd script? Is it possible to modify a registry value (whether string or DWORD) via a .bat/.cmd script?
A: You can use the REG command. From http://www.ss64.com/nt/reg.html:
Syntax:
REG QUERY [ROOT\]RegKey /v ValueName [/s]
REG QUERY [ROOT\]RegKey /ve --This returns the (default) value
REG ADD [ROOT\]RegKey /v ValueName [/t DataType] [/S Separator] [/d Data] [/f]
REG ADD [ROOT\]RegKey /ve [/d Data] [/f] -- Set the (default) value
REG DELETE [ROOT\]RegKey /v ValueName [/f]
REG DELETE [ROOT\]RegKey /ve [/f] -- Remove the (default) value
REG DELETE [ROOT\]RegKey /va [/f] -- Delete all values under this key
REG COPY [\\SourceMachine\][ROOT\]RegKey [\\DestMachine\][ROOT\]RegKey
REG EXPORT [ROOT\]RegKey FileName.reg
REG IMPORT FileName.reg
REG SAVE [ROOT\]RegKey FileName.hiv
REG RESTORE \\MachineName\[ROOT]\KeyName FileName.hiv
REG LOAD FileName KeyName
REG UNLOAD KeyName
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/v ValueName] [Output] [/s]
REG COMPARE [ROOT\]RegKey [ROOT\]RegKey [/ve] [Output] [/s]
Key:
ROOT :
HKLM = HKey_Local_machine (default)
HKCU = HKey_current_user
HKU = HKey_users
HKCR = HKey_classes_root
ValueName : The value, under the selected RegKey, to edit.
(default is all keys and values)
/d Data : The actual data to store as a "String", integer etc
/f : Force an update without prompting "Value exists, overwrite Y/N"
\\Machine : Name of remote machine - omitting defaults to current machine.
Only HKLM and HKU are available on remote machines.
FileName : The filename to save or restore a registry hive.
KeyName : A key name to load a hive file into. (Creating a new key)
/S : Query all subkeys and values.
/S Separator : Character to use as the separator in REG_MULTI_SZ values
the default is "\0"
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ
Output : /od (only differences) /os (only matches) /oa (all) /on (no output)
A: You can make a .reg file and call start on it. You can export any part of the registry as a .reg file to see what the format is.
Format here:
http://support.microsoft.com/kb/310516
This can be run on any Windows machine without installing other software.
A: Yes, you can script using the reg command.
Example:
reg add HKCU\Software\SomeProduct
reg add HKCU\Software\SomeProduct /v Version /t REG_SZ /d v2.4.6
This would create key HKEY_CURRENT_USER\Software\SomeProduct, and add a String value "v2.4.6" named "Version" to that key.
reg /? has the details.
A: This is how you can modify registry, without yes or no prompt and don't forget to run as administrator
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\etc\etc /v Valuename /t REG_SZ /d valuedata /f
Below is a real example to set internet explorer as my default browser
reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice /v ProgId /t REG_SZ /d IE.HTTPS /f
/f Force: Force an update without prompting "Value exists, overwrite
Y/N"
/d Data : The actual data to store as a "String", integer etc
/v Value : The value name eg ProgId
/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ |
REG_MULTI_SZ
Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from here
A: @Franci Penov - modify is possible in the sense of overwrite with /f, eg
reg add "HKCU\Software\etc\etc" /f /v "value" /t REG_SZ /d "Yes"
A: Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.
A: In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.
A: See http://www.chaminade.org/MIS/Articles/RegistryEdit.htm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
}
|
Q: What's the best way to instantiate a generic from its name? Assuming I have only the class name of a generic as a string in the form of "MyCustomGenericCollection(of MyCustomObjectClass)" and don't know the assembly it comes from, what is the easiest way to create an instance of that object?
If it helps, I know that the class implements IMyCustomInterface and is from an assembly loaded into the current AppDomain.
Markus Olsson gave an excellent example here, but I don't see how to apply it to generics.
A: Once you parse it up, use Type.GetType(string) to get a reference to the types involved, then use Type.MakeGenericType(Type[]) to construct the specific generic type you need. Then, use Type.GetConstructor(Type[]) to get a reference to a constructor for the specific generic type, and finally call ConstructorInfo.Invoke to get an instance of the object.
Type t1 = Type.GetType("MyCustomGenericCollection");
Type t2 = Type.GetType("MyCustomObjectClass");
Type t3 = t1.MakeGenericType(new Type[] { t2 });
ConstructorInfo ci = t3.GetConstructor(Type.EmptyTypes);
object obj = ci.Invoke(null);
A: The MSDN article How to: Examine and Instantiate Generic Types with Reflection describes how you can use Reflection to create an instance of a generic Type. Using that in conjunction with Marksus's sample should hopefully get you started.
A: If you don't mind translating to VB.NET, something like this should work
foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
{
// find the type of the item
Type itemType = assembly.GetType("MyCustomObjectClass", false);
// if we didnt find it, go to the next assembly
if (itemType == null)
{
continue;
}
// Now create a generic type for the collection
Type colType = assembly.GetType("MyCusomgGenericCollection").MakeGenericType(itemType);;
IMyCustomInterface result = (IMyCustomInterface)Activator.CreateInstance(colType);
break;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: What is a good algorithm for compacting records in a blocked file? Suppose you have a large file made up of a bunch of fixed size blocks. Each of these blocks contains some number of variable sized records. Each record must fit completely within a single block and then such records by definition are never larger than a full block. Over time, records are added to and deleted from these blocks as records come and go from this "database".
At some point, especially after perhaps many records are added to the database and several are removed - many of the blocks may end up only partially filled.
What is a good algorithm to shuffle the records around in this database to compact out unnecessary blocks at the end of the file by better filling up the partially filled blocks?
Requirements of the algorithm:
*
*The compaction must happen in place of the original file without temporarily extending the file by more than a few blocks at most from its starting size
*The algorithm should not unnecessarily disturb blocks that are already mainly full
*Entire blocks must be read or written from/to the file at one time and one should assume the write operation is relatively expensive
*If records are moved from one block to another they must be added at their new location before being removed from their starting position so that in case the operation is interrupted no records are lost as a result of the "failed" compaction. (Assume that this temporary duplication of such records can be detected at recovery).
*The memory that can be used for this operation can only be on the order of perhaps several blocks which is a very small percentage of the overall file size
*Assume that records are on the order of 10 bytes to 1K bytes with an average size of maybe 100 bytes. The fixed sized blocks are on the order of 4K or 8K and that the file is on the order of 1000's of blocks.
A: If there is no ordering to these records, I'd simply fill the blocks from the front with records extracted from the last block(s). This will minimize movement of data, is fairly simple, and should do a decent job of packing data tightly.
E.g.:
// records should be sorted by size in memory (probably in a balanced BST)
records = read last N blocks on disk;
foreach (block in blocks) // read from disk into memory
{
if (block.hasBeenReadFrom())
{
// we read from this into records already
// all remaining records are already in memory
writeAllToNewBlocks(records);
// this will leave some empty blocks on the disk that can either
// be eliminated programmatically or left alone and filled during
// normal operation
foreach (record in records)
{
record.eraseFromOriginalLocation();
}
break;
}
while(!block.full())
{
moveRecords = new Array; // list of records we've moved
size = block.availableSpace();
record = records.extractBestFit(size);
if (record == null)
{
break;
}
moveRecords.add(record);
block.add(record);
if (records.gettingLow())
{
records.readMoreFromDisk();
}
}
if(moveRecords.size() > 0)
{
block.writeBackToDisk();
foreach (record in moveRecords)
{
record.eraseFromOriginalLocation();
}
}
}
Update: I neglected to maintain the no-blocks-only-in-memory rule. I've updated the pseudocode to fix this. Also fixed a glitch in my loop condition.
A: This sounds like a variation of the bin packing problem, but where you already have an inferior allocation that you want to improve. So I suggest looking at variations of the approaches which are successful for the bin packing problem.
First of all, you probably want to parameterize your problem by defining what you consider "full enough" (where a block is full enough that you don't want to touch it), and what is "too empty" (where a block has so much empty space that it has to have more records added to it). Then, you can classify all the blocks as full enough, too empty, or partially full (those that are neither full enough nor too empty). You then redefine the problem as how to eliminate all the too empty blocks by creating as many full enough blocks as possible while minimising the number of partially full blocks.
You'll also want to work out what's more important: getting the records into the fewest blocks possible, or packing them adequately but with the least amount of blocks read and written.
My approach would be to make an initial pass over all the blocks, to classify them all into one of the three classes defined above. For each block, you also want to keep track of the free space available in it, and for the too empty blocks, you'll want to have a list of all the records and their sizes. Then, starting with the largest records in the too empty blocks, move them into the partially full blocks. If you want to minimise reads and writes, move them into any of the blocks you currently have in memory. If you want to minimise wasted space, find the block with the least amount of empty space that will still hold the record, reading the block in if necessary. If no block will hold the record, create a new block. If a block in memory reaches the "full enough" threshold, write it out. Repeat until all the records in the partially filled blocks have been placed.
I've skipped over more than a few details, but this should give you some idea. Note that the bin packing problem is NP-hard, which means that for practical applications, you'll want to decide what's most important to you, so you can pick an approach that will give you an approximately best solution in reasonable time.
A: A modification of an on-line (to defragment in one pass) bounded space (the memory requirements) bin packing algorithm could probably work here.
See "Bin Packing Approximation Algorithms: Combinatorial Analysis" by Coffman et al.
A: Here's an algorithm you might be able to leverage, albeit your records within fixed size blocks might require a little bit more work.
Heap Defragmentation in Bounded Time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to do a SVN export without shell access? I started using subversion for one of my projects and it would be absolutely amazing if I could just export the latest version from the repository on my production server by for example running a php or perl script.
The production site is hosted with a shared hosting provider who doesn't allow shell access or for example the php exec() function. (I don't know much about perl; I only know that my hoster allows perl and custom cgi scripts).
Is it possible to perform a SVN export in this environment?
A: As far as I know there is no SVN client fully written in PHP or Perl. SO without exec you're out of luck.
Workarounds:
*
*Depending on your own OS and what methods you have to access your web space you might be able to mount the web space in your local file system and just use your system's SVN client for checking out/updating.
*Again depending on your access methods (I'm guessing ftp or sftp) you might update a local checkout and sync any changes up onto the web space.
A: SVN supports access over WebDAV (i.e. HTTPS). This means for simple read access you don't actually need an SVN client to access an SVN repository. You can even use a web browser, or in your case any PHP function that accepts a URL as its argument. SVN has to be set up on the server side to work with apache, for more info check out the svn red book
A: Have a look on this:
http://www.randomsequence.com/articles/svn-backup-script/
Of course, you still need exec for that, but as said it won't be difficult to code something in PHP that runs an http call to your svn server.
Or else, something like:
palaniraja.wordpress.com/2008/09/20/svn-export-only-updated-files-between-2-revisions/
Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to package a Linux binary for my Open Source application? I have an Open Source app and I currently only post the binary for the Windows build. At this point Linux users have to get the source and compile it. Is there a standard way for posting a Linux binary?
My app is in c / c++ and compiled with gcc, the only external Linux code I use is X Windows and CUPS.
A: The most common way would be to package it in a .rpm file for RedHat-based distros like Fedora, or a .deb file for Debian-based distros like Ubuntu.
A: Find someone skilled with Debian and get their help to set up a build process to build .deb packages for Debian and Ubuntu.
A: Of course: take a look at this tutorial from IBM. Its only for RPMs, but it at least would get you going. DEB files are similar - see this tutorial.
Basically, once you've built your binaries, you write a control file describing what files the package ships, and where it puts them. Then you build everything into a package using the packaging tools. Its a lot like Windows where you write an installer file, then run it through Wix or Intellishield or whatever to create a .msi file.
A: Don't hesitate to file a Request For Package (RFP) bug on Debian's bug tracking system. A debian developer may be interested by your software and package it.
http://www.debian.org/Bugs/Reporting
A: You could provide the packages yourself, but that's not the ideal way to distribute your application. Users won't be able to find your software in their distribution's package repository and will have to hit your website to download the latest version.
IMO the best thing to do is solicit the help of package maintainers for the distributions of your choice. Get one of them who is interested in your application to adopt it and bring it in to the distro, then they can take care of the distro-specific details of packaging it.
Your role will be to assist them as much as possible in getting your software to build on their platform and work out any bugs related to interactions with other package versions, etc.
A: I only use precompiled binaries from my distribution - never from other hand. If you can afford it just roll a tarball and add some buildscript so that people can build your project. To publish it add it to sites like: Freshmeat
A: Edit: Below are some of the great guides for producing a portable Linux binary-
*
*How to create portable Linux binaries, containing
*
*portability and backward compatibility requirements
*introduction into dynamic libraries
*symbol versioning on Linux
*Portable Linux Binaries, containing
*
*Common Issues
*Ways to avoid those
*Linux Game Development - Part 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can I use a generated variable name in PHP? I have a bunch a values I would like to add together which are entered into a form. Right now, the form has 11 lines but it could get larger in the future. I can easily add all the values together with something like:
$total = $value1 + $value2 + ... + $value11;
All the values I want to add together are coming from an HTML form. I want to avoid javascript.
But, I want to avoid having to manually do it, especially if it grows much larger. This is my attempt at adding all the values together using a loop but it returns an "undefined variable" error (it is just some test code to try out the idea):
<?php
$tempTotal = 0;
$pBalance1 = 5;
$pBalance2 = 5;
$pBalance3 = 5;
for ($i = 1 ; $i <= 3 ; $i++){
$tempTotal = $tempTotal + $pBalance.$i;
}
echo $tempTotal;
?>
Is what I want to do possible in PHP?
A: for ($i = 1 ; $i <= 3 ; $i++){
$varName = "pBalance".$i;
$tempTotal += $$varName;
}
This will do what you want. However you might indeed consider using an array for this kind of thing.
A: I would use @unexist's solution.. give the input fields names like:
<input name="myInput[]" />
<input name="myInput[]" />
<input name="myInput[]" />
...
Then in your PHP get the sum like this:
$total = array_sum($_REQUEST['myInput']);
Because of the '[]' at the end of each input name, PHP will make $_REQUEST['myInput'] automatically be an array. A handy feature of PHP!
A: Uhm why don't you use an array? If you give the forms a name like foobar[] it will be an array in PHP.
A: The values you need are posted from a form, right? If so, you could iterate through the keys in the $_POST variable that match your form field's generated names.
foreach($_POST as $key=>$value)
{
if(strpos($key, 'pBalance')===0)
{
$final_total += $value;
}
}
A: You can use an array to store your data, and just loop over it.
$tempTotal = 0;
$balances[] = 5;
$balances[] = 5;
$balances[] = 5;
for ($i = 0; $i <= count($balances); $i++) {
$tempTotal = $tempTotal + $balances[$i];
}
Or for brevity, use a foreach loop:
foreach($balances as $balance) {
$tempTotal += $balance;
}
A: If you're trying to collect the values of a POST, you should really use an array. You can avoid having to manually piece together such an array by using:
<input type="text" name="vals[]" value="one" />
<input type="text" name="vals[]" value="two" />
$_POST["vals"] will then be array("one", "two");
A: In about 99% of all cases involving a PHP generated variable, you are doing The Wrong Thing. I'll just re-iterate what others have said:
USE AN ARRAY
A: Try
$varName = 'pBalance' . $i;
$tempTotal = $tempTotal + $$varName;
A: The concept you're looking for is called a variable variable (at least it's called that in PHP). Here is the official documentation and a useful tutorial. The syntax for a variable variable is a double dollar sign ($$).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130240",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I efficiently filter computed values within a Python list comprehension? The Python list comprehension syntax makes it easy to filter values within a comprehension. For example:
result = [x**2 for x in mylist if type(x) is int]
Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One option is:
result = [expensive(x) for x in mylist if expensive(x)]
This will result in a list of non-"false" expensive(x) values, however expensive() is called twice for each x. Is there a comprehension syntax that allows you to do this test while only calling expensive once per x?
A: The most obvious (and I would argue most readable) answer is to not use a list comprehension or generator expression, but rather a real generator:
def gen_expensive(mylist):
for item in mylist:
result = expensive(item)
if result:
yield result
It takes more horizontal space, but it's much easier to see what it does at a glance, and you end up not repeating yourself.
A: result = [x for x in map(expensive,mylist) if x]
map() will return a list of the values of each object in mylist passed to expensive(). Then you can list-comprehend that, and discard unnecessary values.
This is somewhat like a nested comprehension, but should be faster (since the python interpreter can optimize it fairly easily).
A: This is exactly what generators are suited to handle:
result = (expensive(x) for x in mylist)
result = (do_something(x) for x in result if some_condition(x))
...
result = [x for x in result if x] # finally, a list
*
*This makes it totally clear what is happening during each stage of the pipeline.
*Explicit over implicit
*Uses generators everywhere until the final step, so no large intermediate lists
cf: 'Generator Tricks for System Programmers' by David Beazley
A: Came up with my own answer after a minute of thought. It can be done with nested comprehensions:
result = [y for y in (expensive(x) for x in mylist) if y]
I guess that works, though I find nested comprehensions are only marginally readable
A: If the calculations are already nicely bundled into functions, how about using filter and map?
result = filter (None, map (expensive, mylist))
You can use itertools.imap if the list is very large.
A: You could always memoize the expensive() function so that calling it the second time around is merely a lookup for the computed value of x.
Here's just one of many implementations of memoize as a decorator.
A: You could memoize expensive(x) (and if you are calling expensive(x) frequently, you probably should memoize it any way. This page gives an implementation of memoize for python:
http://code.activestate.com/recipes/52201/
This has the added benefit that expensive(x) may be run less than N times, since any duplicate entries will make use of the memo from the previous execution.
Note that this assumes expensive(x) is a true function, and does not depend on external state that may change. If expensive(x) does depend on external state, and you can detect when that state changes, or you know it wont change during your list comprehension, then you can reset the memos before the comprehension.
A: I will have a preference for:
itertools.ifilter(bool, (expensive(x) for x in mylist))
This has the advantage to:
*
*avoid None as the function (will be eliminated in Python 3): http://bugs.python.org/issue2186
*use only iterators.
A: In 3.8 and above, the "walrus" operator accomplishes this:
[e for x in mylist if (e:=expensive(x))]
A: There is the plain old use of a for loop to append to a list, too:
result = []
for x in mylist:
expense = expensive(x)
if expense:
result.append(expense)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Impact of AWS Account Identifiers I'm using Amazon's tools to build a web app. I'm very happy with them, but I have a security concern.
Right now, I'm using multiple EC2 instances, S3, SimpleDB and SQS. In order to authenticate requests to the different services, you include your Access Identifiers (login required).
For example, to upload a file to S3 from an EC2 instance, your EC2 instance needs to have your Access Key ID and your Secret Access Key.
That basically means your username and password need to be in your instances.
If one of my instances were to be compromised, all of my Amazon assets would be compromised. The keys can be used upload/replace S3 and SimpleDB data, start and stop EC2 instances, etc.
How can I minimize the damage of a single compromised host?
My first thought is to get multiple identifiers per account so I can track changes made and quickly revoke the 'hacked' account. Amazon doesn't support more than one set of credentials per account.
My second thought was to create multiple accounts and use ACL's to control access. Unfortunately, not all the services support granting other accounts access to your data. Plus bandwidth is cheaper the more that you use, so having it all go through one account is ideal.
Has anyone dealt with, or at least thought about this problem?
A: What you can do is have a single, super-locked down 'authentication server'. The secret key only exists on this one server, and all the other servers will need to ask it for permission. You can assign your own keys to the various servers, and lock it down by IP address as well. That way if a server gets compromised, you simply revoke its key from the 'authentication server'.
This is possible, because of the way the AWS authentication works. Say your webserver needs to upload a file to S3. First, it will generate the AWS request, and send that request along with your custom server key to the 'authentication server'. The authentication server will authenticate the request, doing the crypto magic stuff, and return the authenticated string back to the webserver. The webserver can then use this to actually submit the request along with the file to upload to S3.
A: AWS allows you to create multiple users with Identity and Access Management. This will allow you to implement either of your scenarios.
I would suggest defining an IAM user per EC2 instance, this allows you to revoke access to a specific user (or just their access keys) if the corresponding EC2 instance is compromised and also use fine-grained permissions to restrict what APIs the user can call and what resources they can access (e.g. only permit the user to upload to a specific bucket).
A: Furthermore, AWS IAM roles allow you to assign permissions to an EC2 instance rather than having to place keys on the instance.
See the blog post at http://aws.typepad.com/aws/2012/06/iam-roles-for-ec2-instances-simplified-secure-access-to-aws-service-apis-from-ec2.html
Most of the SDKs utilize the temporary keys created by the roles.
A: AWS offers "Consolidated Billing" which addresses your concern in the second thought.
https://aws-portal.amazon.com/gp/aws/developer/account/index.html?ie=UTF8&action=consolidated-billing
"Consolidated Billing enables you to consolidate payment for multiple Amazon Web Services (AWS) accounts within your company by designating a single paying account. You can see a combined view of AWS costs incurred by all accounts, as well as obtain a detailed cost report for each of the individual AWS accounts associated with your paying account. Consolidated Billing may also lower your overall costs since the rolled up usage across all of your accounts could help you reach lower-priced volume tiers more quickly."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How to eager load objects with a custom join in rails? Background
Normal rails eager-loading of collections works like this:
Person.find(:all, :include=>:companies)
This generates some sql which does
LEFT OUTER JOIN companies ON people.company_id = companies.id
Question
However, I need a custom join (this could also arise if I was using find_by_sql) so I can't use the vanilla :include => :companies
The custom join/sql will get me all the data I need, but how can I tell activerecord that it belongs to the associated Company objects rather than just being a pile of extra rows?
Update
I need to put additional conditions in the join. Something like this:
SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL
<Several other joins>
WHERE blahblahblah
A: Can you not add the join conditions using ActiveRecord?
For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives
Contractors.find(
:all,
:include => {:council_areas => :suburbs},
:conditions => ["suburbs.postcode = ?", customer.postcode]
)
Assuming that:
*
*Contractors have_many CouncilAreas
*CouncilAreas have_many Suburbs
This join returns the Contractors in the suburb identified by customer.postcode.
The generated query looks like:
SELECT contractors.*, council_areas.*, suburbs.*
FROM `contractors`
LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id
LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id
LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id
LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')
(Note: I edited the column list for brevity).
A: You can use something like the following to get the appropriate left outer join syntactical magic.
Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'
A: I'm not sure it's what you want (I'm not 100% sure I've understood your question and what you want to accomplish) but:
What about providing both :joins and :includes?
Person.find(
:all,
:joins => 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_',
:includes => :companies
)
Or AR3 way:
Person.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')
A: Can you elaborate a bit more on exactly what you are trying to accomplish with this query?
Also take a look at at the :joins option for find. It allows you to specify how you want the tables joined. link text
And beware when using :include, the behavior changes a bit in Rails 2.1 and may cause some problems when used in conjunction with a :conditions option that references an included table. link text and link text are two articles from Pivotal that mention this gotcha.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: .cmd and .bat file converting return code to an error message I'm trying to automate a program I made with a test suite via a .cmd file.
I can get the program that I ran's return code via %errorlevel%.
My program has certain return codes for each type of error.
For example:
1 - means failed for such and such a reason
2 - means failed for some other reason
...
echo FAILED: Test case failed, error level: %errorlevel% >> TestSuite1Log.txt
Instead I'd like to somehow say:
echo FAILED: Test case failed, error reason: lookupError(%errorlevel%) >> TestSuite1Log.txt
Is this possible with a .bat file? Or do I have to move to a scripting language like python/perl?
A: You can do something like the following code. Note that the error level comparisons should be in decreasing order due to a cmd quirk.
setlocal
rem Main script
call :LookupErrorReason %errorlevel%
echo FAILED Test case failed, error reason: %errorreason% >> TestSuite1Log.txt
goto :EndOfScript
rem Lookup subroutine
:LookupErrorReason
if %%1 == 3 set errorreason=Some reason
if %%1 == 2 set errorreason=Another reason
if %%1 == 1 set errorreason=Third reason
goto :EndOfScript
:EndOfScript
endlocal
A: You can do this quite neatly with the ENABLEDELAYEDEXPANSION option. This allows you to use ! as variable marker that is evaluated after %.
REM Turn on Delayed Expansion
SETLOCAL ENABLEDELAYEDEXPANSION
REM Define messages as variables with the ERRORLEVEL on the end of the name
SET MESSAGE0=Everything is fine
SET MESSAGE1=Failed for such and such a reason
SET MESSAGE2=Failed for some other reason
REM Set ERRORLEVEL - or run command here
SET ERRORLEVEL=2
REM Print the message corresponding to the ERRORLEVEL
ECHO !MESSAGE%ERRORLEVEL%!
Type HELP SETLOCAL and HELP SET at a command prompt for more information on delayed expansion.
A: Not exactly like that, with a subroutine, but you can either populate the a variable with the text using a goto workaround.
It may be easier if this test suite of yours grows quite a bit to use a more powerful language. Perl or even Windows Scripting Host can help you there.
A: Yes you can use call. Just on a new line have call, and pas the errorcode. This should work, but i have not tested.
C:\Users\matt.MATTLANT>help call
Calls one batch program from another.
CALL [drive:][path]filename [batch-parameters]
batch-parameters Specifies any command-line information required by the
batch program.
SEDIT: orry i may have misunderstood a bit, but you can use IF also
A: Test your values in reverse order and use the overloaded behaviour of IF:
@echo off
myApp.exe
if errorlevel 2 goto Do2
if errorlevel 1 goto do1
echo Success
goto End
:Do2
echo Something when 2 returned
goto End
:Do1
echo Something when 1 returned
goto End
:End
If you want to be more powerful, you could try something like this (you'd need to replace the %1 with %errorlevel but it's harder to test for me). You would need to put a label for each error level you deal with:
@echo off
echo passed %1
goto Label%1
:Label
echo not matched!
goto end
:Label1
echo One
goto end
:Label2
echo Two
goto end
:end
Here is a test:
C:\>test
passed
not matched!
C:\>test 9
passed 9
The system cannot find the batch label specified - Label9
C:\>test 1
passed 1
One
C:\>test 2
passed 2
Two
A: You can use the 'IF ERRORLEVEL' statement to do different things based on the return code.
See:
http://www.robvanderwoude.com/errorlevel.html
In response to your second question, I would move to using a scripting language anyway, since Windows batch files are inherently so limited. There are great Windows distributions for Perl, Python, Ruby, etc., so no reason not to use them, really. I personally love doing Perl scripting on Windows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: streaming wav files I have a server that sends data via a socket, the data is a wav 'file'. I can easily write the data to disk and then play it in WMP, but I have no idea how I can play it as I read it from the socket. Is it possible?
Bonus question: how would I do it if the stream was in mp3 or other format?
This is for windows in native C++.
A: Because you've said WMP, I'm assuming the question applies to trying to play a wav file on a windows machine. If not, this answer isn't relevant.
What you want to do isn't trivial. There is a good article here on code project that describes the windows audio model. It describes how to set up the audio device and how to stream data into the device for playback. You "simply" need to supply data coming in from your socket as data for the playback buffers. But that's where all of the tricky work is. You have to be sure that
*
*You have enough data to begin a playback
*Handle the case when your socket is starved for data and you have nothing to send to the playback buffer
*You are able to read data off of the socket with enough speed to keep the playback buffers full
It's an interesting exercise. But tricky.
A: Mark is right about this being a tricky problem. It may be less tricky if you use DirectSound instead of waveOut. Here's an article on streaming wave files from disk: streaming from the network is essentially the same process. Make sure you collect enough data from the network before you start - you'll want more than the 2 buffers the article mentions.
Even less tricky would be FMOD. From the FAQ:
Enhanced Internet features
*
*Internet audio streaming. Custom internet streaming code is included, which allows for seamless SHOUTcast, Icecast and http streaming support.
*Download capability. A side effect of FMOD’s modular file system which supports network files, even static samples can be loaded off the internet.
File format support: FMOD currently supports a wide range of audio file formats.
partial list:
*
*MP3 - (MPEG I/II Layer 3, including VBR support)
*OGG - (Ogg Vorbis format)
*WAV - (Microsoft Wave files, inlcluding compressed wavs. PCM, MP3 and IMA ADPCM compressed wav
A: Mark is right about this being a tricky problem. The waveOutXXXX API is ancient (it predates Windows 95) and requires more error-prone coding than you would think. You will have an easier time interacting with the API in C++ than with C#. Just make sure this is something you really want to do.
If your stream is some format other than WAV file data (like MP3 or WMA), you will have to perform the additional step of decoding the data into WAV format and playing it with the waveOutXXXX API. Finding a good component to do MP3 decoding is trickier than you would expect - I think this is related to the Fraunhofer licensing situation (you're supposed to pay them if you use MP3 code in any way).
I'd find an off-the-shelf product to do this, unless you want the learning experience.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the proper way to inject a data access dependency for lazy loading? What is the proper way to inject a data access dependency when I do lazy loading?
For example I have the following class structure
class CustomerDao : ICustomerDao
public Customer GetById(int id) {...}
class Transaction {
int customer_id; //Transaction always knows this value
Customer _customer = null;
ICustomerDao _customer_dao;
Customer GetCustomer() {
if(_customer == null)
_customer = _customer_dao.GetById(_customer_id);
return _customer
}
How do I get the reference to _customer_dao into the transaction object? Requiring it for the constructor seems like it wouldn't really make sense if I want the Transaction to at least look like a POCO. Is it ok to have the Transaction object reference the Inversion of Control Container directly? That also seems awkward too.
How do frameworks like NHibernate handle this?
A: I suggest something different...
Use a lazy load class :
public class Lazy<T>
{
T value;
Func<T> loader;
public Lazy(T value) { this.value = value; }
public Lazy(Func<T> loader { this.loader = loader; }
T Value
{
get
{
if (loader != null)
{
value = loader();
loader = null;
}
return value;
}
public static implicit operator T(Lazy<T> lazy)
{
return lazy.Value;
}
public static implicit operator Lazy<T>(T value)
{
return new Lazy<T>(value);
}
}
Once you get it, you don't need to inject the dao in you object anymore :
public class Transaction
{
private static readonly Lazy<Customer> customer;
public Transaction(Lazy<Customer> customer)
{
this.customer = customer;
}
public Customer Customer
{
get { return customer; } // implicit cast happen here
}
}
When creating a Transcation object that is not bound to database :
new Transaction(new Customer(..)) // implicite cast
//from Customer to Lazy<Customer>..
When regenerating a Transaction from the database in the repository:
public Transaction GetTransaction(Guid id)
{
custmerId = ... // find the customer id
return new Transaction(() => dao.GetCustomer(customerId));
}
Two interesting things happen :
- Your domain objects can be used with or without data access, it becomes data acces ignorant. The only little twist is to enable to pass a function that give the object instead of the object itself.
- The Lazy class is internaly mutable but can be used as an immutable value. The readonly keyword keeps its semantic, since its content cannot be changed externaly.
When you want the field to be writable, simply remove the readonly keyword. when assigning a new value, a new Lazy will be created with the new value due to the implicit cast.
Edit:
I blogged about it here :
http://www.thinkbeforecoding.com/post/2009/02/07/Lazy-load-and-persistence-ignorance
A: I typically do the dependency injection in the constructor like you have above, but take the lazy loading a step further by acting only when the "get" is called like I have below. Not sure if this is the pure approach you are looking for, but it does eliminate the "dirty" constructor DI/Lazy Loading in 1 step ;)
public class Product
{
private int mProductID;
private Supplier mSupplier;
private ISupplierService mSupplierService;
public Product()
{
//if you want your object to remain POCO you can use dual constr
//this constr will be for app use, the next will be for testing
}
public Product(ISupplierService SupplierService)
{
mSupplierService = SupplierService;
}
public Supplier Supplier {
get {
if (mSupplier == null) {
if (mSupplierService == null) {
mSupplierService = new SupplierService();
}
mSupplier = mSupplierService.GetSupplierByProductID(mProductID);
}
return mSupplier;
}
set { mSupplier = value; }
}
}
A: I'm not terribly familiar with the term POCO, but the definitions I've read seem to generally follow the spirit of the object being independent of some larger framework.
That said, no matter how you slice it, if you're performing dependency injection, you're going to have collaborations with those classes whose functionality is injected in, and something that sticks the depended upon objects in, whether its a full blown injection framework or just some assembler class.
To myself it seems strange to inject a reference to an IOC container into a class. I prefer my injections to occur in the constructor with code looking something like this:
public interface IDao<T>
{
public T GetById(int id);
}
public interface ICustomerDao : IDao<Customer>
{
}
public class CustomerDao : ICustomerDao
{
public Customer GetById(int id)
{...}
}
public class Transaction<T> where T : class
{
int _id; //Transaction always knows this value
T _dataObject;
IDao<T> _dao;
public Transaction(IDao<T> myDao, int id)
{
_id = id;
_dao = myDao;
}
public T Get()
{
if (_dataObject == null)
_dataObject = _dao.GetById(_id);
return _dataObject;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Getting stated with NHibernate. Real world project example? One of my goals over the next few months is to get familiar with NHibernate and am curious if anyone out there has any suggestions of where to begin. Preferably, I'd like to find a example project that demonstrates what you would see in an in-the-field application.
A: The author of the NHibernate ASP.NET Best Practices article and went on to produce a newer sample called Sharp Architecture using ASP.NET MVC.
A: I pretty much based the first iteration of an application architecture solely on this article from CodeProject: NHibernate Best Practices. Also check out this blog: Ayende @ Rahien
A: The nhibernate FAQ blog is pretty useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Cross-model relationships in NSManagedObjectModel from merged models? Is it possible to model relationships between entities that are defined in separate NSManagedObjectModels if the entities are always used within an NSManagedObjectModel that is created by merging the relevant models?
For example, say model 1 defines an entity Foo with relationship (one-to-one) toBar and that model 2 defines an entity Bar with a relationship (one-to-one) toFoo. I will build a CoreData stack using -[NSManagedObjectModel mergedModelFromModels], merging model 1 and model 2. Is there any way to define these relationships either in the data modeler or programatically so that they behave as if they were in-model relationships?
A: Neither model 1 nor model 2 will be loadable at run time unless they're well-formed — that is, unless the toBar and toFoo relationships have destinations. Furthermore, if model 1 and model 2 have identically-named models, you won't be able to create a merged model from them; they will not be coalesced, they will collide, which is an error.
However, you can use the NSManagedObjectModel API manually to load each model and create a new model by hand that contains entities from both. The NSEntityDescription and NSPropertyDescription classes (and its subclasses) do implement the NSCopying protocol so in most cases you should just be able to copy properties over from each component model to your overall model.
Furthermore, the NS*Description classes all support a userInfo dictionary that you can edit in Xcode's data modeling tool, which you can use to do things like tag the destination of a relationship as a stand-in. For example, in model 1 you could have a Bar entity with a userInfo key MyRealEntity and check for that when creating your merged model, as a signal to use the real entity instead.
You'll also want to put stand-in inverse relationships to your stand-in entities; these will be replaced with real inverses after merging. You don't have to totally replicate your stand-in entities in all models, though; you only need the inverse relationships used in your real model in a stand in entity.
Thus if your real Foo has a name attribute, and your real Bar has a kind attribute, your stand-in Foo and Bar won't need those, just stand-in toBar and toFoo relationships.
Here's some code demonstrating what I'm talking about:
- (NSManagedObjectModel *)mergeModelsReplacingDuplicates:(NSArray *)models {
NSManagedObjectModel *mergedModel = [[[NSManagedObjectModel alloc] init] autorelease];
// General strategy: For each model, copy its non-placeholder entities
// and add them to the merged model. Placeholder entities are identified
// by a MyRealEntity key in their userInfo (which names their real entity,
// though their mere existence is sufficient for the merging).
NSMutableArray *mergedModelEntities = [NSMutableArray arrayWithCapacity:0];
for (NSManagedObjectModel *model in models) {
for (NSEntityDescription *entity in [model entities]) {
if ([[entity userInfo] objectForKey:@"MyRealEntity"] == nil) {
NSEntityDescription *newEntity = [entity copy];
[mergedModelEntities addObject:newEntity];
[newEntity release];
} else {
// Ignore placeholder.
}
}
}
[mergedModel setEntities:mergedModelEntities];
return mergedModel;
}
This works because copying of NS*Description objects in Core Data is by-name rather than by-value with respect to a relationship's destination entity and inverse (and to an entity's subentities as well). Thus while a model is mutable — that is, before it's set as the model for an NSPersistentStoreCoordinator — you can use tricks like this to break your model into multiple models.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Haskell newbie: use layout or not? What are the pro's and con's (use examples) I cant seem to find much info on haskells layout features, as I understand it is something like pythons formatting requirements except that is optional. How can I choose not to use this option correctly? Would it be a good idea to start without it so that I get a solid feel for the language itself?
A: See http://en.wikibooks.org/wiki/Programming:Haskell_indentation
and http://www.haskell.org/onlinereport/lexemes.html#sect2.7
(both contain examples).
Pros:
*
*less typing
*less to read, nicer-looking (if you're comfortable with it)
Cons:
*
*you might get it wrong, especially if you're not familiar with it. Braces make things crystal clear if you're not sure.
A: Haskell's layout is one of its defining features, imho. Part of the entire philosophy of Haskell is that it is more math-like. And using layout is a huge step towards that. For many programs, if you were to write pseudo-code out of math equations, it would end up being valid Haskell syntax using layout. I highly recommend at least trying layout.
The downside is that subtle indentation errors can arise. This can be frustrating at first, esp. if you're not familiar with it. But the compiler tells you about them. Once you fix it, you're left with code that is often very pleasant to look at.
You can not use it simply by using curly braces for explicit blocks and semicolons for separators.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you pass a member function pointer? I am trying to pass a member function within a class to a function that takes a member function class pointer. The problem I am having is that I am not sure how to properly do this within the class using the this pointer. Does anyone have suggestions?
Here is a copy of the class that is passing the member function:
class testMenu : public MenuScreen{
public:
bool draw;
MenuButton<testMenu> x;
testMenu():MenuScreen("testMenu"){
x.SetButton(100,100,TEXT("buttonNormal.png"),TEXT("buttonHover.png"),TEXT("buttonPressed.png"),100,40,&this->test2);
draw = false;
}
void test2(){
draw = true;
}
};
The function x.SetButton(...) is contained in another class, where "object" is a template.
void SetButton(int xPos, int yPos, LPCWSTR normalFilePath, LPCWSTR hoverFilePath, LPCWSTR pressedFilePath, int Width, int Height, void (object::*ButtonFunc)()) {
BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);
this->ButtonFunc = &ButtonFunc;
}
If anyone has any advice on how I can properly send this function so that I can use it later.
A: I know this is a quite old topic. But there is an elegant way to handle this with c++11
#include <functional>
declare your function pointer like this
typedef std::function<int(int,int) > Max;
declare your the function your pass this thing into
void SetHandler(Max Handler);
suppose you pass a normal function to it you can use it like normal
SetHandler(&some function);
suppose you have a member function
class test{
public:
int GetMax(int a, int b);
...
}
in your code you can pass it using std::placeholders like this
test t;
Max Handler = std::bind(&test::GetMax,&t,std::placeholders::_1,std::placeholders::_2);
some object.SetHandler(Handler);
A: Would you not be better served to use standard OO. Define a contract (virtual class) and implement that in your own class, then just pass a reference to your own class and let the receiver call the contract function.
Using your example (I've renamed the 'test2' method to 'buttonAction'):
class ButtonContract
{
public:
virtual void buttonAction();
}
class testMenu : public MenuScreen, public virtual ButtonContract
{
public:
bool draw;
MenuButton<testMenu> x;
testMenu():MenuScreen("testMenu")
{
x.SetButton(100,100,TEXT("buttonNormal.png"),
TEXT("buttonHover.png"),
TEXT("buttonPressed.png"),
100, 40, &this);
draw = false;
}
//Implementation of the ButtonContract method!
void buttonAction()
{
draw = true;
}
};
In the receiver method, you store the reference to a ButtonContract, then when you want to perform the button's action just call the 'buttonAction' method of that stored ButtonContract object.
A: To call a member function by pointer, you need two things: A pointer to the object and a pointer to the function. You need both in MenuButton::SetButton()
template <class object>
void MenuButton::SetButton(int xPos, int yPos, LPCWSTR normalFilePath,
LPCWSTR hoverFilePath, LPCWSTR pressedFilePath,
int Width, int Height, object *ButtonObj, void (object::*ButtonFunc)())
{
BUTTON::SetButton(xPos, yPos, normalFilePath, hoverFilePath, pressedFilePath, Width, Height);
this->ButtonObj = ButtonObj;
this->ButtonFunc = ButtonFunc;
}
Then you can invoke the function using both pointers:
((ButtonObj)->*(ButtonFunc))();
Don't forget to pass the pointer to your object to MenuButton::SetButton():
testMenu::testMenu()
:MenuScreen("testMenu")
{
x.SetButton(100,100,TEXT("buttonNormal.png"), TEXT("buttonHover.png"),
TEXT("buttonPressed.png"), 100, 40, this, test2);
draw = false;
}
A: In the rare case that you happen to be developing with Borland C++Builder and don't mind writing code specific to that development environment (that is, code that won't work with other C++ compilers), you can use the __closure keyword. I found a small article about C++Builder closures. They're intended primarily for use with Borland VCL.
A: Others have told you how to do it correctly. But I'm surprised no-one told you this code is actually dangerous:
this->ButtonFunc = &ButtonFunc;
Since ButtonFunc is a parameter, it will go out of scope when the function returns. You are taking its address. You will get a value of type void (object::**ButtonFunc)() (pointer to a pointer to a member function) and assign it to this->ButtonFunc. At the time you would try to use this->ButtonFunc you would try to access the storage of the (now not existing anymore) local parameter, and your program would probably crash.
I agree with Commodore's solution. But you have to change his line to
((ButtonObj)->*(ButtonFunc))();
since ButtonObj is a pointer to object.
A: I'd strongly recommend boost::bind and boost::function for anything like this.
See Pass and call a member function (boost::bind / boost::function?)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: nHibernate isn't retrieving manually changed data nHibernate is not able to retrieve manually changed data from repository table? I have disabled second level cache also but looks like it(nhibernate) is retrieving sometimes from cache and sometimes from repository table.
A: There are two types of caches in nhibernate: session caches and second-level caches. The session cache is always caching objects seen by that session - it's how nhibernate knows which objects have changed and need to be persisted. The second-level cache, which you disabled, is below that. The information you're seeing cached is coming from the session cache.
If your application needs to see changes persisted by other sources (say, manual database changes), the answer is probably to create sessions at a finer granularity. While a SessionFactory lives for the life of your application, a Session object should be created much more often. For example, in a web application, every request generates its own session.
If that's not an option, session.Clear() will evict all objects from the session.
A: A good relation with NHibernate always depends on strong OO commitment and at most common cases depends on data changes exclusivity. If you don't have it you'll see some nasty problems and will give up most of the really nice things NH could offer.
Lets say there is a class called "Foo" mapped to a table "Foo" with columns "Id" and "SomeProperty". If all rows have "SomeProperty" manually updated from "oldValue" to "newValue" and NH sends some query to DB asking for all Foos where SomeProperty = "newValue", the DB returns all Foos, as expected. But Foo instances NH delivers may have "oldValue" because Foo with the returned Id was already attached to the session (on other words, it was on 1st level cache).
The only short way to make NHibernate be aware of all manual updates is using StatelessSesion, so it won't cache object instances and will always deliver the DB version of data. But if you want to apply this on a transactional system its a clear sign of unappropriate use of NH and you won't obtain most of nice NH features.
A: I don't know whether it will solve the problem you're having, but the documentation states:
To completely evict all objects from the session cache, call ISession.Clear()
For the second-level cache, there are methods defined on ISessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role.
If you did this every time you did something that executes a SELECT on data likely to change out of band, it should do what you want.
A: I think you're going to have to be a bit more descriptive of your exact problem to get an answer; I have some minimal experience with nhibernate, but I can't really go about replicating what's going on and try to fix it without, say, some code.
A: Srry for being too specific
Nhibernate is retrieving data without any problem.
But When I manually change data in a repository table. the Icriterea(nhibernate) is sometimes picking up from cache or from the table.
i am using Icriteria funcnality:
ICriteria criteria = session.CreateCriteria(typeof(xyzclass));
criteria.Add(Expression.Eq("xyzclass", somestringto retreivedata));
criteria.SetCacheable(false);
return criteria.UniqueResult();
A: I've never actually used the caching features of NHibernate first hand, but I believe the intent of it is to remove the need to go to the database at all, meaning it wouldn't pick up manual changes because it doesn't know about them.
I'd question exactly what it is you're trying to achieve here, are you just doing some testing by manually editing the database or will this be a regular activity in a live application? Really, the only thing that should be modifying your database is the application, doing so through your NHibernate data layer, therefor updating and/or dirtying the cache in the process.
A: THis is just part of testing.
But in the future we could edit the datatable manually.
I have also set lazy to false for that table and commented out all the second level cache properties used by hibernate.
But even then it is returning me different values instead of newly edited value.
Sometimes it is giving me old value and sometimes the new, so it is not constant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Linux-based solution for domain management? Using any member of the Windows Server family, I can set up an active directory, and have a single pool of users for a large scale of computers; access can be given / removed for any shared resources in the given domain (including access to client computers, etc).
What similar (and widespread) solutions exist for managing a multi-user, multi-computer environment using Linux? What are their advantages/disadvantages? And how can they interoperate with Windows?
A: Not sure if this is what you had in mind, but Linux w/Samba can act as a domain controller for Windows desktops. For example, see SAMBA (Domain Controller) Server For Small Workgroups at HowToForge. This works for file/print sharing etc.
For something more akin to Microsoft's Active Directory, you might check out Red Hat Directory Server:
Red Hat Directory Server is an LDAP-based server that centralizes application
settings, user profiles, group data, policies, and access control information
into an operating system-independent, network-based registry.
If cost is a concern, there's a Fedora Directory Server version that's the community version for free.
Another potential offering would be Sun's OpenDS project:
OpenDS is an open source community project building a free and
comprehensive next generation directory service based on LDAP
and DSML. OpenDS is designed to address large deployments, to
provide high performance, to be highly extensible, and to be
easy to deploy, manage and monitor.
A: Joe: I think NIS is considered legacy Unix stuff these days. I wouldn't recommend it to anyone on a new deployment.
At the company where I work, we run Apple's Open Directory for our LDAP directory and Kerberos KDC. You can achieve the same thing using Red Hat's directory server (mentioned by Jay above), or something like Apache Directory.
While LDAP and Kerberos can be daunting at first, and a bit challenging to get working, I think the effort is quite worthwhile. You can easily scale both up to whatever size you need.
For the Windows end of things, you can hook Samba in to LDAP and authenticate your Windows clients against that.
A: LDAP is clearly the way to go. See for instance OpenLDAP Software 2.4 Administrator's Guide.
An example of setting up user authentication with LDAP on Linux and FreeBSD is on my blog (in french), Comptes Unix stockés sur LDAP.
A: Supposedly Linux computers can use Likewise Open to connect to Active Directory Domains. i.e. use the Active Directory credentials for authentication and access control.
I have tried it briefly myself and had no luck though (ended up inadvertently making my desktop system a domain controller and had to get network admins to reassign it!). Probably just needed to read the docs a bit better...
A: Samba provides interoperability with Windows domain controllers. With version 3 it can act as a primary domain controller. From what I read, version 4 will improve support for ActiveDirectory.
A: Linux servers can be configured to participate in NIS domains, you should typically be prompted for this kind of setup when building the server. NIS is a lot like Active Directory, providing common identity and authentication across many boxes. You can also configure home directories to be mounted off a common NFS share so that identity and working environment move with the user from box to box.
I have experienced this from the user/tech-lead side of things, hopefully a Linux admin can provide further pointers on how to do it and where to find resources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I get the caller's IP address in a WebMethod? How do I get the caller's IP address in a WebMethod?
[WebMethod]
public void Foo()
{
// HttpRequest... ? - Not giving me any options through intellisense...
}
using C# and ASP.NET
A: Just a caution. IP addresses can't be used to uniquely identify clients. NAT Firewalls and corporate proxies are everywhere, and hide many users behind a single IP.
A: HttpContext.Current.Request.UserHostAddress is what you want.
A: Try:
Context.Request.UserHostAddress
A: Try this:
string ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
Haven't tried it in a webMethod, but I use it in standard HttpRequests
A: The HttpContext is actually available inside the WebService base class, so just use Context.Request (or HttpContext.Current which also points to the current context) to get access to the members provided by the HttpRequest.
A: I made the following function:
static public string sGetIP()
{
try
{
string functionReturnValue = null;
String oRequestHttp =
WebOperationContext.Current.IncomingRequest.Headers["User-Host-Address"];
if (string.IsNullOrEmpty(oRequestHttp))
{
OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
oRequestHttp = endpoint.Address;
}
return functionReturnValue;
}
catch (Exception ex)
{
return "unknown IP";
}
}
This work only in Intranet, if you have some Proxy or natting you should study if the original IP is moved somewhere else in the http packet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: How do you prevent a user from posting data multiple times on a website I am working on a web application (J2EE) and I would like to know the options that are available for handling a double post from the browser.
The solutions that I have seen and used in the past are all client-side:
*
*Disable the submit button as soon as the user clicks it.
*Follow a POST-Redirect-GET pattern to prevent POSTs when the user clicks the back button.
*Handle the onSubmit event of the form and keep track of the submission status with JavaScript.
I would prefer to implement a server side solution if possible. Are there any better approaches than the ones I have mentioned above, or are client-side solutions best?
A: You could supply a "ticket" as part of the form, some random number - and make sure it doesn't get accepted twice, on the server side.
A: Two server-side solutions come to mind:
*
*Create one-time use "tokens" in a hidden form field. Once a token is used, it is deleted from whatever database or session context object you're storing it in. The second time, it's not accepted.
*Cache information received, and if an identical form is received within a certain time period (10 minutes? an hour? You decide!) it is ignored.
A: we use a time sensitive, one time ticket. It's like a session id of sort. But it is tied to the form/page.
You discard the ticket when the user submits the page, and you only process pages that comes with a valid ticket. You can, at the same time, tighten security by attaching the ticket to a user, so tat if a ticket comes in that is submitted by a user that is not the user that the ticket was submitted to, you reject the request.
A: Implement a uniqueid to go with the request and log it along with the execution. If the id was already logged, you don't do the job again. This is kinda like the fallback solution - you should try and disable the button or link clientside as well as you suggested yourself
A: Struts has something like this built in if you happen to be using it.
http://struts.apache.org/1.x/apidocs/org/apache/struts/util/TokenProcessor.html
A: Its hard to implement an idiot-proof solution (as they are alway improving the idiots). No matter what you do, the client side can be manipulated or perform incorrectly.
Your solution has got to be server side to be reliable and secure. That said, one approach is to review the request and check system/database state or logs to determine if it was already processed. Ideally, the process on the server side should be idempotent if possible, and it will have to protect against dupe submits if it can't be.
A: I'd use a timestamp and compare values with your server side code. If two timestamps are close enough and have the same IP address, ignore the second form submission.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Webpart feature not adding Description I am adding a webpart to the webpart gallery as part of a feature within a solution.
When the webpart is added to the gallery, the webparts Description field is being overwritten by an empty string.
I have added a description to everywhere I can think of, including:
*
*The webpart itself. myWebpart.webpart <property name="Description" type="string">my description</property>
*The feature.xml Description="mywebpart description"
*The feature.xml <Property Key="Description" Value="mywebpart description"></Property>
*The webpartManifest.xml (specified in the feature) <File ...><Property Name=Description" Value="mywebpart description">
I have run out of ideas of where to put the description so it will appear in the Description field of the web part gallery when the solution is deployed.
Do you have any ideas?
A: Check the following blog, it describes the whole process:
Adding custom webparts in a Sharepoint Site Definition
Specially notice the custom property TextToDisplay (I think you've gone through all the other steps).
A: Actually, all the steps were correct, except that the property name for the webpart was mis-spelt as "Decription".
Doh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I simulate a low bandwidth, high latency environment? I need to simulate a low bandwidth, high latency connection to a server in order to emulate the conditions of a VPN at a remote site. The bandwidth and latency should be tweakable so I can discover the best combination in order to run our software package.
A: For macOS, there is the Network Link Conditioner that simulates configurable bandwidth, latency, and packet loss. It is contained in the Additional Tools for Xcode package.
A: I would try using netem on linux. With it you can simulate additional delay, corruption, packet loss and duplication. It even works on the loopback device.
A: Another client-side program (Windows only), is NetLimiter - http://www.netlimiter.com
A: I use NetBalancer on my Windows machine.
http://seriousbit.com/netbalancer/
Updates on 2017-10-07: The last free version of NetBalancer is 9.2.7. The program has a hard-coded expiration date. Before you start the NetBalancer service, you need to turn back the system clock before 2016-10-18. See this article for details.
A: Found this one for Windows using Fiddler (free solution)
http://www.logic-worx.com/index.php/tools-and-apps/fiddler-connection-simulator/
A: I guess tc could do the job on UNIX based platform.
tc is used to configure Traffic Control in the Linux kernel
http://lartc.org/manpages/tc.txt
A: There's an excellent writeup of setting up a FreeBSD machine to do just this - take your standard old desktop, toss in an additional NIC, and build.
The writeup is available at http://www.freebsd.org/doc/en/articles/filtering-bridges/article.html.
In step 5 of the above instructions, you're enabling a firewall. For just simulating a different IP connection, you could (for example) do the following:
Create a file /etc/rc.firewall.56k which contains the following:
ipfw add pipe 1 ip from any to any out
ipfw add pipe 2 ip from any to any in
ipfw pipe 1 config bw 56Kbit/s
ipfw pipe 2 config bw 56Kbit/s
And change /etc/rc.conf... replace the line
firewall_type="open"
with
firewall_type="/etc/rc.firewall.56k"
reboot, and you've got yourself a 56K bridge!
If you happen to be working from a Macintosh, that OS has ipfw built into it by default. I've done the same thing by routing network traffic over the Airport and through the ethernet, setting it up so that anything coming over the airport has the same characteristics as whatever I'm trying to emulate. You can invoke the ipfw commands directly from the terminal and get the same effects.
A: In the past, I have used a bridge using the Linux Netem (Network Emulation) functionality. It is highly configurable -- allowing the introduction of delays (the first example is for a WAN), packet loss, corruption, etc.
I'm noting that Netem worked very well for my applications, but I also ended up using WANem several times. The provided bootable ISO (and virtual appliance images) made it quite handy.
A: To simulate a low bandwidth connection for testing web sites use Google Chrome, you can go to the Network Tab in F12 Tools and select a bandwidth level to simulate or create custom bandwidth to simulate.
A: I found this little neat program for Windows called clumsy. It's in kind of alpha status, but it seem to work fine for me, and it's open source.
Edit: Others have noticed that you can't limit bandwidth with clumsy, and that's true. You can only add Latency and a couple of other network related errors.
This will disqualify this answer as a valid answer to the question, however since I had good use for it when I wanted to simulate a bad network so I'll leave it here as long as it has > 0 votes or similar.
A: Charles
I came across Charles the web debugging proxy application and had great success in emulating network latency. It works on Windows, Mac, and Linux.
Bandwidth throttle / Bandwidth simulator
Charles can be used to adjust the bandwidth and latency of your Internet connection. This enables you to simulate modem conditions using your high-speed connection.
The bandwidth may be throttled to any arbitrary bytes per second. This enables any connection speed to be simulated.
The latency may also be set to any arbitrary number of milliseconds. The latency delay simulates the latency experienced on slower connections, that is the delay between making a request and the request being received at the other end.
DummyNet
You could also use vmware to run BSD or Linux and try this article (DummyNet) or this one.
A: Try WANem
WANem is a Wide Area Network Emulator, meant to provide a real experience of a Wide Area Network/Internet, during application development / testing over a LAN environment.
A: For Windows you can use this application: http://www.softperfect.com/products/connectionemulator/
WAN Connection Emulator for Windows 2000, XP, 2003, Vista, Seven and 2008.
Perhaps the only one available for Windows.
A: If you're on linux, I find the Traffic Control program to be a great help for this sort of thing.
A: There is a product from http://www.shunra.com called VE Desktop which can be used to simulate varying network conditions. It allows you to tweak latencies, bandwidth and packetloss with a simple UI. Only caveat is, its not free. Hope this helps.
A: I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator
If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.
A: i think i found what i need. maybe you can use charles proxy or slowy. hope it helps.
A: Take a look at the NE-ONE Network Emulator which allows you to configure bandwidth, latency, packet loss, packet reordering, packet duplication, packet fragmentation, network congestion and many more impairments so that you can create real-world network conditions in the lab. Different impairments can be configured for the up and downlink so you could have a really good uplink but a really bad downlink experience, great for seeing how the app handles TCP queuing because the acks don't come back in a timely manner and the overall latency therefore increases!
There's an overview video here http://www.youtube.com/watch?v=DwtqlE7LcrQ specifically aimed at game developers, but it shows what it's about. NE-ONE is configured using a web browser so it's really easy to get installed and configured - you don't need to be a network guru :-)
There's a hardware version - http://www.itrinegy.com/index.php/products/network-emulators/ne-one - or you can download a Virtual Appliance (software) version that runs under VMware ESXi Server. The Virtual Appliance can be download from VMware's Solution Exchange - solutionexchange.vmware.com/store/products/ne-one-flex-network-emulator
A: LANforge ICE is a network emulator with an emphasis on virtual routing, jitter, corruption and delay. Projects have used it to emulate satellite link, cable and modem connections, and high-speed (10Gbit) wan emulation. You can use a Java GUI to build your virtual networks and generate very detailed reports of the traffic flow. The LANforge products also provide traffic generation features: frame, ethernet, layer-3 and stateful traffic (NFS, http). Recent editions for LANforge have sophisticated WiFi testing features as well.
A: You can try this: CovenantSQL/GNTE
just write YAML like this:
group:
-
name: china
nodes:
-
ip: 10.250.1.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.1.3
cmd: "cd /scripts && ./YourBin args"
delay: "100ms 10ms 30%"
loss: "1% 10%"
-
name: us
nodes:
-
ip: 10.250.2.2
cmd: "cd /scripts && ./YourBin args"
-
ip: 10.250.2.3
cmd: "cd /scripts && ./YourBin args"
delay: "1000ms 10ms 30%"
loss: "1% 10%"
network:
-
groups:
- china
- us
delay: "200ms 10ms 1%"
corrupt: "0.2%"
rate: "10mbit"
run ./generate scripts/your.yaml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "221"
}
|
Q: Can you keep Visual Studio source control binding info out of .sln and .csproj files? My Visual Studio 2005 is storing the info about which projects and solutions go with which source control repositories in the .sln and .csproj files. Is it possible to make it store that binding information in some external file instead?
The reason I wish the info were stored outside the solution/project files is to facilitate experimenting with the AnknSVN plugin. Right now we have all our stuff in VSS 6, but I want to maintain an experimental copy of the repository of SVN and then manually sync the two using the ideas described here:
http://www.dotnet6.com/blogs/jeroen/archive/2008/04/05/using-subversion-in-a-vss-only-shop.aspx
Unfortunately, having bindings stored in the .sln file (for example) throws a wrench in this. To illustrate, let's say I copy my whole VSS repository into a parallel SVN instance. Now I open up the main solution from SVN in Visual Studio using AnknSvn; in this process, AnkhSvn will change the source control binding info in the .sln file to point to SVN. Next let's say I add a new project P1 to the solution. This will cause Visual Studio to modify the .sln file a second time, noting the existence of P1. Say at this point I want to sync the changes I've made in the SVN copy back to the VSS repository. If source control binding weren't stored in the .sln file, that wouldn't be too bad. However, the .sln file now has two different changes in it, and I want to propagate the project-add change back to VSS, but I don't want to propagate the source control binding change back to VSS, because that would break the build for all the VSS users! I don't think there's a way to propagate the one change without the other manual intervention. If Visual Studio would just stored the binding info outside the .sln file, in contrast, then I would indeed want to propagate all .sln file changes back to VSS, and that would be ok.
A: VisualSVN does not use the native source control ecosystem plugin (SCC) so thus does not pollute your solution or project file. It is commercial licensed but very reasonable < $50. Thus allowing you to continue to use the nasty VSS (although ideally exclude .svn directories)
A: AnkhSVN 2.0 has two modes of operation.
*
*Connected (recommended). This stores binding information in the .sln and optionally project files.
*Disconnected. This does not store the binding.
You can connect and disconnect the solution and individual projects in File->Subversion->Change Source Control.
The advantages of connecting are:
*
*Automatic switching between SCC providers on opening the solution (E.g. between VSS, TFS and AnkhSVN)
*Compatible with all project types that implement SCC support.
*(2.1+) Automatic handling projects outside the primary working copy. (E.g. websites in c:\inetpub)
Note: If you previously used AnkhSVN 1.X on a solution you should manually remove your Ankh.load files. When AnkhSVN 2.0 sees an Ankh.load file it automatically connects your solution.
[Follow up:]
An easy way to use AnkhSVN next to another SCC implementation is to just create an extra .sln file. AnkhSVN doesn't use the actual values in the individual project's SCC fields. (It just has to insert them to enable the project for full SCC management)
A: A coworker wrote this NAnt task for removing bindings
http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/21/2custom-nant-task-for-removing-tfs-bindings.aspx
You could probably adapt into a custom build step or other script to help you.
A: IIRC both AnkhSVN, and VSS implements version-control binding strictly by .sln / .csproj files (the version control plugin interface of VS facilitate this kind of storage). Therefore, the short answer is no.
However, you can still use subversion as an outside version-control solution, which, in terms of security, and stability, would be much better, that VSS, using either the command line (the book is your friend), or TortoiseSVN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Are there constants in JavaScript? Is there a way to use constants in JavaScript?
If not, what's the common practice for specifying variables that are used as constants?
A: Yet there is no exact cross browser predefined way to do it , you can achieve it by controlling the scope of variables as showed on other answers.
But i will suggest to use name space to distinguish from other variables. this will reduce the chance of collision to minimum from other variables.
Proper namespacing like
var iw_constant={
name:'sudhanshu',
age:'23'
//all varibale come like this
}
so while using it will be iw_constant.name or iw_constant.age
You can also block adding any new key or changing any key inside iw_constant using Object.freeze method. However its not supported on legacy browser.
ex:
Object.freeze(iw_constant);
For older browser you can use polyfill for freeze method.
If you are ok with calling function following is best cross browser way to define constant. Scoping your object within a self executing function and returning a get function for your constants
ex:
var iw_constant= (function(){
var allConstant={
name:'sudhanshu',
age:'23'
//all varibale come like this
};
return function(key){
allConstant[key];
}
};
//to get the value use
iw_constant('name') or iw_constant('age')
** In both example you have to be very careful on name spacing so that your object or function shouldn't be replaced through other library.(If object or function itself wil be replaced your whole constant will go)
A: "use strict";
var constants = Object.freeze({
"π": 3.141592653589793 ,
"e": 2.718281828459045 ,
"i": Math.sqrt(-1)
});
constants.π; // -> 3.141592653589793
constants.π = 3; // -> TypeError: Cannot assign to read only property 'π' …
constants.π; // -> 3.141592653589793
delete constants.π; // -> TypeError: Unable to delete property.
constants.π; // -> 3.141592653589793
See Object.freeze. You can use const if you want to make the constants reference read-only as well.
A: For a while, I specified "constants" (which still weren't actually constants) in object literals passed through to with() statements. I thought it was so clever. Here's an example:
with ({
MY_CONST : 'some really important value'
}) {
alert(MY_CONST);
}
In the past, I also have created a CONST namespace where I would put all of my constants. Again, with the overhead. Sheesh.
Now, I just do var MY_CONST = 'whatever'; to KISS.
A: IE does support constants, sort of, e.g.:
<script language="VBScript">
Const IE_CONST = True
</script>
<script type="text/javascript">
if (typeof TEST_CONST == 'undefined') {
const IE_CONST = false;
}
alert(IE_CONST);
</script>
A: My opinion (works only with objects).
var constants = (function(){
var a = 9;
//GLOBAL CONSTANT (through "return")
window.__defineGetter__("GCONST", function(){
return a;
});
//LOCAL CONSTANT
return {
get CONST(){
return a;
}
}
})();
constants.CONST = 8; //9
alert(constants.CONST); //9
Try! But understand - this is object, but not simple variable.
Try also just:
const a = 9;
A: ECMAScript 5 does introduce Object.defineProperty:
Object.defineProperty (window,'CONSTANT',{ value : 5, writable: false });
It's supported in every modern browser (as well as IE ≥ 9).
See also: Object.defineProperty in ES5?
A: I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I've come up with a viable solution to this.
It seems that most of the answers that I've come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts' answer that the constants object can not be accessed by the outside, but only from the functions on the inside.
So I came up with this solution:
Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the 'real' functions by having other functions call the 'real' functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are 'protected' on the inside and cannot be changed.
/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/
(function(){
/*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST).
They're the same just as he did them, the only things I changed are the variable names and the text
of the error messages.
*/
//object literal to hold the constants
var j = {};
/*Global function _define(String h, mixed m). I named it define to mimic the way PHP 'defines' constants.
The argument 'h' is the name of the const and has to be a string, 'm' is the value of the const and has
to exist. If there is already a property with the same name in the object holder, then we throw an error.
If not, we add the property and set the value to it. This is a 'hidden' function and the user doesn't
see any of your coding call this function. You call the _makeDef() in your code and that function calls
this function. - You can change the error messages to whatever you want them to say.
*/
self._define = function(h,m) {
if (typeof h !== 'string') { throw new Error('I don\'t know what to do.'); }
if (!m) { throw new Error('I don\'t know what to do.'); }
else if ((h in j) ) { throw new Error('We have a problem!'); }
else {
j[h] = m;
return true;
}
};
/*Global function _makeDef(String t, mixed y). I named it makeDef because we 'make the define' with this
function. The argument 't' is the name of the const and doesn't need to be all caps because I set it
to upper case within the function, 'y' is the value of the value of the const and has to exist. I
make different variables to make it harder for a user to figure out whats going on. We then call the
_define function with the two new variables. You call this function in your code to set the constant.
You can change the error message to whatever you want it to say.
*/
self._makeDef = function(t, y) {
if(!y) { throw new Error('I don\'t know what to do.'); return false; }
q = t.toUpperCase();
w = y;
_define(q, w);
};
/*Global function _getDef(String s). I named it getDef because we 'get the define' with this function. The
argument 's' is the name of the const and doesn't need to be all capse because I set it to upper case
within the function. I make a different variable to make it harder for a user to figure out whats going
on. The function returns the _access function call. I pass the new variable and the original string
along to the _access function. I do this because if a user is trying to get the value of something, if
there is an error the argument doesn't get displayed with upper case in the error message. You call this
function in your code to get the constant.
*/
self._getDef = function(s) {
z = s.toUpperCase();
return _access(z, s);
};
/*Global function _access(String g, String f). I named it access because we 'access' the constant through
this function. The argument 'g' is the name of the const and its all upper case, 'f' is also the name
of the const, but its the original string that was passed to the _getDef() function. If there is an
error, the original string, 'f', is displayed. This makes it harder for a user to figure out how the
constants are being stored. If there is a property with the same name in the object holder, we return
the constant value. If not, we check if the 'f' variable exists, if not, set it to the value of 'g' and
throw an error. This is a 'hidden' function and the user doesn't see any of your coding call this
function. You call the _getDef() function in your code and that function calls this function.
You can change the error messages to whatever you want them to say.
*/
self._access = function(g, f) {
if (typeof g !== 'string') { throw new Error('I don\'t know what to do.'); }
if ( g in j ) { return j[g]; }
else { if(!f) { f = g; } throw new Error('I don\'t know what to do. I have no idea what \''+f+'\' is.'); }
};
/*The four variables below are private and cannot be accessed from the outside script except for the
functions inside this anonymous function. These variables are strings of the four above functions and
will be used by the all-dreaded eval() function to set them back to their original if any of them should
be changed by a user trying to hack your code.
*/
var _define_func_string = "function(h,m) {"+" if (typeof h !== 'string') { throw new Error('I don\\'t know what to do.'); }"+" if (!m) { throw new Error('I don\\'t know what to do.'); }"+" else if ((h in j) ) { throw new Error('We have a problem!'); }"+" else {"+" j[h] = m;"+" return true;"+" }"+" }";
var _makeDef_func_string = "function(t, y) {"+" if(!y) { throw new Error('I don\\'t know what to do.'); return false; }"+" q = t.toUpperCase();"+" w = y;"+" _define(q, w);"+" }";
var _getDef_func_string = "function(s) {"+" z = s.toUpperCase();"+" return _access(z, s);"+" }";
var _access_func_string = "function(g, f) {"+" if (typeof g !== 'string') { throw new Error('I don\\'t know what to do.'); }"+" if ( g in j ) { return j[g]; }"+" else { if(!f) { f = g; } throw new Error('I don\\'t know what to do. I have no idea what \\''+f+'\\' is.'); }"+" }";
/*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we're 'checking the functions'
The argument 'u' is the name of any of the four above function names you want to check. This function will
check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then
we use the eval() function to set the function back to its original coding using the function string
variables above. This function will also throw an error depending upon the doError variable being set to true
This is a 'hidden' function and the user doesn't see any of your coding call this function. You call the
doCodeCheck() function and that function calls this function. - You can change the error messages to
whatever you want them to say.
*/
self._doFunctionCheck = function(u) {
var errMsg = 'We have a BIG problem! You\'ve changed my code.';
var doError = true;
d = u;
switch(d.toLowerCase())
{
case "_getdef":
if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ }
else { eval("_getDef = "+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_makedef":
if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ }
else { eval("_makeDef = "+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_define":
if(_define.toString().indexOf("else if((h in j) ) {") != -1) { /*do nothing*/ }
else { eval("_define = "+_define_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
case "_access":
if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ }
else { eval("_access = "+_access_func_string); if(doError === true) { throw new Error(errMsg); } }
break;
default:
if(doError === true) { throw new Error('I don\'t know what to do.'); }
}
};
/*Global function _doCodeCheck(String v). I named it doCodeCheck because we're 'doing a code check'. The argument
'v' is the name of one of the first four functions in this script that you want to check. I make a different
variable to make it harder for a user to figure out whats going on. You call this function in your code to check
if any of the functions has been changed by the user.
*/
self._doCodeCheck = function(v) {
l = v;
_doFunctionCheck(l);
};
}())
It also seems that security is really a problem and there is not way to 'hide' you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/. (This is not my site, don't worry I'm not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.
*
*Copy all the code in the above script and paste it into the top textarea on the javascriptcompressor.com page.
*Check the Base62 encode checkbox, check the Shrink Variables checkbox.
*Press the Compress button.
*Paste and save it all in a .js file and add it to your page in the head of your page.
A: Clearly this shows the need for a standardized cross-browser const keyword.
But for now:
var myconst = value;
or
Object['myconst'] = value;
Both seem sufficient and anything else is like shooting a fly with a bazooka.
A: I use const instead of var in my Greasemonkey scripts, but it is because they will run only on Firefox...
Name convention can be indeed the way to go, too (I do both!).
A: In JavaScript my practice has been to avoid constants as much as I can and use strings instead. Problems with constants appear when you want to expose your constants to the outside world:
For example one could implement the following Date API:
date.add(5, MyModule.Date.DAY).add(12, MyModule.Date.HOUR)
But it's much shorter and more natural to simply write:
date.add(5, "days").add(12, "hours")
This way "days" and "hours" really act like constants, because you can't change from the outside how many seconds "hours" represents. But it's easy to overwrite MyModule.Date.HOUR.
This kind of approach will also aid in debugging. If Firebug tells you action === 18 it's pretty hard to figure out what it means, but when you see action === "save" then it's immediately clear.
A: Okay, this is ugly, but it gives me a constant in Firefox and Chromium, an inconstant constant (WTF?) in Safari and Opera, and a variable in IE.
Of course eval() is evil, but without it, IE throws an error, preventing scripts from running.
Safari and Opera support the const keyword, but you can change the const's value.
In this example, server-side code is writing JavaScript to the page, replacing {0} with a value.
try{
// i can haz const?
eval("const FOO='{0}';");
// for reals?
var original=FOO;
try{
FOO='?NO!';
}catch(err1){
// no err from Firefox/Chrome - fails silently
alert('err1 '+err1);
}
alert('const '+FOO);
if(FOO=='?NO!'){
// changed in Sf/Op - set back to original value
FOO=original;
}
}catch(err2){
// IE fail
alert('err2 '+err2);
// set var (no var keyword - Chrome/Firefox complain about redefining const)
FOO='{0}';
alert('var '+FOO);
}
alert('FOO '+FOO);
What is this good for? Not much, since it's not cross-browser. At best, maybe a little peace of mind that at least some browsers won't let bookmarklets or third-party script modify the value.
Tested with Firefox 2, 3, 3.6, 4, Iron 8, Chrome 10, 12, Opera 11, Safari 5, IE 6, 9.
A: An improved version of Burke's answer that lets you do CONFIG.MY_CONST instead of CONFIG.get('MY_CONST').
It requires IE9+ or a real web browser.
var CONFIG = (function() {
var constants = {
'MY_CONST': 1,
'ANOTHER_CONST': 2
};
var result = {};
for (var n in constants)
if (constants.hasOwnProperty(n))
Object.defineProperty(result, n, { value: constants[n] });
return result;
}());
* The properties are read-only, only if the initial values are immutable.
A: If it is worth mentioning, you can define constants in angular using $provide.constant()
angularApp.constant('YOUR_CONSTANT', 'value');
A: JavaScript ES6 (re-)introduced the const keyword which is supported in all major browsers.
Variables declared via const cannot be re-declared or re-assigned.
Apart from that, const behaves similar to let.
It behaves as expected for primitive datatypes (Boolean, Null, Undefined, Number, String, Symbol):
const x = 1;
x = 2;
console.log(x); // 1 ...as expected, re-assigning fails
Attention: Be aware of the pitfalls regarding objects:
const o = {x: 1};
o = {x: 2};
console.log(o); // {x: 1} ...as expected, re-assigning fails
o.x = 2;
console.log(o); // {x: 2} !!! const does not make objects immutable!
const a = [];
a = [1];
console.log(a); // 1 ...as expected, re-assigning fails
a.push(1);
console.log(a); // [1] !!! const does not make objects immutable
If you really need an immutable and absolutely constant object: Just use const ALL_CAPS to make your intention clear. It is a good convention to follow for all const declarations anyway, so just rely on it.
A: Are you trying to protect the variables against modification? If so, then you can use a module pattern:
var CONFIG = (function() {
var private = {
'MY_CONST': '1',
'ANOTHER_CONST': '2'
};
return {
get: function(name) { return private[name]; }
};
})();
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
CONFIG.MY_CONST = '2';
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
CONFIG.private.MY_CONST = '2'; // error
alert('MY_CONST: ' + CONFIG.get('MY_CONST')); // 1
Using this approach, the values cannot be modified. But, you have to use the get() method on CONFIG :(.
If you don't need to strictly protect the variables value, then just do as suggested and use a convention of ALL CAPS.
A: Another alternative is something like:
var constants = {
MY_CONSTANT : "myconstant",
SOMETHING_ELSE : 123
}
, constantMap = new function ConstantMap() {};
for(var c in constants) {
!function(cKey) {
Object.defineProperty(constantMap, cKey, {
enumerable : true,
get : function(name) { return constants[cKey]; }
})
}(c);
}
Then simply: var foo = constantMap.MY_CONSTANT
If you were to constantMap.MY_CONSTANT = "bar" it would have no effect as we're trying to use an assignment operator with a getter, hence constantMap.MY_CONSTANT === "myconstant" would remain true.
A: in Javascript already exists constants. You define a constant like this:
const name1 = value;
This cannot change through reassignment.
A: The keyword 'const' was proposed earlier and now it has been officially included in ES6. By using the const keyword, you can pass a value/string that will act as an immutable string.
A: No, not in general. Firefox implements const but I know IE doesn't.
@John points to a common naming practice for consts that has been used for years in other languages, I see no reason why you couldn't use that. Of course that doesn't mean someone will not write over the variable's value anyway. :)
A: In JavaScript, my preference is to use functions to return constant values.
function MY_CONSTANT() {
return "some-value";
}
alert(MY_CONSTANT());
A: Mozillas MDN Web Docs contain good examples and explanations about const. Excerpt:
// define MY_FAV as a constant and give it the value 7
const MY_FAV = 7;
// this will throw an error - Uncaught TypeError: Assignment to constant variable.
MY_FAV = 20;
But it is sad that IE9/10 still does not support const. And the reason it's absurd:
So, what is IE9 doing with const? So
far, our decision has been to not
support it. It isn’t yet a consensus
feature as it has never been available
on all browsers.
...
In the end, it seems like the best
long term solution for the web is to
leave it out and to wait for
standardization processes to run their
course.
They don't implement it because other browsers didn't implement it correctly?! Too afraid of making it better? Standards definitions or not, a constant is a constant: set once, never changed.
And to all the ideas: Every function can be overwritten (XSS etc.). So there is no difference in var or function(){return}. const is the only real constant.
Update:
IE11 supports const:
IE11 includes support for the well-defined and commonly used features of the emerging ECMAScript 6 standard including let, const, Map, Set, and WeakMap, as well as __proto__ for improved interoperability.
A: Introducing constants into JavaScript is at best a hack.
A nice way of making persistent and globally accessible values in JavaScript would be declaring an object literal with some "read-only" properties like this:
my={get constant1(){return "constant 1"},
get constant2(){return "constant 2"},
get constant3(){return "constant 3"},
get constantN(){return "constant N"}
}
you'll have all your constants grouped in one single "my" accessory object where you can look for your stored values or anything else you may have decided to put there for that matter. Now let's test if it works:
my.constant1; >> "constant 1"
my.constant1 = "new constant 1";
my.constant1; >> "constant 1"
As we can see, the "my.constant1" property has preserved its original value. You've made yourself some nice 'green' temporary constants...
But of course this will only guard you from accidentally modifying, altering, nullifying, or emptying your property constant value with a direct access as in the given example.
Otherwise I still think that constants are for dummies.
And I still think that exchanging your great freedom for a small corner of deceptive security is the worst trade possible.
A: Rhino.js implements const in addition to what was mentioned above.
A: const keyword available in javscript language but it does not support IE browser. Rest all browser supported.
A: with the "new" Object api you can do something like this:
var obj = {};
Object.defineProperty(obj, 'CONSTANT', {
configurable: false
enumerable: true,
writable: false,
value: "your constant value"
});
take a look at this on the Mozilla MDN for more specifics. It's not a first level variable, as it is attached to an object, but if you have a scope, anything, you can attach it to that. this should work as well.
So for example doing this in the global scope will declare a pseudo constant value on the window (which is a really bad idea, you shouldn't declare global vars carelessly)
Object.defineProperty(this, 'constant', {
enumerable: true,
writable: false,
value: 7,
configurable: false
});
> constant
=> 7
> constant = 5
=> 7
note: assignment will give you back the assigned value in the console, but the variable's value will not change
A: If you don't mind using functions:
var constant = function(val) {
return function() {
return val;
}
}
This approach gives you functions instead of regular variables, but it guarantees* that no one can alter the value once it's set.
a = constant(10);
a(); // 10
b = constant(20);
b(); // 20
I personally find this rather pleasant, specially after having gotten used to this pattern from knockout observables.
*Unless someone redefined the function constant before you called it
A: Forget IE and use the const keyword.
A: Group constants into structures where possible:
Example, in my current game project, I have used below:
var CONST_WILD_TYPES = {
REGULAR: 'REGULAR',
EXPANDING: 'EXPANDING',
STICKY: 'STICKY',
SHIFTING: 'SHIFTING'
};
Assignment:
var wildType = CONST_WILD_TYPES.REGULAR;
Comparision:
if (wildType === CONST_WILD_TYPES.REGULAR) {
// do something here
}
More recently I am using, for comparision:
switch (wildType) {
case CONST_WILD_TYPES.REGULAR:
// do something here
break;
case CONST_WILD_TYPES.EXPANDING:
// do something here
break;
}
IE11 is with new ES6 standard that has 'const' declaration.
Above works in earlier browsers like IE8, IE9 & IE10.
A: You can easily equip your script with a mechanism for constants that can be set but not altered. An attempt to alter them will generate an error.
/* author Keith Evetts 2009 License: LGPL
anonymous function sets up:
global function SETCONST (String name, mixed value)
global function CONST (String name)
constants once set may not be altered - console error is generated
they are retrieved as CONST(name)
the object holding the constants is private and cannot be accessed from the outer script directly, only through the setter and getter provided
*/
(function(){
var constants = {};
self.SETCONST = function(name,value) {
if (typeof name !== 'string') { throw new Error('constant name is not a string'); }
if (!value) { throw new Error(' no value supplied for constant ' + name); }
else if ((name in constants) ) { throw new Error('constant ' + name + ' is already defined'); }
else {
constants[name] = value;
return true;
}
};
self.CONST = function(name) {
if (typeof name !== 'string') { throw new Error('constant name is not a string'); }
if ( name in constants ) { return constants[name]; }
else { throw new Error('constant ' + name + ' has not been defined'); }
};
}())
// ------------- demo ----------------------------
SETCONST( 'VAT', 0.175 );
alert( CONST('VAT') );
//try to alter the value of VAT
try{
SETCONST( 'VAT', 0.22 );
} catch ( exc ) {
alert (exc.message);
}
//check old value of VAT remains
alert( CONST('VAT') );
// try to get at constants object directly
constants['DODO'] = "dead bird"; // error
A: The const keyword is in the ECMAScript 6 draft but as of Aug 8, 2015 it had only enjoyed a smattering of browser support. For the current state, consider this ES6 compatibility table. The syntax is:
const CONSTANT_NAME = 0;
A: Since ES2015, JavaScript has a notion of const:
const MY_CONSTANT = "some-value";
This will work in pretty much all browsers except IE 8, 9 and 10. Some may also need strict mode enabled.
You can use var with conventions like ALL_CAPS to show that certain values should not be modified if you need to support older browsers or are working with legacy code:
var MY_CONSTANT = "some-value";
A: Checkout https://www.npmjs.com/package/constjs, which provides three functions to create enum, string const and bitmap. The returned result is either frozen or sealed thus you can't change/delete the properties after they are created, you can neither add new properties to the returned result
create Enum:
var ConstJs = require('constjs');
var Colors = ConstJs.enum("blue red");
var myColor = Colors.blue;
console.log(myColor.isBlue()); // output true
console.log(myColor.is('blue')); // output true
console.log(myColor.is('BLUE')); // output true
console.log(myColor.is(0)); // output true
console.log(myColor.is(Colors.blue)); // output true
console.log(myColor.isRed()); // output false
console.log(myColor.is('red')); // output false
console.log(myColor._id); // output blue
console.log(myColor.name()); // output blue
console.log(myColor.toString()); // output blue
// See how CamelCase is used to generate the isXxx() functions
var AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');
var curMode = AppMode.LOG_IN;
console.log(curMode.isLogIn()); // output true
console.log(curMode.isSignUp()); // output false
console.log(curMode.isForgotPassword()); // output false
Create String const:
var ConstJs = require('constjs');
var Weekdays = ConstJs.const("Mon, Tue, Wed");
console.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'}
var today = Weekdays.Wed;
console.log(today); // output: 'Wed';
Create Bitmap:
var ConstJs = require('constjs');
var ColorFlags = ConstJs.bitmap("blue red");
console.log(ColorFlags.blue); // output false
var StyleFlags = ConstJs.bitmap(true, "rustic model minimalist");
console.log(StyleFlags.rustic); // output true
var CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});
console.log(CityFlags.Chengdu); //output true
console.log(CityFlags.Sydney); // output false
var DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});
console.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean
For more information please checkout
*
*https://www.npmjs.com/package/constjs
*or https://github.com/greenlaw110/constjs
Disclaim: I am the author if this tool.
A:
Declare a readonly named constatnt.
Variables declared via const cannot be re-declared or re-assigned.
Constants can be declared with uppercase or lowercase, but a common
convention is to use all-uppercase letters.
// const c;
// c = 9; //intialization and declearation at same place
const c = 9;
// const c = 9;// re-declare and initialization is not possible
console.log(c);//9
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1175"
}
|
Q: JavaScript data formatting/pretty printer I'm trying to find a way to "pretty print" a JavaScript data structure in a human-readable form for debugging.
I have a rather big and complicated data structure being stored in JS and I need to write some code to manipulate it. In order to work out what I'm doing and where I'm going wrong, what I really need is to be able to see the data structure in its entirety, and update it whenever I make changes through the UI.
All of this stuff I can handle myself, apart from finding a nice way to dump a JavaScript data structure to a human-readable string. JSON would do, but it really needs to be nicely formatted and indented. I'd usually use Firebug's excellent DOM dumping stuff for this, but I really need to be able to see the entire structure at once, which doesn't seem to be possible in Firebug.
A: For those looking for an awesome way to see your object, check prettyPrint.js
Creates a table with configurable view options to be printed somewhere on your doc. Better to look than in the console.
var tbl = prettyPrint( myObject, { /* options such as maxDepth, etc. */ });
document.body.appendChild(tbl);
A: I'm programming in Rhino and I wasn't satisfied with any of the answers that were posted here. So I've written my own pretty printer:
function pp(object, depth, embedded) {
typeof(depth) == "number" || (depth = 0)
typeof(embedded) == "boolean" || (embedded = false)
var newline = false
var spacer = function(depth) { var spaces = ""; for (var i=0;i<depth;i++) { spaces += " "}; return spaces }
var pretty = ""
if ( typeof(object) == "undefined" ) { pretty += "undefined" }
else if ( typeof(object) == "boolean" ||
typeof(object) == "number" ) { pretty += object.toString() }
else if ( typeof(object) == "string" ) { pretty += "\"" + object + "\"" }
else if ( object == null) { pretty += "null" }
else if ( object instanceof(Array) ) {
if ( object.length > 0 ) {
if (embedded) { newline = true }
var content = ""
for each (var item in object) { content += pp(item, depth+1) + ",\n" + spacer(depth+1) }
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "[ " + content + "\n" + spacer(depth) + "]"
} else { pretty += "[]" }
}
else if (typeof(object) == "object") {
if ( Object.keys(object).length > 0 ){
if (embedded) { newline = true }
var content = ""
for (var key in object) {
content += spacer(depth + 1) + key.toString() + ": " + pp(object[key], depth+2, true) + ",\n"
}
content = content.replace(/,\n\s*$/, "").replace(/^\s*/,"")
pretty += "{ " + content + "\n" + spacer(depth) + "}"
} else { pretty += "{}"}
}
else { pretty += object.toString() }
return ((newline ? "\n" + spacer(depth) : "") + pretty)
}
The output looks like this:
js> pp({foo:"bar", baz: 1})
{ foo: "bar",
baz: 1
}
js> var taco
js> pp({foo:"bar", baz: [1,"taco",{"blarg": "moo", "mine": "craft"}, null, taco, {}], bleep: {a:null, b:taco, c: []}})
{ foo: "bar",
baz:
[ 1,
"taco",
{ blarg: "moo",
mine: "craft"
},
null,
undefined,
{}
],
bleep:
{ a: null,
b: undefined,
c: []
}
}
I've also posted it as a Gist here for whatever future changes may be required.
A: I wrote a function to dump a JS object in a readable form, although the output isn't indented, but it shouldn't be too hard to add that: I made this function from one I made for Lua (which is much more complex) which handled this indentation issue.
Here is the "simple" version:
function DumpObject(obj)
{
var od = new Object;
var result = "";
var len = 0;
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
value = "[ " + value + " ]";
}
else
{
var ood = DumpObject(value);
value = "{ " + ood.dump + " }";
}
}
result += "'" + property + "' : " + value + ", ";
len++;
}
od.dump = result.replace(/, $/, "");
od.len = len;
return od;
}
I will look at improving it a bit.
Note 1: To use it, do od = DumpObject(something) and use od.dump. Convoluted because I wanted the len value too (number of items) for another purpose. It is trivial to make the function return only the string.
Note 2: it doesn't handle loops in references.
EDIT
I made the indented version.
function DumpObjectIndented(obj, indent)
{
var result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
value = "'" + value + "'";
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
// Recursive dump
// (replace " " by "\t" or something else if you prefer)
var od = DumpObjectIndented(value, indent + " ");
// If you like { on the same line as the key
//value = "{\n" + od + "\n" + indent + "}";
// If you prefer { and } to be aligned
value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + ",\n";
}
return result.replace(/,\n$/, "");
}
Choose your indentation on the line with the recursive call, and you brace style by switching the commented line after this one.
... I see you whipped up your own version, which is good. Visitors will have a choice.
A: jsDump
jsDump.parse([
window,
document,
{ a : 5, '1' : 'foo' },
/^[ab]+$/g,
new RegExp('x(.*?)z','ig'),
alert,
function fn( x, y, z ){
return x + y;
},
true,
undefined,
null,
new Date(),
document.body,
document.getElementById('links')
])
becomes
[
[Window],
[Document],
{
"1": "foo",
"a": 5
},
/^[ab]+$/g,
/x(.*?)z/gi,
function alert( a ){
[code]
},
function fn( a, b, c ){
[code]
},
true,
undefined,
null,
"Fri Feb 19 2010 00:49:45 GMT+0300 (MSK)",
<body id="body" class="node"></body>,
<div id="links">
]
QUnit (Unit-testing framework used by jQuery) using slightly patched version of jsDump.
JSON.stringify() is not best choice on some cases.
JSON.stringify({f:function(){}}) // "{}"
JSON.stringify(document.body) // TypeError: Converting circular structure to JSON
A: Use Crockford's JSON.stringify like this:
var myArray = ['e', {pluribus: 'unum'}];
var text = JSON.stringify(myArray, null, '\t'); //you can specify a number instead of '\t' and that many spaces will be used for indentation...
Variable text would look like this:
[
"e",
{
"pluribus": "unum"
}
]
By the way, this requires nothing more than that JS file - it will work with any library, etc.
A: You can use the following
<pre id="dump"></pre>
<script>
var dump = JSON.stringify(sampleJsonObject, null, 4);
$('#dump').html(dump)
</script>
A: Taking PhiLho's lead (thanks very much :)), I ended up writing my own as I couldn't quite get his to do what I wanted. It's pretty rough and ready, but it does the job I need. Thank you all for the excellent suggestions.
It's not brilliant code, I know, but for what it's worth, here it is. Someone might find it useful:
// Usage: dump(object)
function dump(object, pad){
var indent = '\t'
if (!pad) pad = ''
var out = ''
if (object.constructor == Array){
out += '[\n'
for (var i=0; i<object.length; i++){
out += pad + indent + dump(object[i], pad + indent) + '\n'
}
out += pad + ']'
}else if (object.constructor == Object){
out += '{\n'
for (var i in object){
out += pad + indent + i + ': ' + dump(object[i], pad + indent) + '\n'
}
out += pad + '}'
}else{
out += object
}
return out
}
A: For anyone checking this question out in 2021 or post-2021
Check out this Other StackOverflow Answer by hassan
TLDR:
JSON.stringify(data,null,2)
here the third parameter is the tab/spaces
A: In Firebug, if you just console.debug ("%o", my_object) you can click on it in the console and enter an interactive object explorer. It shows the entire object, and lets you expand nested objects.
A: For Node.js, use:
util.inspect(object, [options]);
API Documentation
A: This is really just a comment on Jason Bunting's "Use Crockford's JSON.stringify", but I wasn't able to add a comment to that answer.
As noted in the comments, JSON.stringify doesn't play well with the Prototype (www.prototypejs.org) library. However, it is fairly easy to make them play well together by temporarily removing the Array.prototype.toJSON method that prototype adds, run Crockford's stringify(), then put it back like this:
var temp = Array.prototype.toJSON;
delete Array.prototype.toJSON;
$('result').value += JSON.stringify(profile_base, null, 2);
Array.prototype.toJSON = temp;
A: I thought J. Buntings response on using JSON.stringify was good as well. A an aside, you can use JSON.stringify via YUIs JSON object if you happen to be using YUI. In my case I needed to dump to HTML so it was easier to just tweak/cut/paste PhiLho response.
function dumpObject(obj, indent)
{
var CR = "<br />", SPC = " ", result = "";
if (indent == null) indent = "";
for (var property in obj)
{
var value = obj[property];
if (typeof value == 'string')
{
value = "'" + value + "'";
}
else if (typeof value == 'object')
{
if (value instanceof Array)
{
// Just let JS convert the Array to a string!
value = "[ " + value + " ]";
}
else
{
var od = dumpObject(value, indent + SPC);
value = CR + indent + "{" + CR + od + CR + indent + "}";
}
}
result += indent + "'" + property + "' : " + value + "," + CR;
}
return result;
}
A: Lots of people writing code in this thread, with many comments about various gotchas. I liked this solution because it seemed complete and was a single file with no dependencies.
browser
nodejs
It worked "out of the box" and has both node and browser versions (presumably just different wrappers but I didn't dig to confirm).
The library also supports pretty printing XML, SQL and CSS, but I haven't tried those features.
A: A simple one for printing the elements as strings:
var s = "";
var len = array.length;
var lenMinus1 = len - 1
for (var i = 0; i < len; i++) {
s += array[i];
if(i < lenMinus1) {
s += ", ";
}
}
alert(s);
A: My NeatJSON library has both Ruby and JavaScript versions. It is freely available under a (permissive) MIT License. You can view an online demo/converter at:
http://phrogz.net/JS/neatjson/neatjson.html
Some features (all optional):
*
*Wrap to a specific width; if an object or array can fit on the line, it is kept on one line.
*Align the colons for all keys in an object.
*Sort the keys to an object alphabetically.
*Format floating point numbers to a specific number of decimals.
*When wrapping, use a 'short' version that puts the open/close brackets for arrays and objects on the same line as the first/last value.
*Control the whitespace for arrays and objects in a granular manner (inside brackets, before/after colons and commas).
*Works in the web browser and as a Node.js module.
A: flexjson includes a prettyPrint() function that might give you what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "129"
}
|
Q: Call a certain method before each webservice call Here's the situation. I have a webservice (C# 2.0), which consists of (mainly) a class inheriting from System.Web.Services.WebService. It contains a few methods, which all need to call a method that checks if they're authorized or not.
Basically something like this (pardon the architecture, this is purely as an example):
public class ProductService : WebService
{
public AuthHeader AuthenticationHeader;
[WebMethod(Description="Returns true")]
[SoapHeader("AuthenticationHeader")]
public bool MethodWhichReturnsTrue()
{
if(Validate(AuthenticationHeader))
{
throw new SecurityException("Access Denied");
}
return true;
}
[WebMethod(Description="Returns false")]
[SoapHeader("AuthenticationHeader")]
public bool MethodWhichReturnsFalse()
{
if(Validate(AuthenticationHeader))
{
throw new SecurityException("Access Denied");
}
return false;
}
private bool Validate(AuthHeader authHeader)
{
return authHeader.Username == "gooduser" && authHeader.Password == "goodpassword";
}
}
As you can see, the method Validate has to be called in each method. I'm looking for a way to be able to call that method, while still being able to access the soap headers in a sane way. I've looked at the events in the global.asax, but I don't think I can access the headers in that class... Can I?
A: You can implement the so-called SOAP extension by deriving from SoapExtension base class. That way you will be able to inspect an incoming SOAP message and perform validate logic before a particular web method is called.
A: I'd take a look at adding a security aspect to the methods you're looking to secure. Take a look at PostSharp, and in particular the OnMethodBoundryAspect type, and OnEntry method.
A: Here is what you need to do to get this to work correctly.
It is possible to create your own custom SoapHeader:
public class ServiceAuthHeader : SoapHeader
{
public string SiteKey;
public string Password;
public ServiceAuthHeader() {}
}
Then you need a SoapExtensionAttribute:
public class AuthenticationSoapExtensionAttribute : SoapExtensionAttribute
{
private int priority;
public AuthenticationSoapExtensionAttribute()
{
}
public override Type ExtensionType
{
get
{
return typeof(AuthenticationSoapExtension);
}
}
public override int Priority
{
get
{
return priority;
}
set
{
priority = value;
}
}
}
And a custom SoapExtension:
public class AuthenticationSoapExtension : SoapExtension
{
private ServiceAuthHeader authHeader;
public AuthenticationSoapExtension()
{
}
public override object GetInitializer(Type serviceType)
{
return null;
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override void ProcessMessage(SoapMessage message)
{
if (message.Stage == SoapMessageStage.AfterDeserialize)
{
foreach (SoapHeader header in message.Headers)
{
if (header is ServiceAuthHeader)
{
authHeader = (ServiceAuthHeader)header;
if(authHeader.Password == TheCorrectUserPassword)
{
return; //confirmed
}
}
}
throw new SoapException("Unauthorized", SoapException.ClientFaultCode);
}
}
}
Then, in your web service add the following header to your method:
public ServiceAuthHeader AuthenticationSoapHeader;
[WebMethod]
[SoapHeader("AuthenticationSoapHeader")]
[AuthenticationSoapExtension]
public string GetSomeStuffFromTheCloud(string IdOfWhatYouWant)
{
return WhatYouWant;
}
When you consume this service, you must instantiate the custom header with the correct values and attach it to the request:
private ServiceAuthHeader header;
private PublicService ps;
header = new ServiceAuthHeader();
header.SiteKey = "Thekey";
header.Password = "Thepassword";
ps.ServiceAuthHeaderValue = header;
string WhatYouWant = ps.GetSomeStuffFromTheCloud(SomeId);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Auto-organize Visual Studio Tabs? Is there any setting in Visual Studio 2008 to group/organize tabs? For example, I'd prefer to have all code-behind files open in a tab next to its .aspx page if that page is open and vice versa. Dragging tabs around really kills my productivity.
A: Jonathan,
Tabs Studio (developed by me) add-in can automatically group .aspx and .aspx.cs windows in one tab.
A: Check ot this link - it explains how to make the active tab jump to the left-most position, thereby effectively keeping the most used tabs from 'falling off': window tab management in Visual Studio
A: There is no setting for this, but take a look at the documentation for writing visual studio add-ins. This would be a pretty simple one to set up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Do UTF-8, UTF-16, and UTF-32 differ in the number of characters they can store? Okay. I know this looks like the typical "Why didn't he just Google it or go to www.unicode.org and look it up?" question, but for such a simple question the answer still eludes me after checking both sources.
I am pretty sure that all three of these encoding systems support all of the Unicode characters, but I need to confirm it before I make that claim in a presentation.
Bonus question: Do these encodings differ in the number of characters they can be extended to support?
A: There is no Unicode character that can be stored in one encoding but not another. This is simply because the valid Unicode characters have been restricted to what can be stored in UTF-16 (which has the smallest capacity of the three encodings). In other words, UTF-8 and and UTF-32 could be used to represent a wider range of characters than UTF-16, but they aren't. Read on for more details.
UTF-8
UTF-8 is a variable-length code. Some characters require 1 byte, some require 2, some 3 and some 4. The bytes for each character are simply written one after another as a continuous stream of bytes.
While some UTF-8 characters can be 4 bytes long, UTF-8 cannot encode 2^32 characters. It's not even close. I'll try to explain the reasons for this.
The software that reads a UTF-8 stream just gets a sequence of bytes - how is it supposed to decide whether the next 4 bytes is a single 4-byte character, or two 2-byte characters, or four 1-byte characters (or some other combination)? Basically this is done by deciding that certain 1-byte sequences aren't valid characters, and certain 2-byte sequences aren't valid characters, and so on. When these invalid sequences appear, it is assumed that they form part of a longer sequence.
You've seen a rather different example of this, I'm sure: it's called escaping. In many programming languages it is decided that the \ character in a string's source code doesn't translate to any valid character in the string's "compiled" form. When a \ is found in the source, it is assumed to be part of a longer sequence, like \n or \xFF. Note that \x is an invalid 2-character sequence, and \xF is an invalid 3-character sequence, but \xFF is a valid 4-character sequence.
Basically, there's a trade-off between having many characters and having shorter characters. If you want 2^32 characters, they need to be on average 4 bytes long. If you want all your characters to be 2 bytes or less, then you can't have more than 2^16 characters. UTF-8 gives a reasonable compromise: all ASCII characters (ASCII 0 to 127) are given 1-byte representations, which is great for compatibility, but many more characters are allowed.
Like most variable-length encodings, including the kinds of escape sequences shown above, UTF-8 is an instantaneous code. This means that, the decoder just reads byte by byte and as soon as it reaches the last byte of a character, it knows what the character is (and it knows that it isn't the beginning of a longer character).
For instance, the character 'A' is represented using the byte 65, and there are no two/three/four-byte characters whose first byte is 65. Otherwise the decoder wouldn't be able to tell those characters apart from an 'A' followed by something else.
But UTF-8 is restricted even further. It ensures that the encoding of a shorter character never appears anywhere within the encoding of a longer character. For instance, none of the bytes in a 4-byte character can be 65.
Since UTF-8 has 128 different 1-byte characters (whose byte values are 0-127), all 2, 3 and 4-byte characters must be composed solely of bytes in the range 128-256. That's a big restriction. However, it allows byte-oriented string functions to work with little or no modification. For instance, C's strstr() function always works as expected if its inputs are valid UTF-8 strings.
UTF-16
UTF-16 is also a variable-length code; its characters consume either 2 or 4 bytes. 2-byte values in the range 0xD800-0xDFFF are reserved for constructing 4-byte characters, and all 4-byte characters consist of two bytes in the range 0xD800-0xDBFF followed by 2 bytes in the range 0xDC00-0xDFFF. For this reason, Unicode does not assign any characters in the range U+D800-U+DFFF.
UTF-32
UTF-32 is a fixed-length code, with each character being 4 bytes long. While this allows the encoding of 2^32 different characters, only values between 0 and 0x10FFFF are allowed in this scheme.
Capacity comparison:
*
*UTF-8: 2,097,152 (actually 2,166,912 but due to design details some of them map to the same thing)
*UTF-16: 1,112,064
*UTF-32: 4,294,967,296 (but restricted to the first 1,114,112)
The most restricted is therefore UTF-16! The formal Unicode definition has limited the Unicode characters to those that can be encoded with UTF-16 (i.e. the range U+0000 to U+10FFFF excluding U+D800 to U+DFFF). UTF-8 and UTF-32 support all of these characters.
The UTF-8 system is in fact "artificially" limited to 4 bytes. It can be extended to 8 bytes without violating the restrictions I outlined earlier, and this would yield a capacity of 2^42. The original UTF-8 specification in fact allowed up to 6 bytes, which gives a capacity of 2^31. But RFC 3629 limited it to 4 bytes, since that is how much is needed to cover all of what UTF-16 does.
There are other (mainly historical) Unicode encoding schemes, notably UCS-2 (which is only capable of encoding U+0000 to U+FFFF).
A: UTF-8, UTF-16, and UTF-32 all support the full set of unicode code points. There are no characters that are supported by one but not another.
As for the bonus question "Do these encodings differ in the number of characters they can be extended to support?" Yes and no. The way UTF-8 and UTF-16 are encoded limits the total number of code points they can support to less than 2^32. However, the Unicode Consortium will not add code points to UTF-32 that cannot be represented in UTF-8 or UTF-16. Doing so would violate the spirit of the encoding standards, and make it impossible to guarantee a one-to-one mapping from UTF-32 to UTF-8 (or UTF-16).
A: I personally always check Joel's post about unicode, encodings and character sets when in doubt.
A: No, they're simply different encoding methods. They all support encoding the same set of characters.
UTF-8 uses anywhere from one to four bytes per character depending on what character you're encoding. Characters within the ASCII range take only one byte while very unusual characters take four.
UTF-32 uses four bytes per character regardless of what character it is, so it will always use more space than UTF-8 to encode the same string. The only advantage is that you can calculate the number of characters in a UTF-32 string by only counting bytes.
UTF-16 uses two bytes for most charactes, four bytes for unusual ones.
http://en.wikipedia.org/wiki/Comparison_of_Unicode_encodings
A: All of the UTF-8/16/32 encodings can map all Unicode characters. See Wikipedia's Comparison of Unicode Encodings.
This IBM article Encode your XML documents in UTF-8 is very helpful, and indicates if you have the choice, it's better to choose UTF-8. Mainly the reasons are wide tool support, and UTF-8 can usually pass through systems that are unaware of unicode.
From the section What the specs say in the IBM article:
Both the W3C and the IETF have
recently become more adamant about
choosing UTF-8 first, last, and
sometimes only. The W3C Character
Model for the World Wide Web 1.0:
Fundamentals states, "When a unique
character encoding is required, the
character encoding MUST be UTF-8,
UTF-16 or UTF-32. US-ASCII is
upwards-compatible with UTF-8 (an
US-ASCII string is also a UTF-8
string, see [RFC 3629]), and UTF-8 is
therefore appropriate if compatibility
with US-ASCII is desired." In
practice, compatibility with US-ASCII
is so useful it's almost a
requirement. The W3C wisely explains,
"In other situations, such as for
APIs, UTF-16 or UTF-32 may be more
appropriate. Possible reasons for
choosing one of these include
efficiency of internal processing and
interoperability with other
processes."
A: As everyone has said, UTF-8, UTF-16, and UTF-32 can all encode all of the Unicode code points. However, the UCS-2 (sometimes mistakenly referred to as UCS-16) variant can't, and this is the one that you find e.g. in Windows XP/Vista.
See Wikipedia for more information.
Edit: I am wrong about Windows, NT was the only one to support UCS-2. However, many Windows applications will assume a single word per code point as in UCS-2, so you are likely to find bugs. See another Wikipedia article. (Thanks JasonTrue)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Q: Should I store all projects in one repository or multiple? I am currently using TortoiseSVN to manage a couple of the projects that I have on the go at the moment. When I first moved everything into source control I wasn't really sure how everything should be laid out so I ended up putting each project into its own repository.
I was wondering would it be a good idea for me just to move them all into one big repository and have them split into project folders? What does everyone else do?
At the moment none of them share common code but they may in the future. Would it make it easier to manage if they where all together.
Thanks.
A: I would store them in the same repository. It's kind of neater. Plus why would it matter for continuous integration and such - you can always pull a specific folder from the repository.
It's also easier to administer - accounts to one repository, access logs of one repository etc.
A: My rule of thumb is to consolidate things that are delivered together. In other words, if you might deliver project X and project Y separately, then put them in separate repos.
Yes, sometimes this means you have a huge repo for a project that contains a huge number of components, but people can operate on sub-trees of a repo and this forces them to think of the "whole project" when they commit changes to the repo.
A: I would absolutely keep each project in its own repository, separate from all others. This will give each project its own history of commits. Rollbacks on one project will not affect other projects.
A: Personally I prefer each project in it's own repository
A: Depends to an extent what you mean by "project".
I have a general local repository containing random bits of stuff that I write (including my website, since it's small). A single-user local SVN repository is not going to suffer noticeable performance issues until you've spent a lot of years typing. By which time SVN will be faster anyway. So I've yet to regret having thrown everything in one repository, even though some of the stuff in there is completely unrelated other than that I wrote it all.
If a "project" means "an assignment from class", or "the scripts I use to drive my TiVo", or "my progress in learning a new language", then creating a repos per project seems a bit unnecessary to me. Then again, it doesn't cost anything either. So I guess I'd say don't change what you're doing. Unless you really want the experience of re-organising repositories, in which case do change what you're doing :-)
However, if by "project" you mean a 'real' software project, with public access to the repository, then I think separate repos per project is what makes sense: partly because it divides things cleanly and each project scales independently, but also because it's what people will expect to see.
Sharing code between separate repositories is less of an issue than you might think, since svn has the rather lovely "svn:externals" feature. This lets you point a directory of your repository at a directory in another repository, and check that stuff out automatically along with your stuff. See, as always, the SVN book for details.
A: If you work with a lot of other people you might consider whether everyone needs the same level of access to every project. I think it is easier to give access rights per person if you put each project in a separate repository. ~~~
A: If you're going with a separate repository for each project, you might use the External tag to refer to other repositories -thus share code.
A: If your projects are independent, it's fine to keep them in separate repositories. If they share components, then put them together.
A: As long as each project has /trunk /tags and /branches you're good. Proper continuous integration is the criterion here.
A: Yes, put everything in source control.
If you're using SVN, keep projects in their own repository - svn is slow, and gets slower.
A: For Subversion, I'd suggest putting everything in the same repository; the administrative overhead of setting up a new repository is too high to make it a no-brainer, so you're more likely not to version something and regret it later. Subversion provides plenty of fine-grained access controls if you need to restrict access to a portion of your repository.
As I begin to migrate my projects to Mercurial, however, I've switched to creating a repository per project, because it just takes a "hg init" to create a new one in place, and I can use the hg forest extension to easily perform operations on nested repositories. Subversion has svn:externals, which are somewhat similar, but require more administrative overhead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: How does AOP apply to Drupal? How does AOP (Aspect Oriented Programming) work in Drupal?
I have learned about AOP in terms of using it for logging and security, but how does it apply to Drupal?
A: Drupal mimics AOP paradigms through hooks, which basically allow developers to weave in bits of code during the flow of execution. You can take a look at the hooks a developer can implement on the list of Drupal hooks shown in the Drupal documentation site, which just lists the hooks invoked from Drupal core and its modules.
As a quick example, if I were developing a new node based module (nodes being the basic data form in Drupal), I have instant access to comments and taxonomy with no additional work on my part. the comment and taxonomy modules have the ability to hook into nodes, and provide that added functionality. So in that sense, I don't have to account for such features in my program but I am able to take advantage of that flexibility.
A: Drupal is a "multi-paradigm" framework, and only certain bits of it implement "a kind of" AOP:
*
*Drupal 7's render() function, for example, converts a set of nested arrays into output HTML by selecting appropriate templates based on basic precedence rules: in this way, Drupal is behaving a lot like an XSLT transform engine, where your theme's template files taken together constitute an input .xsl file and the input array nest is the initial .xml file. This means that there's something elegantly functional to the way that themeing works.
*Also, the D7 database abstraction layer is close to "straight" object orientation, although as Larry (see later) notes, there is a small amount of quasi-AOP in this OO layer.
Drupal's AOP paradigm might be better visualized as event-driven, and it all happens through Drupal's concept of hooks. For example, when you do the following:
*
*Write a module called mymodule
*In mymodule.module, create a mymodule_init() function
*Install this module in Drupal
What you are declaring is, in pseudo-code:
subscribe mymodule to "hook events" of type init
When Drupal's core then runs module_invoke_all('init'), Drupal is saying:
notify all subscribers to "hook events" of type init that this has occurred
by passing any relevant arguments to them
and letting them run the code they define in their hook_init()
So while PHP is still a procedural language—and your mymodule_init() could do all sorts of crazy, un-encapsulated things if you really wanted—Drupal is still in charge. Drupal in a sense decides whether or not to call your code in the first place.
In this way, Drupal is able to turn its own execution phases into quasi-AOP, by defining joint points (the module_invoke*() functions) and letting you write your own pointcuts (your mymodule_*() function, whose naming convention must match Drupal's hook name.
For more background on this, and the multi-paradigmatic nature of Drupal especially, Programming language trade-offs, by Larry Garfield.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why is Lisp used for AI? I've been learning Lisp to expand my horizons because I have heard that it is used in AI programming. After doing some exploring, I have yet to find AI examples or anything in the language that would make it more inclined towards it.
Was Lisp used in the past because it was available, or is there something that I'm just missing?
A: I think it's wrong to think about this in terms of AI only. Things like the AI-winter and commercial effects on common lisp are distracting if you're asking why it was used for AI, not why it's not often used now ...
Anyway, I think it's because most of the AI code was essentially research code. Lisp is a great language for exploratory programming, for implementing difficult algorithms, for self-modifying and often modified code. In other words, for research code.
I use lisp today for some of my research code (mathematics, signal processing) because it's more flexible and powerful than most languages while still generating more efficient code than most languages. I can typically get performance within a factor of +/- 2 of say c++ speed, but I can implement things much faster, and deal with complexity that would take me far more time than I have if I used c++, java, c#.
That's wandering off topic though. I think AI code was primarily written in common lisp for a while because it is a powerful approach to research code. It still is; but as `AI' algorithms became better understood and explored, parts of them were much easier to teach and use, so they showed up in flavor-of-the-year languages in undergrad courses. From there, it becomes an issue of what people already know, what libraries are available, and what works well for large groups.
A: Lisp is used for AI because it supports the implementation of software that computes with symbols very well. Symbols, symbolic expressions and computing with those is at the core of Lisp.
Typical AI areas for computing with symbols were/are: computer algebra, theorem proving, planning systems, diagnosis, rewrite systems, knowledge representation and reasoning, logic languages, machine translation, expert systems, and more.
It is then no surprise that many famous AI applications in these domains were written in Lisp:
*
*Macsyma as the first large computer algebra system.
*ACL2 as a widely used theorem prover, for example used by AMD.
*DART as the logistics planner used during the first Gulf war by the US military. This Lisp application alone is said to have paid back for all US investments in AI research at that time.
*SPIKE, the planning and scheduling application for the Hubble Space Telescope. Also used by several other large telescopes.
*CYC, one of the largest software systems written. Representation and reasoning in the domain of human common sense knowledge.
*METAL, one of the first commercially used natural language translation systems.
*American Express' Authorizer's Assistant, which checks credit card transactions.
There are thousands of applications in these areas that are written in Lisp. Very common for those is that they need special capabilities in the area of symbolic processing. One implements special languages that have special interpreters/compilers in these domains on top of Lisp. Lisp allows one to create representations for symbolic data and programs and can implement all kinds of machinery to manipulate these expressions (math formulas, logic formulas, plans, ...).
(Note that lots of other general purpose programming languages are used in AI, too. I have tried to answer why especially Lisp is used in AI.)
A: I'd guess that a big reason was the flexibility of lists as a basic data structure.
at the time, being able to turn them into all kind of composite objects, and new things as message passings and polimorphism, made it the language of choice; not specifically for AI, but for big, complex, tasks. especially when they were experimenting with concepts.
A: I think you're right: Lisp was a handy tool for hacking things up. This is because it didn't distinguish much between program and data. This allowed hackers to manipulate functions very easily, just like data.
But lisp is quite difficult for humans to read, with its braces and non-distinction between data and program. Today, I won't use lisp for any production AI code (or perhaps even prototyping) but would much prefer python for scripting.
Another thing to consider is the existing libraries/tools in/related to the language. I am not in a position to compare lisp libraries with python libraries, but I guess libraries and open source matter a lot more now than before.
This answer was inspired by the following comparison between lisp and python: http://amitp.blogspot.com/2007/04/lisp-vs-python-syntax.html
A: I remember hearing that, being a functional language, Lisp was a very good choice for implementing recursive algorithms. Being able to track down a tree and work your way back is essential when considering the decision making processes (traversal) and end result (leaf node).
This was told to me during an AI course at university where we studied Lisp.
A: A more cynical answer might be "because it lost a political AI war between Japan and the USA in the 1980s". There is an fun blog post that speculates about the impact of the Fifth-Generation Computer System demise on the Prolog.
A: One reason is that it allows you to extend the language with constructs specific for your domain, making it, effectively, a domain specific language. This technique is incredibly powerful as it allows you to reason about the problem you are solving, rather than about shuffling bits.
A: Lisp WAS used in AI until the end of the 1980s. In the 80s, though, Common Lisp was oversold to the business world as the "AI language"; the backlash forced most AI programmers to C++ for a few years. These days, prototypes usually are written in a younger dynamic language (Perl, Python, Ruby, etc) and implementations of successful research is usually in C or C++ (sometimes Java).
If you're curious about the 70's...well, I wasn't there. But I think Lisp was successful in AI research for three reasons (in order of importance):
*
*Lisp is an excellent prototyping tool. It was the best for a very long time. Lisp is still great at tackling a problem you don't know how to solve yet. That description characterises AI perfectly.
*Lisp supports symbolic programming well. Old AI was also symbolic. It was also unique in this regard for a long time.
*Lisp is very powerful. The code/data distinction is weaker so it feels more extensible than other languages because your functions and macros look like the built-in stuff.
I do not have Peter Norvig's old AI book, but it is supposed to be a good way to learn to program AI algorithms in Lisp.
Disclaimer: I am a grad student in computational linguistics. I know the subfield of natural language processing a lot better than the other fields. Maybe Lisp is used more in other subfields.
A: My guess has always been that, being a functional language, it doesn't differentiate between code and data. Everything, including function definitions and function calls can be treated as lists and modified like any other piece of data.
So self-inspecting, self-modifying code could be written easily.
A: One possible answer is that AI is a collection of very hard problems, and Lisp is a good language for solving hard problems, not just AI.
As to why that is: macros, generic functions, and rich introspection allow for concise code and easy introduction of domain abstractions — it's a language that you can make more powerful. For a lot of problems that's unnecessary, and it comes with its own costs, but for other problems that power is needed to make any headway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "196"
}
|
Q: Does a hash shrink in Perl as you delete elements? Does a hash shrink in Perl as you delete elements.
More specifically I had a perl program that I inherited that would parse a huge file ( 1 GB ) and load up a hash of hashes. it would do that same for another file and then do a comparison of different elements. The memory consumption was huge during this process and even though I added deleting hash elements has they were used the memory consumption seemed to be unaffected.
The script was extremely slow and such a memory hog. I know it was not well designed but any ideas about the hash memory usage?
A: In general, Perl cannot return memory to the operating system. It may be able to reuse memory internally, though, which could reduce the amount of memory needed by a program.
See perlfaq3: How can I free an array or hash so my program shrinks?
If the memory used by the hashes is excessive (i.e. > physical memory) you could tie them to a file on disk. This would greatly reduce your memory usage but be warned that accessing a structure on disk is much slower than accessing one in memory. (So is disk thrashing.)
A: If your hash is truly gigantic, a better strategy is to probably use an on-disk hash and let the OS worry about getting things into and out of memory. I'm particularly fond of Berkeley DB for storing big hashes on disk, and the Perl BerkeleyDB module provides a full-featured interface, including a tied API.
DBM::Deep can also be used as a drop-in hash replacement, but relies on its own format. This can be a pain if your structure needs to be read by other (non-Perl) systems.
A: Regarding the specific question: No, deleting hash keys does not reduce your program's memory consumption.
Regarding the more general case: The substantial majority of programs and languages will continue to hold on to memory which they have previously used, but are not currently using. This is because requesting the allocation of memory by the operating system is a relatively slow operation, so they keep it in case it's needed again later.
So, if you want to improve on this situation, you'll need to reduce the peak amount of memory required by your program, whether by revising your algorithms to not need access to as much data at once, by using on-disk storage (such as the aforementioned DBM::Deep), or by releasing space from unneeded variables back to perl (let them go out of scope or set them to undef) so that it can be reused.
A: If inputs in the second file are needed only once (as they are read), you could potentially cut the memory usage in half.
Depending on your algorithm, you might even be able to just hold both filehandles open and a small hash of not-used-yet values in memory. An example would be a merge or comparison of sorted data -- you only need to hold the current line from each file and compare it to each other as you go, skipping ahead until the cmp changes.
Another approach might be to make multiple passes, especially if you have one or more otherwise-idle cores in your machine. Open read pipes and have subprocesses feed you the data in manageable pre-organized chunks.
For more generic algorithms, you can only avoid paying for the memory size by trading it for the cost of disk speed.
In most cases, loading every data source into memory only wins on development time -- then you pay for it in footprint and/or speed when N gets large.
A: Workaround: fork a child process that allocates all that memory. Let it pass back some aggregate info when it's done doing its thing; when the forked process dies, its memory will go with it. A bit of a pain, but works for some cases. An example of a case where this helps would be if you are processing many files, each file one at a time, only a few of the files are big, and little intermediate state needs to be kept.
A: You might want to check out something like DBM::Deep. It does that tie-ing stuff that Michael mentioned so you don't have to think about it. Everything is stored on disk instead of in memory. It's just short of needing a fancier database server.
Also, if you want to track down the performance bottleneck, check out Devel::NYTProf, the new hotness in Perl profiling that came out of the New York Times.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: In .net, what's the best / safest way to add a "end of line" character to a text file? I assume there must be a system and language independent way to just stick the "current" EOL character into a text file, but my MSDN-fu seems to be weak today. Bonus points if there is a way to do this in a web application that will put the correct EOL character for the current client's machine's OS, not the web server's.
A: System.Environment.NewLine
A: For the bonus point:
*
*Check the user-agent of the client machine, for substrings such as Windows, or Linux
*The System.Environment.NewLine for Windows is 0x13, 0x10; in unix, it's generally 0x10 only;
*Choose the appropriate newline string, append it to the line, and off you go
A: Open the text file, seek to the end, and append Environment.NewLine.
A: You are looking for Environment.NewLine. This will only be for your current operating system however.
A: For server-side code I would go for TextWriter.WriteLine. Detecting the OS of the client's machine requires browser sniffing - check Request.Browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a source code formatter for Groovy? I use the commercial version of Jalopy for my Java projects but it doesn't work on Groovy files. IntelliJ has a serviceable formatter but I don't like requiring a particular IDE.
A: Try "BUSL"
2022-10-26 NOTE: HISTORIC. "BUSL" seems to be dead. Last archived webpage is from 2020.
I've found that BUSL works really well on Groovy files. It's standalone too, so you can use it from your text editor or whatever.
A: You can use npm-groovy-lint via command line with --format option :)
https://www.npmjs.com/package/npm-groovy-lint
A: spidasoftware/format extracts the groovy eclipse plugin and provides a command line interface to it.
Instructions:
git clone git@github.com:spidasoftware/format.git && \
cd format/bin && \
./format /path/to/groovy/file
caveat: this project is no longer maintained however still works as of the time of this post
A: the latest eclipse plugin will do some formatting and refactoring: http://groovy.codehaus.org/Eclipse+Plugin+Refactoring
A: Groovy support for Jalopy is coming later this year. There is a tiny sneak preview on YouTube showcasing the Eclipse plug-in:
http://www.youtube.com/watch?v=PNFUzvOZei0
A: Older groovyc had some formatter
2022-10-26 NOTE: HISTORIC. The formatter seems to have disappeared in newer versions. See comment.
Actually groovyc came with a builtin formatter (kind of). If you set the environment variable JAVA_OPTS to -Dantlr.ast and run groovyc test.groovy a file called test.groovy.pretty.groovy is generated.
But be aware: From what I found in the internet about this, this formatter is not configurable and strips comments!
A: Spotless also formats groovy. Seems to be impossible to run without gradle/maven though. :(
A: I have yet to find a good solution for this, and I really wish that there was one. Regarding @Gizmomogwai's tip, it doesn't exactly work as you'd think.
First of all, you need to export JAVA_OPTS=-Dantlr.ast:groovy. However, the file produced by groovyc is clearly not "pretty" in the sense that it is pretty to humans. The "pretty" output generates a file which will be parsed by the next stage of the compiler. Effectively, this means that it not only strips comments but also will add and alter newlines and whitespace. It is definitely not suitable for checking code formatting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: MFC "Warning: skipping non-radio button in group." When running an old MFC application in Visual Studio's debugger I've seen a lot of warnings in the Output window like the following:
Warning: skipping non-radio button in group.
I understand that in MFC you put radio buttons in groups to indicate which sets of radio buttons go together. If I remember correctly you do this by setting the "group" property of the first radio button to true, and then set the rest of the radio buttons "group" property to false.
I have three questions about this warning.
*
*How do you get rid of this warning? Do
you have to set the "group" property of all
non-radio button controls to true to
avoid this, or should you just set
it for the first control after the
last radio button?
*Is there an easy way to figure
out what controls or dialogs have this problem?
I could open each dialog and
fiddle with it until the warning
pops up. This application has a lot of
dialogs though, so it would be
nice if there was an easier way.
*What negative behavior can occur if
you don't fix this warning? In other
words, does this even matter?
A: The warning means that there's some control other than a radio button in the tab order between the first and last radio buttons in the group. A control with the WS_GROUP style set marks the start of a group.
To fix this, use the dialog editor to change the tab order and make sure that all the radio buttons are numbered sequentially. Another way to do this would be to open the .rc file in a text editor and change the order of the statements inside each dialog resource (the tab order is simply defined by the order in which the controls are listed).
I think you can safely ignore this warning, provided the radio button grouping is working correctly.
A: Between the responses here and some research in old forums I think I've figured out at least how to fix my problems. Here is what I've found out for my above questions.
*
*ChrisN and Smashery suggested that I reorder the tabs to make sure radio buttons are ordered sequentially, and this did fix some of the warnings.
Additionally, the first control in the tab order after the radio button group must have the WS_GROUP property set (or the group property set to true in the editor). This tells MFC that the radio button group has ended. Without it all remaining controls in the tab order until the next WS_GROUP will generate the warning. After doing both these things the warnings in these dialogs went away.
*This is still an open question, I didn't find a good way to locate these problems without opening each dialog and waiting for warnings.
If you know a dialog is creating this warning but you don't know what control is causing it, you can set a breakpoint in the DDX_Radio() function on the TRACE() call that generates the warning. This can make it easier to identify the specific control that is being complained about.
*I agree with ChrisN, I can't think of any reason for this warning other than to make you double check your tab order. Elsewhere online I can't find any other reference to a problem that this might cause.
A: Perhaps check your tab order (Format/Tab Order) - sounds like you have a normal pushbutton in the middle of a group of radio buttons. If indeed this is the problem, you can fix this by using the Format/Tab Order menu item, and then clicking on the controls in the correct order.
A: For point 2, which is why I guess you're keeping this unanswered, I can't picture anything simplier then doing a text search (*.rc) for all dialogs with radio buttons. For each hit, visually inspect the resource code for this issue and correct it. I'd do it by hand in the resource file's source vs. trying to play with the gui designer.
A: For what it's worth, I had 3 radio buttons in correct tab order (confirmed in .rc file with no problems after it) and still got warning.
Breakpoint in DDX_Radio showed that 2nd and 3rd radio buttons were being reported as non-radio!
Looked in resource.h and discovered 1st radio button using ID 1313 and other two using 1311 and 1312. Put them in desired tab order and renumbered the IDs to suit and problem solved.
Guess the GetWindow GW_HWNDNEXT is somehow linked in ID order not Tab order, even though radio group worked.
Note: still using Visual C++ v6
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Oracle load spikes couple hours after startup We use oracle as the back-end database for our product. I have been running series of stress tests on our system and I have started noticing that oracle is much faster right after the database was restarted. Over time (a couple hours or so) the database seems to get slower and slower and I will see the database machine under more stress.
Running the test right after an oracle restart, i will see a 1 min load average of 5 or so and average CPU around 10-15%. After a few hours, I see the load average at 13 and CPU at 40-70%. (This is red hat linux 2x Quad core xeon, Raid 10 10k rpm sas drives).
My first thought was wouldn't database transactions get faster because those queries are getting cached?
I can't seem to figure out the problem.
EDIT:
Turns out this was a problem on the connecting software side due to bad design. Every action on the system created a new insert, delete, and select. With all these unique queries being generated, what was cached was constantly changing. The spike I am talking about is when the query cache filled up.
A: What version of oracle are you running? Do you have statspack or AWR setup? if you do, check those to show you what the database is doing over time.
A: I've noticed that with Oracle 10g, Oracle schedules a job to automatically compute statistics each day. You might want to look at your active sessions when the database is busy and see if a background session is busy calculating statistics on your tables.
A: Are you sure the stress test is releasing the sessions that it uses? The accumulation of sessions, then subsequent time out of those sessions could produce this kind of behavior.
Moved this query from the comments to the body of my answer per request...
select
username,
osuser,
lockwait,
status,
sql_text
from
v$session,
v$sqltext
where
username is not null
and
username not in ('SYSMAN','DBSNMP')
and
hash_value = sql_hash_value
order by
username,
hash_value,
piece;
A: It could be a problem with the database SGA swapping to disk. Check the size of the SGA and the PGA, compared to the RAM size.
You need to provide more information about the version of Oracle and Red Hat (for example,
I have experienced performance problems with Oracle 9i and Red Hat Enterprise Linux 3.x, with RAM sizes of 4 Gbytes or greater, that have disappeared when upgrading to Red Hat 4.x and Oracle 10g)
A: So after you do the reboot and the performance improves again, do you drop the data or do you keep it? You need to run statspack/AWR/ADDM/OEM to get more information about what's happening.
As you haven't posted any detailed diagnostic info I take it you need to start learning the ABCs first. See Oracle 10.2 Performance Tuning Guide
A: Add to the list of information needed the following:
Are you using archive logs?
How many redo log groups do you have? How many redo logs are in each group?
How big are the redo logs?
How are you restarting Oracle? Are you just doing a shutdown immediate followed by a startup? Are you rebooting the server?
If your log files are too small you might be getting into a state where you're waiting for the redo logs to be written to the archive logs before being able to continue, you can help remedy this by increasing the size of the redo logs.
Shutting down and restarting oracle would result in the redo logs all being written to the archive logs and being fresh and ready to go after you start back up. Then as they fill with redo information you hit a bottleneck when it comes time to archive them.
An AWR report would really be the most useful thing if you're running Oracle 10g. If you're running 9i then statspack equvalent.
Running a AWR Report
Login to sqlplus
sqlplus <sys or system user>/<password>@<SID>
Create a 'before' statistics snapshot
SQL> execute dbms_workload_repository.create_snapshot
Run your specific performance/load tests
Create an 'after' statistics snapshot
SQL> execute dbms_workload_repository.create_snapshot
Create a workload repository report
SQL> start awrrpt
Using the AWR report you should be able to determine where your bottleneck is.
A: A perfect example for a RAC Analyst like me who has downed RAC multiple times but never knew what made it down. Now, I am using the suggested method. Really, Oracle has many hidden functionality or I am less trained hheee or i need to explore more on these
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How many threads should I use in my Java program? I recently inherited a small Java program that takes information from a large database, does some processing and produces a detailed image regarding the information. The original author wrote the code using a single thread, then later modified it to allow it to use multiple threads.
In the code he defines a constant;
// number of threads
public static final int THREADS = Runtime.getRuntime().availableProcessors();
Which then sets the number of threads that are used to create the image.
I understand his reasoning that the number of threads cannot be greater than the number of available processors, so set it the the amount to get the full potential out of the processor(s). Is this correct? or is there a better way to utilize the full potential of the processor(s)?
EDIT: To give some more clarification, The specific algorithm that is being threaded scales to the resolution of the picture being created, (1 thread per pixel). That is obviously not the best solution though. The work that this algorithm does is what takes all the time, and is wholly mathematical operations, there are no locks or other factors that will cause any given thread to sleep. I just want to maximize the programs CPU utilization to decrease the time to completion.
A: The number that your application needs; no more, and no less.
Obviously, if you're writing an application which contains some parallelisable algorithm, then you can probably start benchmarking to find a good balance in the number of threads, but bear in mind that hundreds of threads won't speed up any operation.
If your algorithm can't be parallelised, then no number of additional threads is going to help.
A: Yes, that's a perfectly reasonable approach. One thread per processor/core will maximize processing power and minimize context switching. I'd probably leave that as-is unless I found a problem via benchmarking/profiling.
One thing to note is that the JVM does not guarantee availableProcessors() will be constant, so technically, you should check it immediately before spawning your threads. I doubt that this value is likely to change at runtime on typical computers, though.
P.S. As others have pointed out, if your process is not CPU-bound, this approach is unlikely to be optimal. Since you say these threads are being used to generate images, though, I assume you are CPU bound.
A: Threads are fine, but as others have noted, you have to be highly aware of your bottlenecks. Your algorithm sounds like it would be susceptible to cache contention between multiple CPUs - this is particularly nasty because it has the potential to hit the performance of all of your threads (normally you think of using multiple threads to continue processing while waiting for slow or high latency IO operations).
Cache contention is a very important aspect of using multi CPUs to process a highly parallelized algorithm: Make sure that you take your memory utilization into account. If you can construct your data objects so each thread has it's own memory that it is working on, you can greatly reduce cache contention between the CPUs. For example, it may be easier to have a big array of ints and have different threads working on different parts of that array - but in Java, the bounds checks on that array are going to be trying to access the same address in memory, which can cause a given CPU to have to reload data from L2 or L3 cache.
Splitting the data into it's own data structures, and configure those data structures so they are thread local (might even be more optimal to use ThreadLocal - that actually uses constructs in the OS that provide guarantees that the CPU can use to optimize cache.
The best piece of advice I can give you is test, test, test. Don't make assumptions about how CPUs will perform - there is a huge amount of magic going on in CPUs these days, often with counterintuitive results. Note also that the JIT runtime optimization will add an additional layer of complexity here (maybe good, maybe not).
A: On the one hand, you'd like to think Threads == CPU/Cores makes perfect sense. Why have a thread if there's nothing to run it?
The detail boils down to "what are the threads doing". A thread that's idle waiting for a network packet or a disk block is CPU time wasted.
If your threads are CPU heavy, then a 1:1 correlation makes some sense. If you have a single "read the DB" thread that feeds the other threads, and a single "Dump the data" thread and pulls data from the CPU threads and create output, those two could most likely easily share a CPU while the CPU heavy threads keep churning away.
The real answer, as with all sorts of things, is to measure it. Since the number is configurable (apparently), configure it! Run it with 1:1 threads to CPUs, 2:1, 1.5:1, whatever, and time the results. Fast one wins.
A: number of processors is a good start; but if those threads do a lot of i/o, then might be better with more... or less.
first think of what are the resources available and what do you want to optimise (least time to finish, least impact to other tasks, etc). then do the math.
sometimes it could be better if you dedicate a thread or two to each i/o resource, and the others fight for CPU. the analisys is usually easier on these designs.
A: The benefit of using threads is to reduce wall-clock execution time of your program by allowing your program to work on a different part of the job while another part is waiting for something to happen (usually I/O). If your program is totally CPU bound adding threads will only slow it down. If it is fully or partially I/O bound, adding threads may help but there's a balance point to be struck between the overhead of adding threads and the additional work that will get accomplished. To make the number of threads equal to the number of processors will yield peak performance if the program is totally, or near-totally CPU-bound.
As with many questions with the word "should" in them, the answer is, "It depends". If you think you can get better performance, adjust the number of threads up or down and benchmark the application's performance. Also take into account any other factors that might influence the decision (if your application is eating 100% of the computer's available horsepower, the performance of other applications will be reduced).
This assumes that the multi-threaded code is written properly etc. If the original developer only had one CPU, he would never have had a chance to experience problems with poorly-written threading code. So you should probably test behaviour as well as performance when adjusting the number of threads.
By the way, you might want to consider allowing the number of threads to be configured at run time instead of compile time to make this whole process easier.
A: After seeing your edit, it's quite possible that one thread per CPU is as good as it gets. Your application seems quite parallelizable. If you have extra hardware you can use GridGain to grid-enable your app and have it run on multiple machines. That's probably about the only thing, beyond buying faster / more cores, that will speed it up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: How can I use WPF's D3DImage with managed DirectX or XNA? I'd really like to get into some D3D coding, but I don't have the time lately to learn C++ for what will amount to a hobby project.
A: It's not officially supported as far as I know. Looks like some folks hacked it to make it work.
A: Looks like this might not be an issue for much longer, at least come .NET 4.0. Microsoft showed off a demo of XNA integration with WPF at PDC on Tuesday. If you want to see it in action, you can see the session video at the PDC site:
https://sessions.microsoftpdc.com/public/timeline.aspx
The session is PC46 (WPF Roadmap), XNA demo is around the 38 minute mark. I'm hoping they'll go into more details during the WPF Graphics Futures talk today (Session PC07). Might be a bit down the road, but it's encouraging that they're working on it.
A: If you're looking for a managed way to do Direct3D programming, I would recommend SlimDX. It's an open source .NET wrapper over DirectX. Since managed DirectX is not being supported any longer by Microsoft, this is a good way to use managed code with D3D. It's updated quite frequently and I've had very good luck using it thus far. There's a thread here that talks about using SlimDX with D3DImage.
A: Another alternative to managed DirectX and XNA is MOgre, which is a C# wrapper around a great open source C++ graphics engine that uses Direct3D, called Ogre3D. (If it is a hobby project, I think you might get going quicker by using an engine like this rather than straight-up D3D. I don't know much about XNA or SlimDX.)
Here is a CodeProject article by Leslie Godwin that takes the D3DImage class (from the Dr. WPF article mentioned by Ian) and shows how to use it with MOgre.
Edit: I created an open source project, called MogreInWpf, for using D3DImage with Mogre, based on Leslie Godwin's code referenced above, and with an alternative sample app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: PHP: Current encoding used to send data to the browser How can I know what encoding will be used by PHP when sending data to the browser? I.e. with the Cotent-Type header, for instance: iso-8859-1.
A: You can use the header() solution that William suggested, however if you are running Apache, and the Apache config is using a default charset, that will win everytime (Internet Explorer will go crazy) See: AddDefaultCharset
A: Keep in mind that content-types and encodings are two different things. text/html is a content-type; ISO-8859-1 and UTF-8 are encodings.
The HTTP response header that the server sends typically looks like this:
Content-Type: text/html; charset=utf-8
"charset" is actually the character encoding. It's not in a separate header; however there is a header called "Content-Encoding" which actually specifies what kind of compression the response uses (e.g. gzip).
If you want to change the character encoding to UTF-8, in a file that contains HTML:
<?
header("Content-Type: text/html; charset=utf-8");
A: Usually Apache + PHP servers of webhosters are configured to send out NO charset header.
The shortest way to test how your server is configured are these:
*
*Use this tool to see the server header by getting any one of your pages on your webiste.
If in the server headers you see a charset it means your server is using it, usually it won't contain a charset.
*Another way is to run this simple script on your server: <?php echo ini_get('default_charset'); ?> As said above this usually prints out an empty string, if different it will show you the charset of the PHP.
The 2nd solution is supposing Apache is not configured with AddDefaultCharset some_charset which is not usually the case, but in such case I'm afraid Apache setting might override PHP deafult_charset ini directive.
A: You can set your own with header('Content-type: xxx/yyy');, but I believe that text/html is sent by default.
A: AFAIK, PHP sends strings bytewise. that is, if your variables hold UTF-8, it will send UTF-8. if you have iso-8859-1, it will send that too. if you mix them, it won't be pretty.
A: If your server is not configured to have a default content or charset, and neither is PHP, PHP will send only Content-Type: text/html - it won't specify a charset at all, and will send the bytes as it sees them in the script.
If a browser receives a page without charset specified, various things can happen:
*
*most browsers have an "Encoding/Charset" menu; if the user explicitly selects one, the browser will try to apply it. Doesn't happen too often, so:
*some browsers try to render it with a default charset (which is locale-dependent, e.g. for FF and cs_CZ it used to be iso-8859-2; YMMV)
*IE will try to determine the charset heuristically (it will take a guess, based on character distribution - and many times it gets it right; sometimes it gets it wrong and you get a page in Romanian interpreted as Chinese text, which usually means "unreadable")
*some old browsers will fall back on us-ascii
If with this procedure, the PHP script's charset and the browser's charset matches, the text will - accidentally - be readable. If not, there will be weird signs and similar phenomena.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Renaming Objects in PowerPoint Probably a very stupid question but I can't figure how to rename an object in PowerPoint.. For example, all my Graphs are called by default "Graph 1" etc.
Could someone help me on that?
Thanks!
A: In PowerPoint 2007 you can do this from the Selection pane.
To show the Selection pane, click on the Home tab in the ribbon, then click on Arrange and then 'Selection Pane...' at the bottom. The Selection pane will open on the right. (Or press CTRL+F10)
To rename an object, first select the object and then double click on the object name in the Selection pane and you will be able to type the new object name.
A: (This answer assumes you are merely assigning more meaningful names during development, so your other code that references the objects can be more readable).
Put the code below into a sub, then run it from the slide in question. Each shape will be selected in turn, so you can see what shape is being referenced. An input box will tell you the current name and ask you for a new name. If you cancel or OK a zero-length input, the old name will stay in place. There is no name entry validation in this code, so be sure you type only valid names. After running it once, you can run it again just to check that the names you typed in the first round were applied to the object you intended.
The loop will cover all objects on the current slide, so if you want to process multiple slides, you have to run this separately on each slide. Every object on the slide is considered: title, drawing objects, groups, embedded pictures, equations, etc. etc. - just don't type a new name for objects that you don't care.
After your development is finished, best hide (Private Sub) or erase this code, so your users don't change object names by mistake.
Dim s As Integer, NewName As String
With ActiveWindow.Selection.SlideRange
For s = 1 To .Shapes.Count
.Shapes(s).Select ' So you can see the object in question
NewName = InputBox(.Shapes(s).Name) ' Tell what current name it is and ask for new name
If Len(NewName) > 0 Then .Shapes(s).Name = NewName ' If you typed a new name, apply it
Next s ' 1 To .Shapes.Count
End With ' ActiveWindow.Selection.SlideRange
A: Thanks for your help but actually I am just doing it using VBA...
ActiveWindow.Selection.ShapeRange(1).Name = "newname"
Cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Can anyone recommend a good Hashtable implementation in Javascript? I've found jCache and some other home-grown methods using associative arrays. If you've had experience with jCache, were there any limitations?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: In FinalBuilder, how do I use the HTTP Get File action with Windows Authentication? I have a FinalBuilder project where I deploy an ASP.Net website to a remote folder, configured as a website in IIS.
As part of my build script, I want to use the FinalBuilder action HTTP Get File to help determine whether my deployment was succesful.
I'm having difficulty, because the website is configured (under IIS 6) to use Integrated Windows Authentication, and anonymous access is not enabled.
Now the HTTP Get File action, has only a handful of properties, one of which is a security section, containing a UserName and Password. Great I thought! I can just put some valid credentials in there, which FinalBuilder will impersonate, whilst retrieving my file.
It turns out I was mistaken. I receive the following error:
Error retrieving url : Socket Error # 10061
Connection refused.
If I run the action without setting the Security Username and Password, I get the following error:
Error retrieving url : HTTP/1.1 401 Unauthorized Response Code : 401
Here are some facts to help with the context of my problem.
I'm running FinalBuilder 6 Professional, upon a Windows Server 2003 installation, and deploying my ASP.Net website to a remote IIS6 server within our corporate LAN.
If I configure IIS on the remote server to allow Anonymous access, I can run the HTTP Get File action without error. However, running this particular site with anon access is not acceptable in our situation.
Can anyone help suggest a workaround?
A: For a definitive answer, I think the Finalbuilder Forum is probably your best bet.
My guess, though, is that the HTTP library used by FB doesn't support Windows authentication, and is failing because no common authentication method can be negotiated. Since HTTPS isn't supported either by the 'HTTP Get File action', the possible workaround of allowing basic authentication on your site isn't a good idea, as you would be passing credentials over the network in plain text.
The only remaining workaround I can think of (other than waiting for a future FB release), is creating your own FB action to retrieve the file. Using the .NET Framework System.Net.WebClient, that should be trivial. Just start with a standalone EXE to make sure everything works, then refactor it into a 'real' action using FinalBuilder Action Studio (if that's even required: spawning an external EXE may work just fine in your case).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Setting up Rails to work with sqlserver Ok I followed the steps for setting up ruby and rails on my Vista machine and I am having a problem connecting to the database.
Contents of database.yml
development:
adapter: sqlserver
database: APPS_SETUP
Host: WindowsVT06\SQLEXPRESS
Username: se
Password: paswd
Run rake db:migrate from myapp directory
----------
rake aborted!
no such file to load -- deprecated
ADO
I have dbi 0.4.0 installed and have created the ADO folder in
C:\Ruby\lib\ruby\site_ruby\1.8\DBD\ADO
I got the ado.rb from the dbi 0.2.2
What else should I be looking at to fix the issue connecting to the database? Please don't tell me to use MySql or Sqlite or Postgres.
****UPDATE****
I have installed the activerecord-sqlserver-adapter gem from --source=http://gems.rubyonrails.org
Still not working.
I have verified that I can connect to the database by logging into SQL Management Studio with the credentials.
rake db:migrate --trace
PS C:\Inetpub\wwwroot\myapp> rake db:migrate --trace
(in C:/Inetpub/wwwroot/myapp)
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:migrate
rake aborted!
no such file to load -- deprecated
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/site_ruby/1.8/dbi.rb:48
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
C:/Ruby/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:7:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnin
gs'
C:/Ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/kernel/requires.rb:5:in `require_library_
or_gem'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-sqlserver-adapter-1.0.0.9250/lib/active_record/connection_adapters/sqlserver
_adapter.rb:29:in `sqlserver_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `send'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:292:in `connection='
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:260:in `retrieve_connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/abstract/connection_specificatio
n.rb:78:in `connection'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:408:in `initialize'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `new'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up'
C:/Ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate'
C:/Ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `call'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:621:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:616:in `execute'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:582:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:575:in `invoke_with_call_chain'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:568:in `invoke'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2031:in `invoke_task'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `each'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2009:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2003:in `top_level'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1982:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:2048:in `standard_exception_handling'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/lib/rake.rb:1979:in `run'
C:/Ruby/lib/ruby/gems/1.8/gems/rake-0.8.2/bin/rake:31
C:/Ruby/bin/rake:19:in `load'
C:/Ruby/bin/rake:19
PS C:\Inetpub\wwwroot\myapp>
A: I ran into the same problem yesterday. Apparently 'deprecated' is a gem, so you want to run "gem install deprecated" to grab and install the latest version. Good luck.
A: I used and ODBC data source and the SQL Server adapter on Windows Server 2008 against SQL Server 2000 running on a remote instance.
Install SQL Server Adapter
gem.bat install activerecord-sqlserver-adapter
Successfully installed deprecated-2.0.1
Successfully installed dbi-0.4.1
Successfully installed dbd-odbc-0.2.4
Successfully installed activerecord-sqlserver-adapter-2.2.22
4 gems installed
Create an ODBC datasource
*
*Type: SQL Server
*Name: rails_development
*Description: rails_development
*Server: SERVER
*SQL Authentication (sa/12345)
*Default Database: DATABASE
Setup database.yml
development:
adapter: sqlserver
mode: odbc
dsn: rails_development
username: sa
password: 12345
YMMV
A couple of helpful links:
*
*http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html
*http://wiki.rubyonrails.org/rails/pages/HowToUseLegacySchemas
A: Did you install the SQL Server adapter?
gem install activerecord-sqlserver-adapter --source=http://gems.rubyonrails.org
A: If you're on a 64 bit machine, there are two ODBC administrator programs, one for 32 bit and one for 64 bit. activerecord-sqlserver-adapter looks for DSNs set up with the 32 bit version.
A: Correct link is http://rubyrailsandwindows.blogspot.com/2008/03/rails-2-and-sql-server-2008-on-windows_24.html
A: I too had faced this problem. There is another work around.
You can create a DSN for the app db from control panel->admin tools->Odbc.
Database.yml file should look like below:
adapter: sqlserver
mode: odbc
dsn: DSN_NAME
host: localhost
database: App_development
username: uname
password: password
I tried using the deprecated gem, wasn't of much use.
I had tried installing an ADO adaptor too which rendered useless.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Example client implementation for the Service Location Protocol? Does anyone know of a good example implementation of the Service Location Protocol that can be build/ran on a windows box?
A: OpenSLP is said to compile fine on Windows.
A: OpenSLP referenced above is the code base that Novell uses for its SLP implementation for eDirectory now a days. Not too many things really use SLP for real these days. Usually more of a half hearted implementation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: update page text using web user control I am building an application where a page will load user controls (x.ascx) dynamically based on query string.
I have a validation summary on the page and want to update it from the User Controls. This will allow me to have multiple controls using one Validation Summary. How can I pass data between controls and pages.
I know I can define the control at design time and use events to do that but these controls are loaded dynamically using Page.LoadControl.
Also, I want to avoid using sessions or querystring.
A: Found a way of doing this:
Step 1: Create a Base User Control and define Delegates and Events in this control.
Step 2: Create a Public function in the base user control to Raise Events defined in Step1.
'SourceCode for Step 1 and Step 2
Public Delegate Sub UpdatePageHeaderHandler(ByVal PageHeading As String)
Public Class CommonUserControl
Inherits System.Web.UI.UserControl
Public Event UpdatePageHeaderEvent As UpdatePageHeaderHandler
Public Sub UpdatePageHeader(ByVal PageHeadinga As String)
RaiseEvent UpdatePageHeaderEvent(PageHeadinga)
End Sub
End Class
Step 3: Inherit your Web User Control from the base user control that you created in Step1.
Step 4: From your Web User Control - Call the MyBase.FunctionName that you defined in Step2.
'SourceCode for Step 3 and Step 4
Partial Class DerievedUserControl
Inherits CommonUserControl
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
MyBase.PageHeader("Test Header")
End Sub
End Class
Step 5: In your page, Load the control dynamically using Page.LoadControl and Cast the control as the Base user control.
Step 6: Attach Event Handlers with this Control.
'SourceCode for Step 5 and Step 6
Private Sub LoadDynamicControl()
Try
'Try to load control
Dim c As CommonUserControl = CType(LoadControl("/Common/Controls/Test.ascx", CommonUserControl))
'Attach Event Handlers to the LoadedControl
AddHandler c.UpdatePageHeaderEvent, AddressOf PageHeaders
DynamicControlPlaceHolder.Controls.Add(c)
Catch ex As Exception
'Log Error
End Try
End Sub
A: Assuming you're talking about asp's validator controls, making them work with the validation summary should be easy: use the same Validation Group. Normally, I derive all usercontrols from a base class that adds a ValidationGroup property whose setter calls a overriden method that changes all internal validators to the same validation group.
The tricky part is making them behave when added dynamically. There are some gotchas you should be aware of, mainly concerning the page cycle and when you add them to your Page object. If you know all the possible user controls you'll use during design time, I'd try to add them statically using EnableViewState and Visible to minimize overhead, even if there are too many of them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I let a table's body scroll but keep its head fixed in place? I am writing a page where I need an HTML table to maintain a set size. I need the headers at the top of the table to stay there at all times but I also need the body of the table to scroll no matter how many rows are added to the table. Think a mini version of excel. This seems like a simple task but almost every solution I have found on the web has some drawback. How can I solve this?
A: I had to find the same answer. The best example I found is http://www.cssplay.co.uk/menu/tablescroll.html - I found example #2 worked well for me. You will have to set the height of the inner table with Java Script, the rest is CSS.
A: Edit: This is a very old answer and is here for prosperity just to show that it was supported once back in the 2000's but dropped because browsers strategy in the 2010's was to respect W3C specifications even if some features were removed: Scrollable table with fixed header/footer was clumsily specified before HTML5.
Bad news
Unfortunately there is no elegant way to handle scrollable table with fixed thead/tfoot
because HTML/CSS specifications are not very clear about that feature.
Explanations
Although HTML 4.01 Specification says thead/tfoot/tbody are used (introduced?) to scroll table body:
Table rows may be grouped [...] using the THEAD, TFOOT and TBODY elements [...].
This division enables user agents to support scrolling of table bodies independently of the table head and foot.
But the working scrollable table feature on FF 3.6 has been removed in FF 3.7 because considered as a bug because not compliant with HTML/CSS specifications. See this and that comments on FF bugs.
Mozilla Developer Network tip
Below is a simplified version of the MDN useful tips for scrollable table
see this archived page or the current French version
<style type="text/css">
table {
border-spacing: 0; /* workaround */
}
tbody {
height: 4em; /* define the height */
overflow-x: hidden; /* esthetics */
overflow-y: auto; /* allow scrolling cells */
}
td {
border-left: 1px solid blue; /* workaround */
border-bottom: 1px solid blue; /* workaround */
}
</style>
<table>
<thead><tr><th>Header
<tfoot><tr><th>Footer
<tbody>
<tr><td>Cell 1 <tr><td>Cell 2
<tr><td>Cell 3 <tr><td>Cell 4
<tr><td>Cell 5 <tr><td>Cell 6
<tr><td>Cell 7 <tr><td>Cell 8
<tr><td>Cell 9 <tr><td>Cell 10
<tr><td>Cell 11 <tr><td>Cell 12
<tr><td>Cell 13 <tr><td>Cell 14
</tbody>
</table>
However MDN also says this does not work any more on FF :-(
I have also tested on IE8 => table is not scrollable either :-((
A: I found DataTables to be quite flexible. While its default version is based on jquery, there is also an AngularJs plugin.
A: Not sure if anyone is still looking at this but they way I have done this previously is to use two tables to display the single original table - the first just the original table title line and no table body rows (or an empty body row to make it validate).
The second is in a separate div and has no title and just the original table body rows. The separate div is then made scrollable.
The second table in it's div is placed just below the first table in the HTML and it looks like a single table with a fixed header and a scrollable lower section. I have only tested this in Safari, Firefox and IE (latest versions of each in Spring 2010) but it worked in all of them.
The only issue it had was that the first table would not validate without a body (W3.org validator - XHTML 1.0 strict), and when I added one with no content it causes a blank row. You can use CSS to make this not visible but it still eats up space on the page.
A: This solution works in Chrome 35, Firefox 30 and IE 11 (not tested other versions)
Its pure CSS:
http://jsfiddle.net/ffabreti/d4sope1u/
Everything is set to display:block, table needs a height:
table {
overflow: scroll;
display: block; /*inline-block*/
height: 120px;
}
thead > tr {
position: absolute;
display: block;
padding: 0;
margin: 0;
top: 0;
background-color: gray;
}
tbody > tr:nth-of-type(1) {
margin-top: 16px;
}
tbody tr {
display: block;
}
td, th {
width: 70px;
border-style:solid;
border-width:1px;
border-color:black;
}
A: This caused me huge headaches trying to implement such a grid for an application of ours. I tried all the various techniques out there but they each had problems. The closest I came was using a jQuery plugin such as Flexigrid (look on http://www.ajaxrain.com for alternatives), but this doesn't seem to support 100% wide tables which is what I needed.
What I ended up doing was rolling my own; Firefox supports scrolling tbody elements so I browser sniffed and used appropriate CSS (setting height, overflow etc... ask if you want more details) to make that scroll, and then for other browsers I used two separate tables set to use table-layout: fixed which uses a sizing algorithm that is guarenteed not to overflow the stated size (normal tables will expand when content is too wide to fit). By giving both tables identical widths I was able to get their columns to line up. I wrapped the second one in a div set to scroll and with a bit of jiggery pokery with margins etc managed to get the look and feel I wanted.
Sorry if this answer sounds a bit vague in places; I'm writing quickly as I don't have much time. Leave a comment if you want me to expand any further!
A: Here's a code that really works for IE and FF (at least):
<html>
<head>
<title>Test</title>
<style type="text/css">
table{
width: 400px;
}
tbody {
height: 100px;
overflow: scroll;
}
div {
height: 100px;
width: 400px;
position: relative;
}
tr.alt td {
background-color: #EEEEEE;
}
</style>
<!--[if IE]>
<style type="text/css">
div {
overflow-y: scroll;
overflow-x: hidden;
}
thead tr {
position: absolute;
top: expression(this.offsetParent.scrollTop);
}
tbody {
height: auto;
}
</style>
<![endif]-->
</head>
<body>
<div >
<table border="0" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th style="background: lightgreen;">user</th>
<th style="background: lightgreen;">email</th>
<th style="background: lightgreen;">id</th>
<th style="background: lightgreen;">Y/N</th>
</tr>
</thead>
<tbody align="center">
<!--[if IE]>
<tr>
<td colspan="4">on IE it's overridden by the header</td>
</tr>
<![endif]-->
<tr>
<td>user 1</td>
<td>user@user.com</td>
<td>1</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 2</td>
<td>user@user.com</td>
<td>2</td>
<td>N</td>
</tr>
<tr>
<td>user 3</td>
<td>user@user.com</td>
<td>3</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 4</td>
<td>user@user.com</td>
<td>4</td>
<td>N</td>
</tr>
<tr>
<td>user 5</td>
<td>user@user.com</td>
<td>5</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 6</td>
<td>user@user.com</td>
<td>6</td>
<td>N</td>
</tr>
<tr>
<td>user 7</td>
<td>user@user.com</td>
<td>7</td>
<td>Y</td>
</tr>
<tr class="alt">
<td>user 8</td>
<td>user@user.com</td>
<td>8</td>
<td>N</td>
</tr>
</tbody>
</table>
</div>
</body></html>
I've changed the original code to make it clearer and also to put it working fine in IE and also FF..
Original code HERE
A: I saw Sean Haddy's excellent solution to a similar question and took the liberty of making some edits:
*
*Use classes instead of ID, so one jQuery script could be reused for
multiple tables on one page
*Added support for semantic HTML table elements like caption, thead, tfoot, and tbody
*Made scrollbar optional so it won't appear for tables that are "shorter" than the scrollable height
*Adjusted scrolling div's width to bring the scrollbar up to the right edge of the table
*Made concept accessible by
*
*using aria-hidden="true" on injected static table header
*and leaving original thead in place, just hidden with jQuery and set aria-hidden="false"
*Showed examples of multiple tables with different sizes
Sean did the heavy lifting, though. Thanks to Matt Burland, too, for pointing out need to support tfoot.
Please see for yourself at http://jsfiddle.net/jhfrench/eNP2N/
A: Have you tried using thead and tbody, and setting a fixed height on tbody with overflow:scroll?
What are your target browsers?
EDIT: It worked well (almost) in firefox - the addition of the vertical scrollbar caused the need for a horizontal scrollbar as well - yuck. IE just set the height of each td to what I had specifed the height of tbody to be. Here's the best I could come up with:
<html>
<head>
<title>Blah</title>
<style type="text/css">
table { width:300px; }
tbody { height:10em; overflow:scroll;}
td { height:auto; }
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>One</th><th>Two</th>
</td>
</tr>
</thead>
<tbody>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
</tbody>
</table>
</body>
</html>
A: What you need is :
*
*have a table body of limited height as scroll occurs only when contents is bigger than the scrolling window. However tbody cannot be sized, and you have to display it as a block to do so:
tbody {
overflow-y: auto;
display: block;
max-height: 10em; // For example
}
*Re-sync table header and table body columns widths as making the latter a block made it an unrelated element. The only way to do so is to simulate synchronization by enforcing the same columns width to both.
However, since tbody itself is a block now, it can no longer behave like a table. Since you still need a table behavior to display you columns correctly, the solution is to ask for each of your rows to display as individual tables:
thead {
display: table;
width: 100%; // Fill the containing table
}
tbody tr {
display: table;
width: 100%; // Fill the containing table
}
(Note that, using this technique, you won't be able to span across rows anymore).
Once that done, you can enforce column widths to have the same width in both thead and tbody. You could not that:
*
*individually for each column (through specific CSS classes or inline styling), which is quite tedious to do for each table instance ;
*uniformly for all columns (through th, td { width: 20%; } if you have 5 columns for example), which is more practical (no need to set width for each table instance) but cannot work for any columns count
*uniformly for any columns count, through a fixed table layout (i.e. same width for all).
I prefer the last option, which requires adding:
thead {
table-layout: fixed; // Same layout for all cells
}
tbody tr {
table-layout: fixed; // Same layout for all cells
}
th, td {
width: auto; // Same width for all cells, if table has fixed layout
}
See a demo here, forked from the answer to this question.
A: Here's my alternative. It also uses different DIVs for the header, body and footer but synchronised for window resizing and with searching, scrolling, sorting, filtering and positioning:
My CD lists
Click on the Jazz, Classical... buttons to see the tables. It's set up so that it's adequate even if JavaScript is turned off.
Seems OK on IE, FF and WebKit (Chrome, Safari).
A: Sorry I haven.t read all replies to your question.
Yeah here the thing you want (I have done already)
You can use two tables, with same class name for similar styling, one only with table head and another with your rows.
Now put this table inside a div having fixed height with overflow-y:auto OR scroll.
A: The main problem I had with the suggestions above was being able to plug in tablesorter.js AND being able to float the headers for a table constrained to a specific max size. I eventually stumbled across the plugin jQuery.floatThead which provided the floating headers and allowed sorting to continue to work.
It also has a nice comparison page showing itself vs similar plugins.
A: Live JsFiddle
It is possible with only HTML & CSS
table.scrollTable {
border: 1px solid #963;
width: 718px;
}
thead.fixedHeader {
display: block;
}
thead.fixedHeader tr {
height: 30px;
background: #c96;
}
thead.fixedHeader tr th {
border-right: 1px solid black;
}
tbody.scrollContent {
display: block;
height: 262px;
overflow: auto;
}
tbody.scrollContent td {
background: #eee;
border-right: 1px solid black;
height: 25px;
}
tbody.scrollContent tr.alternateRow td {
background: #fff;
}
thead.fixedHeader th {
width: 233px;
}
thead.fixedHeader th:last-child {
width: 251px;
}
tbody.scrollContent td {
width: 233px;
}
<table cellspacing="0" cellpadding="0" class="scrollTable">
<thead class="fixedHeader">
<tr class="alternateRow">
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody class="scrollContent">
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>And Repeat 1</td>
<td>And Repeat 2</td>
<td>And Repeat 3</td>
</tr>
<tr class="normalRow">
<td>Cell Content 1</td>
<td>Cell Content 2</td>
<td>Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>More Cell Content 1</td>
<td>More Cell Content 2</td>
<td>More Cell Content 3</td>
</tr>
<tr class="normalRow">
<td>Even More Cell Content 1</td>
<td>Even More Cell Content 2</td>
<td>Even More Cell Content 3</td>
</tr>
<tr class="alternateRow">
<td>End of Cell Content 1</td>
<td>End of Cell Content 2</td>
<td>End of Cell Content 3</td>
</tr>
</tbody>
</table>
A: If its ok to use JavaScript here is my solution
Create a table set fixed width on all columns (pixels!) add the class Scrollify to the table and add this javascript + jquery 1.4.x set height in css or style!
Tested in: Opera, Chrome, Safari, FF, IE5.5(Epic script fail), IE6, IE7, IE8, IE9
//Usage add Scrollify class to a table where all columns (header and body) have a fixed pixel width
$(document).ready(function () {
$("table.Scrollify").each(function (index, element) {
var header = $(element).children().children().first();
var headerHtml = header.html();
var width = $(element).outerWidth();
var height = parseInt($(element).css("height")) - header.outerHeight();
$(element).height("auto");
header.remove();
var html = "<table style=\"border-collapse: collapse;\" border=\"1\" rules=\"all\" cellspacing=\"0\"><tr>" + headerHtml +
"</tr></table><div style=\"overflow: auto;border:0;margin:0;padding:0;height:" + height + "px;width:" + (parseInt(width) + scrollbarWidth()) + "px;\">" +
$(element).parent().html() + "</div>";
$(element).parent().html(html);
});
});
//Function source: http://www.fleegix.org/articles/2006-05-30-getting-the-scrollbar-width-in-pixels
//License: Apache License, version 2
function scrollbarWidth() {
var scr = null;
var inn = null;
var wNoScroll = 0;
var wScroll = 0;
// Outer scrolling div
scr = document.createElement('div');
scr.style.position = 'absolute';
scr.style.top = '-1000px';
scr.style.left = '-1000px';
scr.style.width = '100px';
scr.style.height = '50px';
// Start with no scrollbar
scr.style.overflow = 'hidden';
// Inner content div
inn = document.createElement('div');
inn.style.width = '100%';
inn.style.height = '200px';
// Put the inner div in the scrolling div
scr.appendChild(inn);
// Append the scrolling div to the doc
document.body.appendChild(scr);
// Width of the inner div sans scrollbar
wNoScroll = inn.offsetWidth;
// Add the scrollbar
scr.style.overflow = 'auto';
// Width of the inner div width scrollbar
wScroll = inn.offsetWidth;
// Remove the scrolling div from the doc
document.body.removeChild(
document.body.lastChild);
// Pixel width of the scroller
return (wNoScroll - wScroll);
}
Edit: Fixed height.
A: I do this with javascript (no library) and CSS - the table body scrolls with the page, and the table does not have to be fixed width or height, although each column must have a width. You can also keep sorting functionality.
Basically:
*
*In HTML, create container divs to position the table header row and the
table body, also create a "mask" div to hide the table body as it
scrolls past the header
*In CSS, convert the table parts to blocks
*In Javascript, get the table width and match the mask's width... get
the height of the page content... measure scroll position...
manipulate CSS to set the table header row position and the mask
height
Here's the javascript and a jsFiddle DEMO.
// get table width and match the mask width
function setMaskWidth() {
if (document.getElementById('mask') !==null) {
var tableWidth = document.getElementById('theTable').offsetWidth;
// match elements to the table width
document.getElementById('mask').style.width = tableWidth + "px";
}
}
function fixTop() {
// get height of page content
function getScrollY() {
var y = 0;
if( typeof ( window.pageYOffset ) == 'number' ) {
y = window.pageYOffset;
} else if ( document.body && ( document.body.scrollTop) ) {
y = document.body.scrollTop;
} else if ( document.documentElement && ( document.documentElement.scrollTop) ) {
y = document.documentElement.scrollTop;
}
return [y];
}
var y = getScrollY();
var y = y[0];
if (document.getElementById('mask') !==null) {
document.getElementById('mask').style.height = y + "px" ;
if (document.all && document.querySelector && !document.addEventListener) {
document.styleSheets[1].rules[0].style.top = y + "px" ;
} else {
document.styleSheets[1].cssRules[0].style.top = y + "px" ;
}
}
}
window.onscroll = function() {
setMaskWidth();
fixTop();
}
A: For me, nothing related to scrolling really worked until I removed the width from the table CSS. Originally, the table CSS looked like this:
.table-fill {
background: white;
border-radius:3px;
border-collapse: collapse;
margin: auto;
width: 100%;
max-width: 800px;
padding:5px;
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
animation: float 5s infinite;
}
As soon as I removed the width:100%; all scrolling features started working.
A: If you have low enough standards ;) you could place a table that contains only a header directly above a table that has only a body. It won't scroll horizontally, but if you don't need that...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "148"
}
|
Q: In Installshield, what is the best event to use to launch applications only on install, not on uninstall or repair? We have recently moved back to InstallShield 2008 from rolling our own install. So, I am still trying to get up the learning curve on it.
We are using Firebird and a usb driver, that we couldn't find good msi install solutions. So, we have a cmd line to install firebird silently and the usb driver mostly silently.
We have put this code into the event handler DefaultFeatureInstalled. This works really well on the first time install. But, when I do an uninstall it trys to launch the firebird installer again, so it must be sending the DefaultFeatureInstalled event again.
Is their another event to use, or is there a way to detect whether its an install or uninstall in the DefaultFeatureInstalled event?
A: Chris, I had trouble getting the MsiGetProperty to work at all. Just adding the code that you have
string sRemove;
number nBuffer;
nBuffer = 256;
if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then
//do something
endif;
I get "undefined identifier". I tried several things to get IS to recognize it without success. After some more poking around, I realized that IS was not calling the function on uninstall in the first place. I had another function, onEnd I think that was calling the same things. After cleaning that up, I was getting the result I had expected in the beginning.
So the correct answer would be that you don't have to do anything for the code in the DefaultFeature_Installed event not to be called on uninstall.
A: There are MSI properties you can look at that will tell you if a product is already installed or if an uninstall is taking place. The Installed property will be true if the product is already there, so you can use it in a Boolean expression (Ex: Not Installed). The REMOVE property will be set to "ALL" if an uninstall is taking place. You might be able to condition your Firebird installation logic on these properties, which you can retrieve using the MsiGetProperty function.
Note: Property names mean different things based on case, so make sure you use the cases above.
I couldn't find any reference in the IS online help or Google to the DefaultFeatureInstalled event. Is your InstallShield project Basic MSI or InstallScript?
A: I am doing an InstallScript project.
I double checked the event and the function that I am using is DefaultFeature_Installed with an underscore. I have searched the Net and IS's website and have found mention of it but no definition. I asked the developer here who originally moved the code to this event, and she can't remember where or why she moved the code to this event.
I will look into MsiGetProperty this morning. Thanks for the pointer.
A: You can add this code to the DefaultFeature_Installed event:
string sRemove;
number nBuffer;
nBuffer = 256;
if (MsiGetProperty(ISMSI_HANDLE, "REMOVE", sRemove, nBuffer) = ERROR_SUCCESS) then
//do something
endif;
Note: the function name is case sensitive. The ISMSI_HANDLE value is a handle to the InstallShield install engine. If sRemove is equal to "ALL", which indicates an uninstall is taking place, you can skip the Firebird installation.
A: If you are using an InstallScript or InstallScript MSI project, you will want to handle the OnFirstUIBefore event. It is called the first time the installer is run. When the installer is launch again, the OnMaintUIBefore event is raised in its place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does the windows FILETIME structure include leap seconds? The FILETIME structure counts from January 1 1601 (presumably the start of that day) according to the Microsoft documentation, but does this include leap seconds?
A: Here's some more info about why that particular date was chosen.
The FILETIME structure records time in
the form of 100-nanosecond intervals
since January 1, 1601. Why was that
date chosen?
The Gregorian calendar operates on a
400-year cycle, and 1601 is the first
year of the cycle that was active at
the time Windows NT was being
designed. In other words, it was
chosen to make the math come out
nicely.
I actually have the email from Dave
Cutler confirming this.
A: There can be no single answer to this question without first deciding: What is the Windows FILETIME actually counting? The Microsoft docs say it counts 100 nanosecond intervals since 1601 UTC, but this is problematic.
No form of internationally coordinated time existed prior to the year 1960. The name UTC itself does not occur in any literature prior to 1964. The name UTC as an official designation did not exist until 1970. But it gets worse. The Royal Greenwich Observatory was not established until 1676, so even trying to interpret the FILETIME as GMT has no clear meaning, and it was only around then that pendulum clocks with accurate escapements began to give accuracies of 1 second.
If FILETIME is interpreted as mean solar seconds then the number of leap seconds since 1601 is zero, for UT has no leap seconds. If FILETIME is interpreted as if there had been atomic chronometers then the number of leap seconds since 1601 is about -60 (that's negative 60 leap seconds).
That is ancient history, what about the era since atomic chronometers? It is no better because national governments have not made the distinction between mean solar seconds and SI seconds. For a decade the ITU-R has been discussing abandoning leap seconds, but they have not achieved international consensus. Part of the reason for that can be seen in the
javascript on this page (also see the delta-T link on that page for plots of the ancient history). Because national governments have not made a clear distinction, any attempt to define the count of seconds since 1972 runs the risk of being invalid according to the laws of some jurisdiction. The delegates to ITU-R are aware of this complexity, as are the folks on the POSIX committee. Until the diplomatic issues are worked out, until national governments and international standards make a clear distinction and choice between mean solar and SI seconds, there is little hope that the computer standards can follow suit.
A: The answer to this question used to be no, but has changed to: YES, sort of, sometimes...
Per the Windows Networking team blog article:
Starting in Server 2019 and the Windows 10 October [2018] update time APIs will now take into account all leap seconds the Operating System is aware of when it translates FILETIME to SystemTime.
As there have been no leap seconds issued since the time of this feature being added, the operating system is still unaware of any leap seconds. However, when the next official leap second makes its way into the world, Windows computers that have this new feature enabled will keep track of it, and thus FILETIME values will be offset by the number of leap seconds on the computer at the time they are interpreted.
The blog post goes on to describe:
No change is made to FILETIME. It still represents the number of 100 ns intervals since the start of the epoch. What has changed is the interpretation of that number when it is converted to SYSTEMTIME and back. Here is a list of affected APIs:
*
*GetSystemTime
*GetLocalTime
*FileTimeToSystemTime
*FileTimeToLocalTime
*SystemTimeToFileTime
*SetSystemTime
*SetLocalTime
Previous to this release, SYSTEMTIME had valid values for wSecond between 0 and 59. SYSTEMTIME has now been updated to allow a value of 60, provided the year, month, and day represents day in which a leap second is valid.
...
In order receive the 60 second in the SYSTEMTIME structure a process must explicitly opt-in.
Note that the opt-in applies to the behavior within the functions listed on how a FILETIME is mapped to a SYSTEMTIME. Regardless of whether you opt-in or not, the operating system will still offset FILETIME values according to the leap seconds it is aware of.
With regard to compatibility, the article states:
Applications that rely on 3rd party frameworks should ensure their framework’s implementation on Windows is also calling into the correct APIs to calculate the correct time, or else the application will have the wrong time reported.
And also provides a links to an earlier post which describes how to disable the entire feature, as follows:
... you can revert to the prior operating system behavior and disable leap seconds across the board by adding the following registry key:
*
*HKLM:\SYSTEM\CurrentControlSet\Control\LeapSecondInformation
*Type: "REG_DWORD"
*Name: Enabled
*Value: 0 Disables the system-wide setting
*Value: 1 Enables the system-wide setting
Next, restart your system.
A: Leap seconds are added unpredictably by the IERS. 23 seconds have been added since 1972, when UTC and leap seconds were defined. Wikipedia says "because the Earth's rotation rate is unpredictable in the long term, it is not possible to predict the need for them more than six months in advance."
Since you'd have to keep a history of when leap seconds were inserted, and keep updating the OS to keep a reference of when they had been inserted, and the difference is so small, it's fair not to expect a general-purpose OS to compensate for leap seconds.
In addition, regular clock drift, of the simple electronic clock in your PC compared to UTC, is so much larger than the compensation required for leap seconds. If you need the kind of precision to compensate for leap seconds, you shouldn't use the highly-inaccurate PC clock.
A: The question shouldn't be if FILETIME includes leap seconds.
It should be:
Do the people, functions, and libraries, who interpret a FILETIME (i.e. FileTimeToSystemTime) include leap seconds when counting the duration?
The simple answer is "no". FileTimeToSystemTime returns seconds as 0..59.
The simpler answer is: "of course not, how could it?".
My Windows 2000 machine doesn't know that there were 2 leap seconds added in the decade since it was released. Any interpretation it makes of a FILETIME is wrong.
Finally, rather than relying on logic, we can determine by direct experimental observation, the answer to the posters question:
var
systemTime: TSystemTime;
fileTime: TFileTime;
begin
//Construct a system-time for the 12/31/2008 11:59:59 pm
ZeroMemory(@systemTime, SizeOf(systemTime));
systemtime.wYear := 2008;
systemTime.wMonth := 12;
systemTime.wDay := 31;
systemTime.wHour := 23;
systemtime.wMinute := 59;
systemtime.wSecond := 59;
//Convert it to a file time
SystemTimeToFileTime(systemTime, {var}fileTime);
//There was a leap second 12/31/2008 11:59:60 pm
//Add one second to our filetime to reach the leap second
filetime.dwLowDateTime := fileTime.dwLowDateTime+10000000; //10,000,000 * 100ns = 1s
//Convert the filetime, sitting on a leap second, to a displayable system time
FileTimeToSystemTime(fileTime, {var}systemTime);
//And now print the system time
ShowMessage(DateTimeToStr(SystemTimeToDateTime(systemTime)));
Adding one second to
12/31/2008 11:59:59pm
gives
1/1/2009 12:00:00am
rather than
1/1/2009 11:59:60pm
Q.E.D.
Original poster might not like it, but god intentionally rigged it so that a year is not evenly divisible by a day. He did it just to screw up programmers.
A: According to this comment windows is totally unaware of leap seconds. If you add 24 * 60 * 60 seconds to a FILETIME that represents 1:39:45 today, you get a FILETIME that represents 1:39:45 tomorrow, no matter what.
A: A very crude summary:
UTC = (Atomic Time) + (Leap Seconds) ~~ (Mean Solar Time)
The MS documentation says, specifically, "UTC", and so should include the leap seconds. As always with MS, your mileage may vary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Decoding letters ('a' .. 'z') from a bit sequence without waste I seek an algorithm that will let me represent an incoming sequence of bits as letters ('a' .. 'z' ), in a minimal matter such that the stream of bits can be regenerated from the letters, without ever holding the entire sequence in memory.
That is, given an external bit source (each read returns a practically random bit), and user input of a number of bits, I would like to print out the minimal number of characters that can represent those bits.
Ideally there should be a parameterization - how much memory versus maximum bits before some waste is necessary.
Efficiency Goal - The same number of characters as the base-26 representation of the bits.
Non-solutions:
*
*If sufficient storage was present, store the entire sequence and use a big-integer MOD 26 operation.
*Convert every 9 bits to 2 characters - This seems suboptimal, wasting 25% of information capacity of the letters output.
A: If you assign a different number of bits per letter, you should be able to exactly encode the bits in the twenty-six letters allowed without wasting any bits. (This is a lot like a Huffman code, only with a pre-built balanced tree.)
To encode bits into letters: Accumulate bits until you match exactly one of the bit codes in the lookup table. Output that letter, clear the bit buffer, and keep going.
To decode letters into bits: For each letter, output the bit sequence in the table.
Implementing in code is left as an exercise to the reader. (Or to me, if I get bored later.)
a 0000
b 0001
c 0010
d 0011
e 0100
f 0101
g 01100
h 01101
i 01110
j 01111
k 10000
l 10001
m 10010
n 10011
o 10100
p 10101
q 10110
r 10111
s 11000
t 11001
u 11010
v 11011
w 11100
x 11101
y 11110
z 11111
A: Convert each block of 47 bits to a base 26 number of 10 digits. This gives you more than 99.99% efficiency.
This method, as well as others like Huffman, needs a padding mechanism to support variable-length input. This introduces some inefficiency which is less significant with longer inputs.
At the end of the bit stream, append an extra 1 bit. This must be done in all cases, even when the length of the bit stream is a multiple of 47. Any high-order letters of "zero" value can be skipped in the last block of encoded output.
When decoding the letters, a truncated final block can be filled out with "zero" letters and converted to a 47-bit base 2 representation. The final 1 bit is not data, but marks the end of the bit stream.
A: Could Huffman coding be what you're looking for? It's a compression algorithm, which pretty much represents any information with a minimum of wasted bits.
A: Zero waste would be log_2(26) bits per letter. As pointed out earlier, you can get to 4.7 by reading 47 bits and converting them to 10 letters. However, you can get to 4.67 by converting every 14 bits into 3 characters. This has the advantage that it fits into an integer. If you have storage space and run time is important, you can create a lookup table with 17,576 entries mapping the possible 14 bits into 3 letters. Otherwise, you can do mod and div operations to compute the 3 letters.
number of letters number of bits bits/letter
1 4 4
2 9 4.5
3 14 4.67
4 18 4.5
5 23 4.6
6 28 4.67
7 32 4.57
8 37 4.63
9 42 4.67
10 47 4.7
A: Any solution you use is going to be space-inefficient because 26 is not a power of 2. As far as an algorithm goes, I'd rather use a lookup table than an on-the-fly calculation for each series of 9 bits. Your lookup table would 512 entries long.
A: If you want the binary footprint of each letter to have the same size, the optimal solution would be given by Arithmetic Encoding. However, it will not reach your goal of a mean representation of 4.5 bits/char. Given 26 different characters (not including space etc) 4.7 would be the best you can reach without using variable-length encoding (Huffman, for instance. See Jaegers's answer) or other compression algoritms.
A suboptimal, although simpler, solution could be to find a feasible number of characters to fit into a big integer. For instance, if you form a 32-bit integer out of every 6 charachter chunk (which is possible as 26^6 < 2^32), you use 5.33 bits/char. You can actually even fit 13 letters into a 64 bit integer (4.92 bits/char). This is quite close to the optimal solution, and still rather easy to implement. Using bigger ints than 64 bits can be tricky due to missing native support in many progamming languages.
If you want even better compression rates for text, you should definitely also look into dictionary-based compression algorithms, such as LZW or Deflate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do you like the new Ribbon Controls in D2009? How do they compare to the DevXpress ones or the original MSOffice ones.
Are they worth investing time in them (for practical usage now, not academic curiosity which I'll do anyway)?
A: From my experience, the new ribbon control implements the entire specification as laid out by Microsoft. The only issue I noticed was a slight flicker when the form was resized which caused one of the sections to collapse or expand.
Worth spending time in? Definitely, as they are lighter weight and its a matter of time before someone gets rid of the flicker (could be as simple as a lockwindowupdate inserted in the source?). It doesn't hurt to use the Delphi action manager, from which all is based.
A: The only problem I can see with them so far, is the lack of Glass Frame implementation on Windows Vista (see my question here), unless someone has found a way to make that work. The only part which may not be a problem for youself is there doesn't appear to be a way to customise the theme, which I know some people would like to do in their applications.
A: IMO, the DevExpress ribbon control is much more complex than it needs to be. i own the DevExpress ribbon control but converted to using the delphi TRibbon. the delphi TRibbon isn't perfect either but i've learned to avoid these problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Preferred protocols to upload static files to your Apache server? If you were the administrator of an Apache web server, what protocol(s) would you prefer to provide, for the web developers to upload static files (html/gif/css/...), with the goal of maximum security ?
If you were the web developer/graphic designer, what protocols would you prefer to be available at the Apache server, to upload static files ?
A: SCP is what I'd go with.
You can even use Filezilla for it and pretend it's unsecure FTP: http://filezilla-project.org/
A: SSH/SCP. It's simple, fast, free, and can be as secure as you want. Alternatives are FTP (hahahaha, yeah right) and POSTing files over HTTPS.
A: I give web developers instructions on using an sftp/scp client and a login shell using scponly. That way they get their access to upload files, but I have fewer concerns about them doing bad things to the webserver.
A: I use ssh config to limit users to sftp on a development server then use version control to review the changes and move them to production with got format-patch
A: We deploy using Capistrano, which afaik does all its work via git (over SSH) - at least, in our deploy script it is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to pass all Visual Studio 2008 "Macros" to Python script? [NOTE: This questions is similar to but not the same as this one.]
Visual Studio defines several dozen "Macros" which are sort of simulated environment variables (completely unrelated to C++ macros) which contain information about the build in progress. Examples:
ConfigurationName Release
TargetPath D:\work\foo\win\Release\foo.exe
VCInstallDir C:\ProgramFiles\Microsoft Visual Studio 9.0\VC\
Here is the complete set of 43 built-in Macros that I see (yours may differ depending on which version of VS you use and which tools you have enabled):
ConfigurationName IntDir RootNamespace TargetFileName
DevEnvDir OutDir SafeInputName TargetFramework
FrameworkDir ParentName SafeParentName TargetName
FrameworkSDKDir PlatformName SafeRootNamespace TargetPath
FrameworkVersion ProjectDir SolutionDir VCInstallDir
FxCopDir ProjectExt SolutionExt VSInstallDir
InputDir ProjectFileName SolutionFileName WebDeployPath
InputExt ProjectName SolutionName WebDeployRoot
InputFileName ProjectPath SolutionPath WindowsSdkDir
InputName References TargetDir WindowsSdkDirIA64
InputPath RemoteMachine TargetExt
Of these, only four (FrameworkDir, FrameworkSDKDir, VCInstallDir and VSInstallDir) are set in the environment used for build-events.
As Brian mentions, user-defined Macros can be defined such as to be set in the environment in which build tasks execute. My problem is with the built-in Macros.
I use a Visual Studio Post-Build Event to run a python script as part of my build process. I'd like to pass the entire set of Macros (built-in and user-defined) to my script in the environment but I don't know how. Within my script I can access regular environment variables (e.g., Path, SystemRoot) but NOT these "Macros". All I can do now is pass them on-by-one as named options which I then process within my script. For example, this is what my Post-Build Event command line looks like:
postbuild.py --t="$(TargetPath)" --c="$(ConfigurationName)"
Besides being a pain in the neck, there is a limit on the size of Post-Build Event command line so I can't pass dozens Macros using this method even if I wanted to because the command line is truncated.
Does anyone know if there is a way to pass the entire set of Macro names and values to a command that does NOT require switching to MSBuild (which I believe is not available for native VC++) or some other make-like build tool?
A: You might want to look into PropertySheets. These are files containing Visual C++ settings, including user macros. The sheets can inherit from other sheets and are attached to VC++ projects using the PropertyManager View in Visual Studio. When you create one of these sheets, there is an interface for creating user macros. When you add a macro using this mechanism, there is a checkbox for setting the user macro as an environment variable. We use this type of mechanism in our build system to rapidly set up projects to perform out-of-place builds. Our various build directories are all defined as user macros. I have not actually verified that the environment variables are set in an external script called from post-build. I tend to use these macros as command line arguments to my post-build scripts - but I would expect accessing them as environment variables should work for you.
A: This is a bit hacky, but it could work.
Why not call multiple .py scripts in a row?
Each scripts can pass in a small subset of the parameters, and the values to a temp text file. The final script will read and work off of the temp text file.
I agree that this method is filled with danger and WTF's, but sometimes you have to just hack stuff together.
A: As far as I can tell, the method described in the question is the only way to pass build variables to a Python script.
Perhaps Visual Studio 2010 has something better?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to implement a company-internal icon gallery I love writing my own web-based applications, but don't want to succumb to the not invented here syndrome. So before I go write this myself, I'm looking for solutions that either do this, or perhaps frameworks (like Django or Joomla, etc.) that give me a starting point fairly close to what I need.
My company produces software with a large variety of user interfaces. We've decided to keep an icon database where one can search for icons by size, keyword, etc, track there they've been used so far, upload them, browse them, etc.
I've toyed with the idea of starting with an "image gallery" (Gallery, Coppermine, 4homepages, etc) but I was hoping for something that allows us to track versions of the icons, like we do for all our other source files, and I'm sure the attributes we track alongside each icon will expand over time, so it needs to be easily extensible.
So what do people suggest I use as a solution or starting point for a solution?
A: Sounds like you need a DAM system
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is Continuous Integration important for a solo developer? I've never used CI tools before, but from what I've read, I'm not sure it would provide any benefit to a solo developer that isn't writing code every day.
First - what benefits does CI provide to any project?
Second - who should use CI? Does it benefit all developers?
A: The basic concept of CI is that you have a system that builds the code and runs automated tests everytime someone makes a commit to the version control system. These tests would include unit and functional tests, or even behavior driven tests.
The benefit is that you know - immediately - when someone has broken the build.
This means either:
A. They committed code that prevents compilation, which would screw any one up
B. They committed code that broke some tests, which either means they introduced a bug that needs to be fixed, or the tests need to be updated to reflect the change in the code.
If you are a solo developer, CI isn't quite as useful if you are in a good habit of running your tests before a commit, which is what you should be doing. That being said, you could develop a bad habit of letting the CI do your tests for you.
As a solo programmer, it mainly comes down to discipline. Using CI is a useful skill to have, but you want to avoid developing any bad habits that wouldn't translate to a team environment.
A: The truth is, that continuous integration makes most sense in teams. Single developers can also get some advantages, you must decide yourself if they are enough to counter the time you invest into setting a CI-system up.
*
*If you forgot to checkin some needed file, the repository contains a broken version, even if it works on your machine. CI would detect that case.
*If your CI-server runs on a different machine, it can indicate dependencies on your build-environment. Means, the build and all tests can work on your dev-box, but on another machine some dependencies aren't fulfilled and the build breaks.
*Daily builds can indicate, that your older software doesn't work with the newest upgrade of the OS/compiler/library...
*If your CI-system has an archive of build-artifacts you can easy get an distribution of an older version of your software.
*Some CI have a nice interface to show you metrics about your build, have links to automatic generated documentation and stuff like that.
A: If you need to support multiple compilers then it's handy to have a CI build system to do all of that whilst you just develop in one IDE. My code builds with Vc6 through VS2008 in x86 and x64 builds on VS2005 & 8, so that's 7 builds per project per project configuration... Having a CI system means that I can develop in one IDE and let the CI system prove that all of the compilers that I support still build.
Likewise, if you are building libs that are used by multiple projects then CI will make sure they work with ALL of the projects rather than just the one that you're working with right now...
A: We use our CI system to do Release builds (as well as the usual automatic "on-commit" builds).
Being able to click a button that kicks off a Release build that steps through all the processes to release a setup is:
*
*fast (I can go straight on with other things, and it runs on a separate machine so it is not slowing me down);
*repetitive (it doesn't forget anything, including copying the setup to the release folder and notifying everyone who needs to know)
*dependable (no mistakes, unlike a human!).
In an Agile environment, where you expect to be delivering working software every 2-4 weeks, this is definitely worth having, even in a team of 1.
A: CI benefits a solo developer in the sense that you're aware if you forgot to check something in (because the build will be broken). The integration value of it is diminished when there are no other developers, though.
A: As other people have noted, CI does have advantages for a solo developer. But the question you have to ask yourself is; is it worth the overhead? If you're like me, it will probably take an hour or two to set up a CI system for a project, just because I'll have to allocate a server, set up all the networking, and install the software. Remember that the CI system will only be saving you a few seconds at a time. For a solo developer, these times aren't likely to add up to more than the time it took to do the CI setup.
However, if you've never set up a CI system before, I recommend doing it just for the sake of learning how to do it. It doesn't take so long that it isn't worth the learning experience.
A: The benefit of CI lies in the ability to discover early when a check in has broken the build. You can also run your suite of automated tests against the build, as well as run any kind of tools to give you metrics and such.
Obviously, this is very valuable when you have a team of commiters, not all of whom are diligent to check for breaking changes. As a solo developer, it is not quite as valuable. Presumably, you run your unit tests, and even maybe integration tests. However, I have seen a number of occasions where the developer forgets to checkin a file out of a set.
The CI build can also be thought of as your "release" build. The environment should be stable, and unaffected by whatever development gizmo you just add to your machine. It should allow you to always reproduce a build.
This can be valuable if you add a new dependency to your project, and forget to setup the release build environment to take that into account.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: Looking for a .NET Function that sums up number and instead of overflowing simply returns int.MaxValue I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that.
ie.
50 + 100 = 150
int.Max + 50 = int.Max and not int.Min + 50
A: This answer...
int penaltySum(int a, int b)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
fails the following test:
[TestMethod]
public void PenaltySumTest()
{
int x = -200000;
int y = 200000;
int z = 0;
Assert.AreEqual(z, penaltySum(x, y));
}
I would suggest implementing penaltySum() as follows:
private int penaltySum(int x, int y, int max)
{
long result = (long) x + y;
return result > max ? max : (int) result;
}
Notice I'm passing in the max value, but you could hardcode in the int.MaxValue if you would like.
Alternatively, you could force the arithmetic operation overflow check and do the following:
private int penaltySum(int x, int y, int max)
{
int result = int.MaxValue;
checked
{
try
{
result = x + y;
}
catch
{
// Arithmetic operation resulted in an overflow.
}
}
return result;
}
A: int penaltySum(int a, int b)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
Update: If your penalties can be negative, this would be more appropriate:
int penaltySum(int a, int b)
{
if (a > 0 && b > 0)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
if (a < 0 && b < 0)
{
return (int.MinValue - a > b) ? int.MinValue : a + b;
}
return a + b;
}
A: Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can LINQ (to SQL) do bitwise queries? I have a table of Users that includes a bitmask of roles that the user belongs to. I'd like to select users that belong to one or more of the roles in a bitmask value. For example:
select *
from [User]
where UserRolesBitmask | 22 = 22
This selects all users that have the roles '2', '4' or '16' in their bitmask. Is this possible to express this in a LINQ query? Thanks.
A: I think this will work, but I haven't tested it.Substitute the name of your DataContext object. YMMV.
from u in DataContext.Users
where UserRolesBitmask | 22 == 22
select u
A: As a side note though for my fellow googlers:
UserRolesBitmask | 22 == 22 selects all users that don't have any other flags (its not a filter, its like saying 1==1).
What you want is either:
*
*UserRolesBitmask & 22 == 22 which selects users which have all the roles in their bitmask or:
*UserRolesBitmask & 22 != 0 which selects users which have at least one of the roles in their bitmask
A: If that doesn't work you could always use ExecuteCommand:
DataContext.ExecuteCommand("select * from [User] where UserRolesBitmask | {0} = {0}", 22);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Change cardinality of item in C# dictionary I've got a dictionary, something like
Dictionary<Foo,String> fooDict
I step through everything in the dictionary, e.g.
foreach (Foo foo in fooDict.Keys)
MessageBox.show(fooDict[foo]);
It does that in the order the foos were added to the dictionary, so the first item added is the first foo returned.
How can I change the cardinality so that, for example, the third foo added will be the second foo returned? In other words, I want to change its "index."
A: If you read the documentation on MSDN you'll see this:
"The order in which the items are returned is undefined."
You can't gaurantee the order, because a Dictionary is not a list or an array. It's meant to look up a value by the key, and any ability to iterate values is just a convenience but the order is not behavior you should depend on.
A: You may be interested in the OrderedDicationary class that comes in System.Collections.Specialized namespace.
If you look at the comments at the very bottom, someone from MSFT has posted this interesting note:
This type is actually misnamed; it is not an 'ordered' dictionary as such, but rather an 'indexed' dictionary. Although, today there is no equivalent generic version of this type, if we add one in the future it is likely that we will name such as type 'IndexedDictionary'.
I think it would be trivial to derive from this class and make a generic version of OrderedDictionary.
A: I am not fully educated in the domain to properly answer the question, but I have a feeling that the dictionary sorts the values according to the key, in order to perform quick key search. This would suggest that the dictionary is sorted by key values according to key comparison. However, looking at object methods, I assume they are using hash codes to compare different objects considering there is no requirement on the type used for keys. This is only a guess. Someone more knowledgey should fill in with more detail.
Why are you interested in manipulating the "index" of a dictionary when its purpose is to index with arbitrary types?
A: I don't know if anyone will find this useful, but here's what I ended up figuring out. It seems to work (by which I mean it doesn't throw any exceptions), but I'm still a ways away from being able to test that it works as I hope it does. I have done a similar thing before, though.
public void sortSections()
{
//OMG THIS IS UGLY!!!
KeyValuePair<ListViewItem, TextSection>[] sortable = textSecs.ToArray();
IOrderedEnumerable<KeyValuePair<ListViewItem, TextSection>> sorted = sortable.OrderBy(kvp => kvp.Value.cardinality);
foreach (KeyValuePair<ListViewItem, TextSection> kvp in sorted)
{
TextSection sec = kvp.Value;
ListViewItem key = kvp.Key;
textSecs.Remove(key);
textSecs.Add(key, sec);
}
}
A: The short answer is that there shouldn't be a way since a Dictionary "Represents a collection of keys and values." which does not imply any sort of ordering. Any hack you might find is outside the definition of the class and may be liable to change.
You should probably first ask yourself if a Dictionary is really called for in this situation, or if you can get away with using a List of KeyValuePairs.
Otherwise, something like this might be useful:
public class IndexableDictionary<T1, T2> : Dictionary<T1, T2>
{
private SortedDictionary<int, T1> _sortedKeys;
public IndexableDictionary()
{
_sortedKeys = new SortedDictionary<int, T1>();
}
public new void Add(T1 key, T2 value)
{
_sortedKeys.Add(_sortedKeys.Count + 1, key);
base.Add(key, value);
}
private IEnumerable<KeyValuePair<T1, T2>> Enumerable()
{
foreach (T1 key in _sortedKeys.Values)
{
yield return new KeyValuePair<T1, T2>(key, this[key]);
}
}
public new IEnumerator<KeyValuePair<T1, T2>> GetEnumerator()
{
return Enumerable().GetEnumerator();
}
public KeyValuePair<T1, T2> this[int index]
{
get
{
return new KeyValuePair<T1, T2> (_sortedKeys[index], base[_sortedKeys[index]]);
}
set
{
_sortedKeys[index] = value.Key;
base[value.Key] = value.Value;
}
}
}
With client code looking something like this:
static void Main(string[] args)
{
IndexableDictionary<string, string> fooDict = new IndexableDictionary<string, string>();
fooDict.Add("One", "One");
fooDict.Add("Two", "Two");
fooDict.Add("Three", "Three");
// Print One, Two, Three
foreach (KeyValuePair<string, string> kvp in fooDict)
Console.WriteLine(kvp.Value);
KeyValuePair<string, string> temp = fooDict[1];
fooDict[1] = fooDict[2];
fooDict[2] = temp;
// Print Two, One, Three
foreach (KeyValuePair<string, string> kvp in fooDict)
Console.WriteLine(kvp.Value);
Console.ReadLine();
}
UPDATE: For some reason it won't let me comment on my own answer.
Anyways, IndexableDictionary is different from OrderedDictionary in that
*
*"The elements of an OrderedDictionary are not sorted in any way." So foreach's would not pay attention to the numerical indices
*It is strongly typed, so you don't have to mess around with casting things out of DictionaryEntry structs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Starting service as a user with no password I'm trying to start a service as a user and things work fine, until I try a user that doesn't have a password. Then, it fails to start (due to log-on error).
Am I doing something wrong or is this "by design"?
The code to register this service:
SC_HANDLE schService = CreateService(
schSCManager,
strNameNoSpaces,
strServiceName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
szPath,
NULL,
NULL,
NULL,
strUser,
(strPassword.IsEmpty())?NULL:strPassword);
A: It may be due to an OS security requirement or security policy. Check the security policies to see if anything is relevant there.
A: Yes, it was indeed related to the security policy. To elaborate:
http://technet.microsoft.com/en-us/library/bb457114.aspx
"If you want to disable the restriction against logging on to the network without a password, you can do so through Local Security Policy. The policy setting that controls blank password restriction can be modified using the Local Security Policy or Group Policy MMC snap-ins. You can use either tool to find this policy option at Security Settings\Local Policies\Security Options. The name of the policy is Accounts: Limit local account use of blank passwords to console logon only. It is enabled by default."
After disabling that, it all works fine.
A: You need to specify an empty string, not NULL if there is no password. NULL is not a valid empty string, "" is. Probably you should just pass strPassword for the last parameter.
SC_HANDLE schService = CreateService(
schSCManager,
strNameNoSpaces,
strServiceName,
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START,
SERVICE_ERROR_NORMAL,
szPath,
NULL,
NULL,
NULL,
strUser,
// change this line to:
strPassword.IsEmpty() ? L"" : strPassword);
// or maybe
strPassword);
A: Thank you - I've tried that first actually, but to no avail.
If I start services.msc, manually go into service properties and clear the 2 password fields, then press "Apply" and try to start it, it also fails.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do you check for permissions to write to a directory or file? I got a program that writes some data to a file using a method like the one below.
public void ExportToFile(string filename)
{
using(FileStream fstream = new FileStream(filename,FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine(text);
}
}
When running the program I get an error:
Unhandled Exception: System.UnauthorizedAccessException: Access to the path 'mypath' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access,
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access
FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolea
bFromProxy)
Question: What code do I need to catch this and how do I grant the access?
A: UPDATE:
Modified the code based on this answer to get rid of obsolete methods.
You can use the Security namespace to check this:
public void ExportToFile(string filename)
{
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");
}
}
else
{
//perform some recovery action here
}
}
As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)
A: Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:
string folder;
AuthorizationRuleCollection rules;
try {
rules = Directory.GetAccessControl(folder)
.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
} catch(Exception ex) { //Posible UnauthorizedAccessException
throw new Exception("No permission", ex);
}
var rulesCast = rules.Cast<FileSystemAccessRule>();
if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)
|| !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))
throw new Exception("No permission");
//Here I have permission, ole!
A: Since this isn't closed, i would like to submit a new entry for anyone looking to have something working properly for them... using an amalgamation of what i found here, as well as using DirectoryServices to debug the code itself and find the proper code to use, here's what i found that works for me in every situation... note that my solution extends DirectoryInfo object... :
public static bool IsReadable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow=false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadPermissions)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
public static bool IsWriteable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (Exception ex)
{ //Posible UnauthorizedAccessException
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteExtendedAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return me.IsReadable() && isAllow;
}
A: When your code does the following:
*
*Checks the current user has permission to do something.
*Carries out the action that needs the entitlements checked in 1.
You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.
Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.
Example (derived from Josh's example):
//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
//2. Attempt the action but handle permission changes.
try
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
writer.WriteLine("sometext");
}
}
catch (UnauthorizedAccessException ex)
{
//No permission.
//Either throw an exception so this can be handled by a calling function
//or inform the user that they do not have permission to write to the folder and return.
}
It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.
A: None of these worked for me.. they return as true, even when they aren't. The problem is, you have to test the available permission against the current process user rights, this tests for file creation rights, just change the FileSystemRights clause to 'Write' to test write access..
/// <summary>
/// Test a directory for create file access permissions
/// </summary>
/// <param name="DirectoryPath">Full directory path</param>
/// <returns>State [bool]</returns>
public static bool DirectoryCanCreate(string DirectoryPath)
{
if (string.IsNullOrEmpty(DirectoryPath)) return false;
try
{
AuthorizationRuleCollection rules = Directory.GetAccessControl(DirectoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
WindowsIdentity identity = WindowsIdentity.GetCurrent();
foreach (FileSystemAccessRule rule in rules)
{
if (identity.Groups.Contains(rule.IdentityReference))
{
if ((FileSystemRights.CreateFiles & rule.FileSystemRights) == FileSystemRights.CreateFiles)
{
if (rule.AccessControlType == AccessControlType.Allow)
return true;
}
}
}
}
catch {}
return false;
}
A: You can try following code block to check if the directory is having Write Access.
It checks the FileSystemAccessRule.
string directoryPath = "C:\\XYZ"; //folderBrowserDialog.SelectedPath;
bool isWriteAccess = false;
try
{
AuthorizationRuleCollection collection = Directory.GetAccessControl(directoryPath).GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
foreach (FileSystemAccessRule rule in collection)
{
if (rule.AccessControlType == AccessControlType.Allow)
{
isWriteAccess = true;
break;
}
}
}
catch (UnauthorizedAccessException ex)
{
isWriteAccess = false;
}
catch (Exception ex)
{
isWriteAccess = false;
}
if (!isWriteAccess)
{
//handle notifications
}
A: Its a fixed version of MaxOvrdrv's Code.
public static bool IsReadable(this DirectoryInfo di)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = di.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (UnauthorizedAccessException uae)
{
Debug.WriteLine(uae.ToString());
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Read) &&
rule.FileSystemRights.HasFlag(FileSystemRights.ReadAttributes) &&
rule.FileSystemRights.HasFlag(FileSystemRights.ReadData)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
public static bool IsWriteable(this DirectoryInfo me)
{
AuthorizationRuleCollection rules;
WindowsIdentity identity;
try
{
rules = me.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier));
identity = WindowsIdentity.GetCurrent();
}
catch (UnauthorizedAccessException uae)
{
Debug.WriteLine(uae.ToString());
return false;
}
bool isAllow = false;
string userSID = identity.User.Value;
foreach (FileSystemAccessRule rule in rules)
{
if (rule.IdentityReference.ToString() == userSID || identity.Groups.Contains(rule.IdentityReference))
{
if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) ||
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) ||
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Deny)
return false;
else if ((rule.FileSystemRights.HasFlag(FileSystemRights.Write) &&
rule.FileSystemRights.HasFlag(FileSystemRights.WriteAttributes) &&
rule.FileSystemRights.HasFlag(FileSystemRights.WriteData) &&
rule.FileSystemRights.HasFlag(FileSystemRights.CreateDirectories) &&
rule.FileSystemRights.HasFlag(FileSystemRights.CreateFiles)) && rule.AccessControlType == AccessControlType.Allow)
isAllow = true;
}
}
return isAllow;
}
A: Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is not a good thing. As a developer, I cannot use the "easy way out" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.
Like most posters of this type of question -- I initially felt it was "hackey", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.
Private Function CheckUserAccessLevel(folder As String) As Boolean
Try
Dim newDir As String = String.Format("{0}{1}{2}",
folder,
If(folder.EndsWith("\"),
"",
"\"),
"LookWhatICanDo")
Dim lookWhatICanDo = Directory.CreateDirectory(newDir)
Directory.Delete(newDir)
Return True
Catch ex As Exception
Return False
End Try
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "62"
}
|
Q: Python Date Comparisons I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to:
if (datetime.now() - self.timestamp) > 100
# Where 100 is either seconds or minutes
This generates a type error.
What is the proper way to do date time comparison in python? I already looked at WorkingWithTime which is close but not exactly what I want. I assume I just want the datetime object represented in seconds so that I can do a normal int comparison.
Please post lists of datetime best practices.
A: Compare the difference to a timedelta that you create:
if datetime.datetime.now() - timestamp > datetime.timedelta(seconds = 5):
print 'older'
A: Alternative:
if (datetime.now() - self.timestamp).total_seconds() > 100:
Assuming self.timestamp is an datetime instance
A: Use the datetime.timedelta class:
>>> from datetime import datetime, timedelta
>>> then = datetime.now() - timedelta(hours = 2)
>>> now = datetime.now()
>>> (now - then) > timedelta(days = 1)
False
>>> (now - then) > timedelta(hours = 1)
True
Your example could be written as:
if (datetime.now() - self.timestamp) > timedelta(seconds = 100)
or
if (datetime.now() - self.timestamp) > timedelta(minutes = 100)
A: You can use a combination of the 'days' and 'seconds' attributes of the returned object to figure out the answer, like this:
def seconds_difference(stamp1, stamp2):
delta = stamp1 - stamp2
return 24*60*60*delta.days + delta.seconds + delta.microseconds/1000000.
Use abs() in the answer if you always want a positive number of seconds.
To discover how many seconds into the past a timestamp is, you can use it like this:
if seconds_difference(datetime.datetime.now(), timestamp) < 100:
pass
A: You can subtract two datetime objects to find the difference between them.
You can use datetime.fromtimestamp to parse a POSIX time stamp.
A: Like so:
# self.timestamp should be a datetime object
if (datetime.now() - self.timestamp).seconds > 100:
print "object is over 100 seconds old"
A: Convert your time delta into seconds and then use conversion back to hours elapsed and remaining minutes.
start_time=datetime(
year=2021,
month=5,
day=27,
hour=10,
minute=24,
microsecond=0)
end_time=datetime.now()
delta=(end_time-start_time)
seconds_in_day = 24 * 60 * 60
seconds_in_hour= 1 * 60 * 60
elapsed_seconds=delta.days * seconds_in_day + delta.seconds
hours= int(elapsed_seconds/seconds_in_hour)
minutes= int((elapsed_seconds - (hours*seconds_in_hour))/60)
print("Hours {} Minutes {}".format(hours,minutes))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
}
|
Q: How to compile Clisp 2.46? When I try to compile the newest version of Clisp on Ubuntu 8.04 I always get this error after running configure:
Configure findings:
FFI: no (user requested: default)
readline: yes (user requested: yes)
libsigsegv: no, consider installing GNU libsigsegv
./configure: libsigsegv was not detected, thus some features, such as
generational garbage collection and
stack overflow detection in interpreted Lisp code
cannot be provided.
Please do this:
mkdir tools; cd tools; prefix=`pwd`/i686-pc-linux-gnu
wget http://ftp.gnu.org/pub/gnu/libsigsegv/libsigsegv-2.5.tar.gz
tar xfz libsigsegv-2.5.tar.gz
cd libsigsegv-2.5
./configure --prefix=${prefix} && make && make check && make install
cd ../..
./configure --with-libsigsegv-prefix=${prefix} --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
If you insist on building without libsigsegv, please pass
--ignore-absence-of-libsigsegv
to this script:
./configure --ignore-absence-of-libsigsegv --with-readline --with-unicode --with-module=i18n --with-module=gdbm --with-module=pcre --with-module=readline --with-module=regexp
I've tried doing as requested, but it didn't help: it seems to ignore the --with-libsigsegv-prefix option. I also tried putting installing libsigsegv in a standard location (/usr/local). Oh, and of course, Ubuntu tells me that libsigsegv and libsigsegv-dev are installed in the system.
I'd really like to be able to compile this version of Clips, as it introduces some serious improvements over the version shipped with Ubuntu (I'd also like to have PCRE).
A: Here are my notes from compiling CLISP on Ubuntu in the past, hope this helps:
sudo apt-get install libsigsegv-dev libreadline5-dev
# as of 7.10, Ubuntu's libffcall1-dev is broken and I had to get it from CVS
# and make sure CLISP didn't use Ubuntu's version.
sudo apt-get remove libffcall1-dev libffcall1
cvs -z3 -d:pserver:anonymous@cvs.sv.gnu.org:/sources/libffcall co -P ffcall
cd ffcall; ./configure; make
sudo make install
cvs -z3 -d:pserver:anonymous@clisp.cvs.sourceforge.net:/cvsroot/clisp co -P clisp
cd clisp
./configure --with-libffcall-prefix=/usr/local --prefix=/home/luis/Software
ulimit -s 16384
cd src; make install
A: If you look at 'config.log' it might tell you why configure is not finding libsigsegv
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: ACCESS_VIOLATION_BAD_IP I am trying to figure out a crash in my application.
WinDbg tells me the following: (using dashes in place of underscores)
LAST-CONTROL-TRANSFER: from 005f5c7e to 6e697474
DEFAULT-BUCKET-ID: BAD_IP
BUGCHECK-STR: ACCESS-VIOLATION
It is obvious to me that 6e697474 is NOT a valid address.
I have three questions:
1) Does the "BAD_IP" bucket ID mean "Bad Instruction Pointer?"
2) This is a multi-threaded application so one consideration was that the object whose function I was attempting to call went out of scope. Does anyone know if that would lead to the same error message?
3) What else might cause an error like this? One of my co-workers suggested that it might be a stack overflow issue, but WinDBG in the past has proven rather reliable at detecting and pointing these out. (not that I'm sure about the voodoo it does in the background to diagnose that).
A: Bad-IP is Bad Instruction Pointer. From the description of your problem, I would assume it is a stack corruption instead of a stack overflow.
A: I can think of the following things that could cause a jump to invalid address, in decreasing order of likelyhood:
*
*calling a member function on a deallocated object. (as you suspect)
*calling a member function of a corrupted object.
*calling a member function of an object with a corrupted vtable.
*a rouge pointer overwriting code space.
I'd start debugging by finding the code at 005f5c7e and looking at what objects are being accessed around there.
A: It may be helpful to ask, what could have written the string 'ttie' to this location? Often when you have bytes in the 0x41-0x5A, 0x61-0x7A ([a-zA-Z]) range, it indicates a string buffer overflow.
As to what was actually overwritten, it could be the return address, some other function pointer you're using, or occasionally that a virtual function table pointer (vfptr) in an object got overwritten to point to the middle of a string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a reasonable way to implement a cd command on VMS? I would like to be able to say things like
cd [.fred] and have my default directory go there,
and my prompt change to indicate the full path to my current location.
A: Just type
cd:==set default
at the command prompt. You can also put this in your LOGIN.COM file, but be sure to put a $ in front, i.e.
$ cd:==set default
To change your prompt to show your default, something like this may work up to a point
$ set prompt='f$env("default")'
There is a problem though with the fact that VMS prompt has maximum 32 characters, and your default might be longer than that. Have a look at this page for a way around that problem.
A: My DCL is really rusty, but can't you create an alias for SET DEFAULT named CD?
A: Here's my setup:
You need 2 files (typed below) : godir.com and prompt.com in your sys$login
You may define a symbole
CD == "@sys$login:godir.com"
But I suggest you to use something else... (ie SD == "@sys$login:godir.com")
I modify the help text. It was in french...
You will have to retype the escape caracters into godir.com
Replace ESC by the real escape into GRAPH_BOUCLE: (see bottom of godir.com)
Then to use it:
SD ?
SD a_directory
...
Hope it helps.
Here's prompt.com
$ noeud = f$trnlnm("SYS$NODE") - "::"
$ if noeud .eqs. "HQSVYC" then noeud = "¥"
$!
$ noeud = noeud - "MQO"
$ def_dir = f$directory()
$ def_dir = f$extract(1,f$length(def_dir)-2,def_dir)
$boucle:
$ i = f$locate(".",def_dir)
$ if i .eq. f$length(def_dir) then goto fin_boucle
$ def_dir = f$extract(i+1,f$length(def_dir)-1,def_dir)
$ goto boucle
$!
$fin_boucle:
$! temp = "''noeud' ''def_dir' " + "''car_prompt'"
$ temp = "''noeud'" -
+ " ''def_dir' " -
+ "''f$logical(""environnement"")'" -
+ "''car_prompt'"
$! temp = "''noeud'" -
$! + "''def_dir'" -
$! + "''f$logical(""environnement"")'" -
$! + "''car_prompt'"
$ set prompt="''temp' "
$!
$! PROMPT.COM
$!
Here's godir.com
$!
$! GODIR.COM
$!
$ set noon
$ set_prompt = "@sys$login:prompt.com"
$ if f$type(TAB_DIR_N) .nes. "" then goto 10$
$ goto 20$
$ INIT:
$ temp2 = "INIT"
$ CLEAR:
$ temp = 0
$
$ INIT2:
$ temp = temp +1
$ if temp .gt. TAB_DIR_N then goto INIT3
$ delete/symb/glo TAB_DIR_'temp'
$ goto INIT2
$
$ INIT3:
$ P1 = ""
$ if temp2 .eqs. "INIT" then goto 20$
$ delete/symb/glo TAB_DIR_N
$ delete/symb/glo TAB_DIR_P
$ delete/symb/glo TAB_DIR_I
$ exit
$
$ 20$:
$ TAB_DIR_N == 1
$ TAB_DIR_P == 1
$ TAB_DIR_I == 1
$ if "''car_prompt'" .eqs. "" then car_prompt == ">"
$ TAB_DIR_1 == f$parse(f$dir(),,,"device")+f$dir()
$ 10$:
$ if P1 .eqs. "" then goto LIST
$ if P1 .eqs. "?" then goto SHOW
$ if P1 .eqs. "." then P1 = "[]"
$ if P1 .eqs. "^" then goto SET_CUR
$ if (P1 .eqs. "<") .or. (P1 .eqs. ">") .or. -
(P1 .eqs. "..") then P1 = "[-]"
$ if (P1 .eqs. "*") .or. (P1 .eqs. "0") then goto HOME
$ if (P1 .eqs. "P") .or. (P1 .eqs. "p") then goto PREVIOUS
$ if (P1 .eqs. "H") .or. (P1 .eqs. "h") then goto HELP
$ if (P1 .eqs. "S") .or. (P1 .eqs. "s") then goto SET_PROMPT
$ if (P1 .eqs. "G") .or. (P1 .eqs. "g") then goto SET_PROMPT_GRAPHIC
$ temp2 = ""
$ if (P1 .eqs. "~INIT") .or. (P1 .eqs. "~init") then goto INIT
$ if (P1 .eqs. "~CLEAR") .or. (P1 .eqs. "~clear") then goto CLEAR
$
$! *** Specification par un numero
$ temp = f$extract(0,1,P1)
$ if temp .eqs. "-" then goto DELETE
$ temp2 = ""
$boucle_reculer:
$ if temp .nes. "\" then goto fin_reculer
$ temp2 = temp2 + "-."
$ P1 = P1 - "\"
$ temp = f$extract(0,1,P1)
$ goto boucle_reculer
$!
$fin_reculer:
$ P1 = temp2 + P1
$ if (P1 .lts. "0") .or. (P1 .gts. "9") then goto SPEC
$ temp = f$integer("''P1'")
$ if temp .eq. 0 then goto HOME
$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR
$ TAB_DIR_P == TAB_DIR_I
$ TAB_DIR_I == temp
$ goto SET2
$
$ SPEC:
$! *** Specification relative de directory
$
$ temp = f$parse("[.''P1']","missing.mis")
$ DD = f$extract(0,f$locate("]",temp)+1,temp)
$ if DD .nes. "" then goto SET1
$
$! *** Specification de directory principal
$
$ temp = f$parse("[''P1']","missing.mis")
$ DD = f$extract(0,f$locate("]",temp)+1,temp)
$ if DD .nes. "" then goto SET1
$
$ temp = f$parse("[''P1']","sys$login:missing.mis")
$ DD = f$extract(0,f$locate("]",temp)+1,temp)
$ if DD .nes. "" then goto SET1
$
$! *** Specification exacte de directory
$
$ temp = f$parse(P1,"missing.mis")
$ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR
$ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "]["
$ DD = f$extract(0,f$locate("]",temp)+1,temp)
$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW
$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2
$ if DD .nes. "" then goto SET1
$
$ temp = f$parse(P1,"sys$login:missing.mis")
$ if f$locate("]"+P1,temp) .ne. f$length(temp) then goto ERR
$ if f$locate(".][",temp) .ne. f$length(temp) then temp = temp - "]["
$ DD = f$extract(0,f$locate("]",temp)+1,temp)
$! if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SHOW
$ if DD .eqs. TAB_DIR_'TAB_DIR_I' then goto SET2
$ if DD .nes. "" then goto SET1
$
$ goto ERR
$
$ HOME:
$ DD = "SYS$LOGIN"
$
$ SET1:
$ Set On
$ On error then goto ERR1
$ set message/nofac/noid/nosever/notext
$ Set def 'DD'
$ dir/output=nl:
$ set message/fac/id/sever/text
$ temp = f$parse(f$dir()) - ".;"
$ if temp .nes. "" then goto SET1F
$ ERR1:
$ set message/fac/id/sever/text
$ temp = TAB_DIR_'TAB_DIR_I'
$ Set def 'temp'
$ goto ERR
$ SET1F:
$ I = 0
$ LOOP1:
$ I = I + 1
$ if temp .eqs. TAB_DIR_'I' then goto FOUND
$ if I .lt. TAB_DIR_N then goto LOOP1
$
$ TAB_DIR_N == TAB_DIR_N + 1
$ TAB_DIR_P == TAB_DIR_I
$ TAB_DIR_I == TAB_DIR_N
$ TAB_DIR_'TAB_DIR_I' == temp
$ goto SHOW
$
$ FOUND:
$ TAB_DIR_P == TAB_DIR_I
$ TAB_DIR_I == I
$ goto SET2
$
$ SET_PROMPT:
$ car_prompt == "''P2'"
$ set_prompt
$ exit
$
$ PREVIOUS:
$ temp = TAB_DIR_P
$ TAB_DIR_P == TAB_DIR_I
$ TAB_DIR_I == temp
$
$ SET_CUR:
$ SET2:
$ DD = TAB_DIR_'TAB_DIR_I'
$ set def 'DD'
$
$ SHOW:
$ temp = TAB_DIR_'TAB_DIR_I'
$ ws " ''TAB_DIR_I' * ''temp'"
$ set_prompt
$ exit
$
$ LIST:
$ I = 0
$ LOOP2:
$ I = I + 1
$ temp = TAB_DIR_'I'
$ if I .eq. TAB_DIR_I then goto L_CUR
$ if I .eq. TAB_DIR_P then GOTO L_PRE
$ ws " ''I' = ''temp'"
$ goto F_LOOP2
$ L_CUR:
$ ws " ''I' * ''temp'"
$ goto F_LOOP2
$ L_PRE:
$ ws " ''I' + ''temp'"
$
$ F_LOOP2:
$ if I .lt. TAB_DIR_N then goto LOOP2
$ set_prompt
$
$ exit
$
$ DELETE:
$ P1 = P1 - "-"
$ temp2 = f$integer("''P1'")
$ DEL_1:
$ temp = f$integer("''P1'")
$ if (temp .lt. 1) .or. (temp .gt. TAB_DIR_N) then goto ERR
$ if temp .eq. TAB_DIR_I then goto ERR
$ if temp .lt. TAB_DIR_I then TAB_DIR_I == TAB_DIR_I - 1
$ if temp .eq. TAB_DIR_P then TAB_DIR_P == TAB_DIR_I
$ if temp .lt. TAB_DIR_P then TAB_DIR_P == TAB_DIR_P - 1
$ LOOP3:
$ if temp .eq. TAB_DIR_N then goto F_LOOP3
$ temp3 = temp + 1
$ TAB_DIR_'temp' == TAB_DIR_'temp3'
$ temp = temp + 1
$ goto LOOP3
$ F_LOOP3:
$ delete/symb/glo tab_dir_'tab_dir_n'
$ TAB_DIR_N == TAB_DIR_N - 1
$ if P2 .eqs. "" then goto FIN_DEL
$ temp2 = temp2 + 1
$ if temp2 .le. f$integer("''P2'") then goto DEL_1
$ FIN_DEL:
$ goto LIST
$
$ ERR:
$ ws "*** ERREUR ***"
$ exit
$
$ HELP:
$ ws " H Show this menu"
$ ws " null Show a list of directories"
$ ws " ? Show current directory"
$ ws " < or [-] or"
$ ws " > or .. Remonte d'un niveau de directory"
$ ws " * ou 0 Return to SYS$LOGIN"
$ ws " P Last directory "
$ ws " . ou [] Set cureent directory"
$ ws " ^ Return to next directory"
$ ws " x Set def to number x"
$ ws " -x Remove the number x"
$ ws " -x y Remove from x to y"
$ ws " ddd Set def to [ddd] or [.ddd] or ddd:"
$ ws " \ddd Set def to [-.ddd]"
$ ws " S "">>"" Modify prompt for >>"
$ ws " ~INIT Initialize to current directory "
$ ws " (and delete all others references)"
$ ws " ~CLEAR Remove all references
$ ws ""
$
$ exit
$
$ SET_PROMPT_GRAPHIC:
$ temp = "''P2'"
$ i=0
$ car_prompt == ""
$ GRAPH_BOUCLE:
$ t=f$extract(i,1,temp)
$ if (t .eqs. "e") .or. (t .eqs. "E") then t="ESC"
$ if (t .eqs. "g") .or. (t .eqs. "G") then t="ESC(0"
$ V° (} .L-_. "N") .-_. (} .L-_. "H") }NL+ }="ESC(B"
$ car_prompt == car_prompt + t
$ i = i+1
$ if i .lts. f$length(temp) then goto GRAPH_BOUCLE
$
$ set_prompt
$ exit
A: Use HGSD which implements an SD (short for SET DEFAULT) command. Just google it. It is an improved version by Hunter Goatley of an older implementation.
The only thing it cannot handle (yet), are logicals with multiple translations. Other than that, It works like a charm, and you do not need to type in complete directory names. You can even move to the next directory on the same level.
It can also set the prompt if you have the right privileges in one go, so your prompt will reflect your default directory, just like in the old days on DOS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Combining two executables I have a command line executable that alters some bits in a file that i want to use from my program.
Is it possible to create my own executable that uses this tool and distribute only one executable?
[edit] Clarification:
The command line tool takes an offset and some bits and changes the bits at this offset in a given file. So I want to create a patcher for an application that changes specific bits to a specific value, so what I can do i write something like a batch file to do it but i want to create an executable that does it, i.e. embed the tool into a wrapper program that calls it with specific values.
I can code wrapper in (windows) c\c++, asm but no .net please.
A: It would be easier to roll your own implementation of this program than to write the wrapper; it sounds like it is trivial -- just open the file, seek to the right location, write your bits, close the file, you're done.
A: The easiest way is to embed this exe into your own and write it to disk to run it.
A: You can add the executable as a binary stream resource in your executable and when you need it you can extract it in a temporary folder and create new process with the temporary file.
The exact code you need to do this depends on whether you are writing .Net or C++ code.
A: Short answer: No.
Less short answer: Not unless it's an installer or a self extracting archive executeable.
Longer, speculative answer: If the file system supports alternate data streams, you could possibly add a stream containing the utility to your program, then your program could access it's own alternate data stream, extracting the utility when you need it. Ahaha.
A: You could append the one executable onto the end of the other and write some code to unpack it to a temporary folder.
I've done a similar thing before but with a configuration file and some bitmaps appended to an EXE in Windows. The way I did it was to firstly append my stuff onto the end of the EXE and then write a little struct after that which contains the file offset of the data which in your case would be the offset of the 2nd exe.
When running your app, seek to the end of the file minus the size of the struct, extract the file offset and copy the 2nd exe to a temporary folder, then launch it.
OK, here is a little more details as requestd. This is some pseudo-code to create the combined EXE. This is a little utility you run after compiling your main EXE:
Open destination file
Open main exe as a binary file
Copy main exe to destination file
offset = size of main exe
Open 2nd exe as a binary file
Copy 2nd exe to the output file
Write the offset to the output file
Now for the extraction procedure. This goes in your main EXE:
Find the location of our own EXE file (GetModuleFileName() under Windows)
Open the file in binary mode
Seek to the end minus sizeof(offset) (typically 4 bytes)
Read the offset value
Seek to the offset position
Open a temporary file in binary mode
Read bytes from the main EXE and write to the temporary file
Launch the temporary file
A: I think the easiest way to do this for your purposes is probably to use a self extracting executable package. For example, use a tool like Paquet Builder which will package the exe (and any other files you want) and can be configured to call the exe or a batch file or whatever else you want when the user unpacks the self-extracting executable.
A: If the exe was built to be relocatable (essentiall linker flag /fixed:no), you can actually do a LoadLibrary on it, get the base address, set up a call chain and call (jump) into it. It would not be worth the effort, and very few exe's are built this way so you would have to have the code to rebuild it, at which point you wouldn't be in this exercise.
So... No.
I'm more intrigued by the developer who doesn't mind writing in C/C++/asm, but 'not .net' - but is apparently stymied by fopen/fseek/fwrite - since that's about all the program you describe sounds like it's doing.
A: I think this is also possible by using AutoIt's FileInstall function. For this you'll have to setup AutoIt, create a script with the FileInstall function to include the who exe's and then use f.i. the function RunWait to execute them. Compile to an exe and you should be done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I protect quotes in a batch file? I want to wrap a Perl one-liner in a batch file. For a (trivial) example, in a Unix shell, I could quote up a command like this:
perl -e 'print localtime() . "\n"'
But DOS chokes on that with this helpful error message:
Can't find string terminator "'" anywhere before EOF at -e line 1.
What's the best way to do this within a .bat file?
A: In Windows' "DOS prompt" (cmd.exe) you need to use double quotes not single quotes. For inside the quoted Perl code, Perl gives you a lot of options. Three are:
perl -e "print localtime() . qq(\n)"
perl -e "print localtime() . $/"
perl -le "print ''.localtime()"
If you have Perl 5.10 or newer:
perl -E "say scalar localtime()"
Thanks to J.F. Sebastian's comment.
A: For general batch files under Windows NT+, the ^ character escapes lots of things (<>|&), but for quotes, doubling them works wonders:
C:\>perl -e "print localtime() . ""\n"""
Thu Oct 2 09:17:32 2008
A: For Perl stuff on Windows, I try to use the generalized quoting as much as possible so I don't get leaning toothpick syndrome. I save the quotes for the stuff that DOS needs:
perl -e "print scalar localtime() . qq(\n)"
If you just need a newline at the end of the print, you can let the -l switch do that for you:
perl -le "print scalar localtime()"
For other cool things you can do with switches, see the perlrun documentation.
A: In DOS, you use the "" around your Perl command. The DOS shell doesn't do single quotes like the normal Unix shell:
perl -e "print localtime();"
A: First, any answer you get to this is command-specific, because the DOS shell doesn't parse the command-line like a uniq one does; it passes the entire unparsed string to the command, which does any splitting. That said, if using /subsystem:console the C runtime provides splitting before calling main(), and most commands use this.
If an application is using this splitting, the way you type a literal double-quote is by doubling it. So you'd do
perl -e "print localtime() . ""\n"""
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do you access Control.ViewState with a dynamically added Control subclass? We have created a control that needs to persist data via the ViewState property of the Control class. Our class subclasses control strictly to get access to the ViewState property (it's protected on the Page object). We are adding the control to Page.Controls in OnInit, and then attempt to set the ViewState property in OnPreLoad.
When we decode and examine the ViewState of the page, our values have not been written out, and are thus not available for later retrieval.
Does anyone know how we can get our control to participate in the ViewState process?
A: The issue is adding the control to the Page directly. Unfortunately this is too high up the controls hierarchy to participate in the Forms ViewState Handling. If you add the control onto the actual ASPNet Form's Controls collection somewhere then it will successfully participate in LoadViewStateRecursive and SaveViewStateRecursive.
A: Try creating your control in OnInit, then add it to the Page.Controls during OnLoad.
A: ViewState isn't loaded until after OnInit, but before OnLoad.
Here's a rough outline of the Page Life-Cycle(GregMac) posted this in a response to an earlier question of mine.
*Initialize
*LoadViewState
*Load Postback Data
*Call control Load events
*Call Load event
*Call control events
*Control PreRender
*PreRender
*SaveViewState
*Unload
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Expanding a Region will expand children in Visual Studio I am developing an ASP.NET Ajax form, and decided to make most of the site in one page, because it isn't a very involved site (it's more of a form). In the codebehind, I have been making my code more organized by adding regions to it (inside are the click events of the controls, etc).
When I expand a region, all the subroutines and child regions are expanded. Is there an option in Visual Studio to prevent this from happening? I'd like to be able to expand a region, and then expand the region or subroutine I'd like to edit, rather than contracting all the subroutines and child regions to prevent me from getting distracted by my fat code. :)
A: These keyboard shortcuts should help. I believe you can collapse all regions and then, when you open one, it's child regions will remain collapsed. Not tested though.
Ctrl + M, Ctrl + M Collapse or expand the block you?re currently in.
Ctrl + M, Ctrl + O Collapse all blocks in the file
Ctrl + M, Ctrl + L Expand all blocks in the file
A: Try the "key chord": Ctrl+M, Ctrl+O, then use Ctrl+M, Ctrl+M to expand one at a time.
Although, I do think regions are evil, and you should do something about the fat code ;)
A: VS does not expand all nested regions by default. It keeps the state of the nested regions. There's no option in VS to have all nested regions collapsed or expanded explicitly when expanding a region.
You could use Ctrl-M Ctrl-L to toggle all regions in the file to collapsed and then use Ctrl-M Ctrl-M to navigate your way down the regions tree to the one you need.
You could also make use of the partial classes and split your codebehind in several source files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How long would it take to setup a new CI repository? I wonder how long it would usually take for:
*
*Professional
*Average
*Beginner
to setup and configure CI for a new project?
A: I have never set up CI before, which puts me squarely in your "Beginner" category. Your question nudged me to try and setup a CI system for my projects; something which I've always avoided, because I thought it would cost me a lot of effort and time.
It took me all of 20 minutes.
I used a fantastic project called CInABox (Continuous Integration in a Box). It consists of two simple scripts which download and compile Ruby and download, install and configure CruiseControl.rb for Ubuntu 8.04.
In just 20 minutes, I downloaded Ubuntu JeOS 8.04, configured a VirtualBox VM, installed Ubuntu in that VM, setup networking, installed Ruby, installed CruiseControl.rb, added my first project to CC.rb and watched the light go green! The most time was actually spent downloading Ubuntu, downloading Ruby and installing Ubuntu. The actual CI setup took less than 5 minutes.
Don't let the name fool you: CC.rb is written in Ruby, but you can build anything with it. In the default configuration, it assumes that you are using rake to build your project, but by setting just one configuration option, you can just as well use a shell script.
A: It depends on how much other infrastructure you already have in place and whether you have issues tying everything together. Even with that in mind, you should be able to get TeamCity and all the infrastructure up and and running within a day or so if you have a decent idea of what you're doing. The documentation is pretty good for TeamCity and should get you past any bumps.
A: It depends on may factors:
*
*What features of CI do you want to use.
*Have you project installed in your CI environment already.
*What type of project. How easily it can be installed on fresh environment.
just to say a few.
I think that if project is not a trivial, then all this time spent for the CI environment is worth the price. Whether it is 20 minutes or 3 days.
A: CI Factory
TeamCity
CC.NET sample configs
Try.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Flex: Why can't I handle certain events? In certain cases, I can't seem to get components to receive events.
[edit]
To clarify, the example code is just for demonstration sake, what I was really asking was if there was a central location that a listener could be added, to which one can reliably dispatch events to and from arbitrary objects.
I ended up using parentApplication to dispatch and receive the event I needed to handle.
[/edit]
If two components have differing parents, or as in the example below, one is a popup, it would seem the event never reaches the listener (See the method "popUp" for the dispatch that doesn't work):
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="absolute"
initialize="init()">
<mx:Script>
<![CDATA[
import mx.controls.Menu;
import mx.managers.PopUpManager;
// Add listeners
public function init():void
{
this.addEventListener("child", handleChild);
this.addEventListener("stepchild", handleStepchild);
}
// Handle the no pop button event
public function noPop(event:Event):void
{
dispatchEvent(new Event("child"));
}
// Handle the pop up
public function popUp(event:Event):void
{
var menu:Menu = new Menu();
var btnMenu:Button = new Button();
btnMenu.label = "stepchild";
menu.addChild(btnMenu);
PopUpManager.addPopUp(menu, this);
// neither of these work...
this.callLater(btnMenu.dispatchEvent, [new Event("stepchild", true)]);
btnMenu.dispatchEvent(new Event("stepchild", true));
}
// Event handlers
public function handleChild(event:Event):void
{
trace("I handled child");
}
public function handleStepchild(event:Event):void {
trace("I handled stepchild");
}
]]>
</mx:Script>
<mx:VBox>
<mx:Button label="NoPop" id="btnNoPop" click="noPop(event)"/>
<mx:Button label="PopUp" id="btnPop" click="popUp(event)"/>
</mx:VBox>
</mx:Application>
I can think of work-arounds, but it seems like there ought to be some central event bus...
Am I missing something?
A: Above is correct.
You are dispatching the event from btnMenu, but you are not listening for events on btnMenu - you are listening for events on the Application.
Either dispatch from Application:
dispatchEvent(new Event("stepchild", true));
or listen on the btnMenu
btnMenu.addEventListener("stepchild",handleStepChild);
btnMenu.dispatchEvent(new Event("stepchild",true));
A: You are attaching the listener to this when the event is getting dispatched from btnMenu.
This should work:
dispatchEvent(new Event("stepchild", true));
ps. There is really no reason to put an unnecessary 'this' everywhere, unless it's explicitly required to overcome scope issues. In this case you can just leave every this out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Impersonating a User in Asp.Net My DBA requires all database access to be done through trusted domain account. This can be done if you set the web.config . This requires the user to login or to be on the domain for IE pass the credentials through. I want to impersonate a user by using code. I am using the code found in this knowledgebase article:
http://support.microsoft.com/kb/306158
It works great, I pass in the credentials, impersonate the user, then make the call to the database and data is returned.
The problem is if I go to another page, I lose my impersonated credentials. This means every time I make a call to the database I have to run the impersonate code.
If IIS can impersonate a domain user for all pages, then why can I not impersonate a user while using code?
It seems to be something with thread context switching. I have tried setting the alwaysFlowImpersonatingPolicy in the Aspnet.config file and it did not work.
http://msdn.microsoft.com/en-us/library/ms229553.aspx
Any suggestion? Is it even possible to do what I want?
A: Impersonation occurs at the level of the thread. Impersonation causes the access token of the thread, which is usually inherited from the process, to be replaced with another. The best practice is to revert the effect of impersonation and thus the token as soon as you are done with the operation(s) for which it was needed. The story is no different with IIS or ASP.NET. Each request is usually handled by a distinct thread so you will have to make each thread impersonate the user.
This means every time I make a call to
the database I have to run the
impersonate code.
So that is correct.
If IIS can impersonate a domain user
for all pages, then why can I not
impersonate a user while using code?
IIS does not do it any differently and so it may only be a perceived illusion. It cannot impersonate a user for all pages unless all pages are being served by the same thread and where the impersonated token has never been reverted as each page is served.
It seems to be something with thread
context switching.
Not really. Unless you are doing asynchronous processing (which you don't state you do in your question), the flow of the impersonation context won't be relevant. You only need to worry about flowing the impersonation context if you are causing a thread switch either directly or indirectly during the processing of a single request. If you want that the work done by a secondary (worker) thread continues to occur under the impersonation context of the primary one then you need to make sure the secondary thread borrows the impersonation token. In .NET Framework 1.1, you would have to take great care and manually orchestrate the flow of the impersonation context. With .NET 2.0, however, the ExecutionContext API was introduced and does a lot of the heavy-lifting.
A: The reason you're losing the impersonation context is because each time a new page request ends the impersonation context will go out of scope.
As per the docs <alwaysFlowImpersonationPolicy> is used to ensure the same impersonation context is maintained across async calls. For example when making an async call to a remote web service the callback impersonation context is the same one as the initiating thread. In the case of ASP.NET the impersonation context would only flow for the lifetime of the page request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to unit test immutable class constructors? I have an immutable class with some private fields that are set during the constructor execution. I want to unit test this constructor but I'm not sure the "best practice" in this case.
Simple Example
This class is defined in Assembly1:
public class Class2Test
{
private readonly string _StringProperty;
public Class2Test()
{
_StringProperty = ConfigurationManager.AppSettings["stringProperty"];
}
}
This class is defined in Assembly2:
[TestClass]
public class TestClass
{
[TestMethod]
public void Class2Test_Default_Constructor()
{
Class2Test x = new Class2Test();
//what do I assert to validate that the field was set properly?
}
}
EDIT 1: I have answered this question with a potential solution but I'm not sure if it's the "right way to go". So if you think you have a better idea please post it.
This example isn't really worth testing, but assume the constructor has some more complex logic. Is the best approach to avoid testing the constructor and to just assume it works if all the tests for the methods on the class work?
EDIT 2: Looks like I made the sample a little to simple. I have updated it with a more reasonable situation.
A: Nothing, unless you are using that field. You don't want over-specification via tests. In other words, there is no need to test that the assignment operator works.
If you are using that field in a method or something, call that method and assert on that.
Edit:
assume the constructor has some more complex logic
You shouldn't be performing any logic in constructors.
Edit 2:
public Class2Test()
{
_StringProperty = ConfigurationManager.AppSettings["stringProperty"];
}
Don't do that! =) Your simple unit test has now become an integration test because it depends on the successful operation of more than one class. Write a class that handles configuration values. WebConfigSettingsReader could be the name, and it should encapsulate the ConfigurationManager.AppSettings call. Pass an instance of that SettingsReader class into the constructor of Class2Test. Then, in your unit test, you can mock your WebConfigSettingsReader and stub out a response to any calls you might make to it.
A: I have properly enabled [InternalsVisibleTo] on Assembly1 (code) so that there is a trust relationship with Assembly2 (tests).
public class Class2Test
{
private readonly string _StringProperty;
internal string StringProperty { get { return _StringProperty; } }
public Class2Test(string stringProperty)
{
_StringProperty = stringProperty;
}
}
Which allows me to assert this:
Assert.AreEqual(x.StringProperty, "something");
The only thing I don't really like about this is that it's not clear (without a comment) when you are just looking at Class2Test what the purpose of the internal property is.
Additional thoughts would be greatly appreciated.
A: In your edit, you now have a dependancy on ConfigurationManager that is hard to test.
One suggestion is to extract an interface to it and then make the Class2Test ctor take an IConfigManager instance as a parameter. Now you can use a fake/mock object to set up its state, such that any methods that rely on Configuration can be tested to see if they utilize the correct values...
public interface IConfigManager
{
string FooSetting { get; set; }
}
public class Class2Test
{
private IConfigManager _config;
public Class2Test(IConfigManager configManager)
{
_config = configManager;
}
public void methodToTest()
{
//do something important with ConfigManager.FooSetting
var important = _config.FooSetting;
return important;
}
}
[TestClass]
public class When_doing_something_important
{
[TestMethod]
public void Should_use_configuration_values()
{
IConfigManager fake = new FakeConfigurationManager();
//setup state
fake.FooSetting = "foo";
var sut = new Class2Test(fake);
Assert.AreEqual("foo", sut.methodToTest());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can one close HTML tags in Vim quickly? It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:
<html><head><title>This is a title</title></head></html>
How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.
Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.
A: I find using the xmledit plugin pretty useful. it adds two pieces of functionality:
*
*When you open a tag (e.g. type <p>), it expands the tag as soon as you type the closing > into <p></p> and places the cursor inside the tag in insert mode.
*If you then immediately type another > (e.g. you type <p>>), it expands that into
<p>
</p>
and places the cursor inside the tag, indented once, in insert mode.
The xml vim plugin adds code folding and nested tag matching to these features.
Of course, you don't have to worry about closing tags at all if you write your HTML content in Markdown and use %! to filter your Vim buffer through the Markdown processor of your choice :)
A: Here is yet another simple solution based on easily foundable Web writing:
*
*Auto closing an HTML tag
:iabbrev </ </<C-X><C-O>
*Turning completion on
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
A: allml (now Ragtag ) and Omni-completion ( <C-X><C-O> )
doesn't work in a file like .py or .java.
if you want to close tag automatically in those file,
you can map like this.
imap <C-j> <ESC>F<lyt>$a</^R">
( ^R is Contrl+R : you can type like this Control+v and then Control+r )
(| is cursor position )
now if you type..
<p>abcde|
and type ^j
then it close the tag like this..
<p>abcde</p>|
A: I like minimal things,
imap ,/ </<C-X><C-O>
A: I find it more convinient to make vim write both opening and closing tag for me, instead of just the closing one. You can use excellent ragtag plugin by Tim Pope. Usage looks like this (let | mark cursor position)
you type:
span|
press CTRL+x SPACE
and you get
<span>|</span>
You can also use CTRL+x ENTER instead of CTRL+x SPACE, and you get
<span>
|
</span>
Ragtag can do more than just it (eg. insert <%= stuff around this %> or DOCTYPE). You probably want to check out other plugins by author of ragtag, especially surround.
A: Building off of the excellent answer by @KeithPinson (sorry, not enough reputation points to comment on your answer yet), this alternative will prevent the autocomplete from copying anything extra that might be inside the html tag (e.g. classes, ids, etc...) but should not be copied to the closing tag.
UPDATE I have updated my response to work with filename.html.erb files.
I noticed my original response didn't work in files commonly used in Rails views, like some_file.html.erb when I was using embedded ruby (e.g. <p>Year: <%= @year %><p>). The code below will work with .html.erb files.
inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwo</<C-r>"><Esc>O
Sample usage
Type:
<div class="foo">[Tab]
Result:
<div class="foo">
|
<div>
where | indicates cursor position
And as an example of adding the closing tag inline instead of block style:
inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwh/[^%]><CR>la</<C-r>"><Esc>F<i
Sample usage
Type:
<div class="foo">[Tab]
Result:
<div class="foo">|<div>
where | indicates cursor position
It's true that both of the above examples rely on >[Tab] to signal a closing tag (meaning you would have to choose either inline or block style). Personally, I use the block-style with >[Tab] and the inline-style with >>.
A: Check this out..
closetag.vim
Functions and mappings to close open HTML/XML tags
https://www.vim.org/scripts/script.php?script_id=13
I use something similar.
A: If you're doing anything elaborate, sparkup is very good.
An example from their site:
ul > li.item-$*3 expands to:
<ul>
<li class="item-1"></li>
<li class="item-2"></li>
<li class="item-3"></li>
</ul>
with a <C-e>.
To do the example given in the question,
html > head > title{This is a title}
yields
<html>
<head>
<title>This is a title</title>
</head>
</html>
A: There is also a zencoding vim plugin: https://github.com/mattn/zencoding-vim
tutorial: https://github.com/mattn/zencoding-vim/blob/master/TUTORIAL
Update: this now called Emmet: http://emmet.io/
An excerpt from the tutorial:
1. Expand Abbreviation
Type abbreviation as 'div>p#foo$*3>a' and type '<c-y>,'.
---------------------
<div>
<p id="foo1">
<a href=""></a>
</p>
<p id="foo2">
<a href=""></a>
</p>
<p id="foo3">
<a href=""></a>
</p>
</div>
---------------------
2. Wrap with Abbreviation
Write as below.
---------------------
test1
test2
test3
---------------------
Then do visual select(line wize) and type '<c-y>,'.
If you request 'Tag:', then type 'ul>li*'.
---------------------
<ul>
<li>test1</li>
<li>test2</li>
<li>test3</li>
</ul>
---------------------
...
12. Make anchor from URL
Move cursor to URL
---------------------
http://www.google.com/
---------------------
Type '<c-y>a'
---------------------
<a href="http://www.google.com/">Google</a>
---------------------
A: Mapping
I like to have my block tags (as opposed to inline) closed immediately and with as simple a shortcut as possible (I like to avoid special keys like CTRL where possible, though I do use closetag.vim to close my inline tags.) I like to use this shortcut when starting blocks of tags (thanks to @kimilhee; this is a take-off of his answer):
inoremap ><Tab> ><Esc>F<lyt>o</<C-r>"><Esc>O<Space>
Sample usage
Type—
<p>[Tab]
Result—
<p>
|
</p>
where | indicates cursor position.
Explanation
*
*inoremap means create the mapping in insert mode
*><Tab> means a closing angle brackets and a tab character; this is what is matched
*><Esc> means end the first tag and escape from insert into normal mode
*F< means find the last opening angle bracket
*l means move the cursor right one (don't copy the opening angle bracket)
*yt> means yank from cursor position to up until before the next closing angle bracket (i.e. copy tags contents)
*o</ means start new line in insert mode and add an opening angle bracket and slash
*<C-r>" means paste in insert mode from the default register (")
*><Esc> means close the closing tag and escape from insert mode
*O<Space> means start a new line in insert mode above the cursor and insert a space
A: Check out vim-closetag
It's a really simple script (also available as a vundle plugin) that closes (X)HTML tags for you. From it's README:
If this is the current content:
<table|
Now you press >, the content will be:
<table>|</table>
And now if you press > again, the content will be:
<table>
|
</table>
Note: | is the cursor here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "127"
}
|
Q: Link error when compiling gcc atomic operation in 32-bit mode I have the following program:
~/test> cat test.cc
int main()
{
int i = 3;
int j = __sync_add_and_fetch(&i, 1);
return 0;
}
I'm compiling this program using GCC 4.2.2 on Linux running on a multi-cpu 64-bit Intel machine:
~/test> uname --all
Linux doom 2.6.9-67.ELsmp #1 SMP Wed Nov 7 13:56:44 EST 2007 x86_64 x86_64 x86_64 GNU/Linux
When I compile the program in 64-bit mode, it compiles and links fine:
~/test> /share/tools/gcc-4.2.2/bin/g++ test.cc
~/test>
When I compile it in 32-bit mode, I get the following error:
~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc
/tmp/ccEVHGkB.o(.text+0x27): In function `main':
: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
~/test>
Although I will never actually run on a 32-bit processor, I do need a 32-bit executable so I can link with some 32-bit libraries.
My 2 questions are:
*
*Why do I get a link error when I compile in 32-bit mode?
*Is there some way to get the program to compile and link, while still being able to link with a 32-bit library?
A: The answer from Dan Udey was close, close enough in fact to allow me to find the real solution.
According to the man page "-mcpu" is a deprecated synonym for "-mtune" and just means "optimize for a particular CPU (but still run on older CPUs, albeit less optimal)". I tried this, and it did not solve the issue.
However, "-march=" means "generate code for a particular CPU (and don't run on older CPUs)". When I tried this it solved the problem: specifying a CPU of i486 or better got rid of the link error.
~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 test.cc
/tmp/ccYnYLj6.o(.text+0x27): In function `main':
: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i386 test.cc
/tmp/ccOr3ww8.o(.text+0x22): In function `main':
: undefined reference to `__sync_add_and_fetch_4'
collect2: ld returned 1 exit status
~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=i486 test.cc
~/test> /share/tools/gcc-4.2.2/bin/g++ -m32 -march=pentium test.cc
A: From the GCC page on Atomic Builtins:
Not all operations are supported by
all target processors. If a particular
operation cannot be implemented on the
target processor, a warning will be
generated and a call an external
function will be generated. The
external function will carry the same
name as the builtin, with an
additional suffix `_n' where n is the
size of the data type.
Judging from your compiler output, which refers to __sync_add_and_fetch_4, this is what's happening. For some reason, GCC is not generating the external function properly.
This is likely why you're only getting an error in 32-bit mode - when compiling for 64-bit mode, it compiles for your processor more closely. When compiling for 32-bit, it may well be using a generic arch (i386, for example) which does not natively support those features. Try specifying a specific architecture for your chip family (Xeon, Core 2, etc.) via -mcpu and see if that works.
If not, you'll have to figure out why GCC isn't including the appropriate function that it should be generating.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Best way to swap two .NET controls based on radio buttons I've got a form where I have two radio buttons and two interchangeable controls (made up of a ListView and a handful of buttons). Based on which radio button is selected I want to display the proper control to the user.
The way I'm doing this now is just loading both controls and setting up an OnRadioButtonSelectionChanged() method which gets called at form load (to set the initial state) and at any time the selection is changed. This method just sets the visible property on each control to the proper value.
This seems to work well enough, but I was curious as to if there was a better or more common way of doing it?
A: Yep, that's pretty much how I do it. I would set the CheckedChanged event of both radio buttons to point at a single event handler and would place the following code to swap out the visible control.
private void OnRadioButtonCheckedChanged(object sender, EventArgs e)
{
Control1.Visible = RadioButton1.Checked;
Control2.Visible = RadioButton2.Checked;
}
A: Well you could also use databinding... seems a bit more elegant to me. Suppose you have two radiobuttons "rbA" and "rbB" and two textboxes "txtA" and "txtB". And you want to have txtA visible only when rbA is checked and txtB visible only when rbB is checked. You could do it like so :
private void Form1_Load(object sender, EventArgs e)
{
txtA.DataBindings.Add("Visible", rbA, "Checked");
txtB.DataBindings.Add("Visible", rbB, "Checked");
}
However... I observed that using UserControls instead of TextBoxes breaks the functionality and I should go read on the net why..
LATER EDIT :
The databinding works two-ways! : If you programatically set (from somewhere else) the visibility of the txtA to false the rbA will become unchecked. That's the beauty of Databinding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Last time a Stored Procedure was executed On Sql Server 2000, is there a way to find out the date and time when a stored procedure was last executed?
A: Not without logging or tracing, I'm afraid
A: If a stored procedure is still in the procedure cache, you can find the last time it was executed by querying the sys.dm_exec_query_stats DMV. In this example, I also cross apply to the sys.dm_exec_query_plan DMF in order to qualify the object id:
declare @proc_nm sysname
-- select the procedure name here
set @proc_nm = 'usp_test'
select s.last_execution_time
from sys.dm_exec_query_stats s
cross apply sys.dm_exec_query_plan (s.plan_handle) p
where object_name(p.objectid, db_id('AdventureWorks')) = @proc_nm
[Source]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Request UAC elevation from within a Python script? I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run cmd.exe "as administator" and then run my script, it works fine.
This makes sense since User Account Control (UAC) normally prevents many file system actions.
Is there a way I can, from within a Python script, invoke a UAC elevation request (those dialogs that say something like "such and such app needs admin access, is this OK?")
If that's not possible, is there a way my script can at least detect that it is not elevated so it can fail gracefully?
A: It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea:
import os
import sys
import win32com.shell.shell as shell
ASADMIN = 'asadmin'
if sys.argv[-1] != ASADMIN:
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + [ASADMIN])
shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params)
sys.exit(0)
A: The following example builds on MARTIN DE LA FUENTE SAAVEDRA's excellent work and accepted answer. In particular, two enumerations are introduced. The first allows for easy specification of how an elevated program is to be opened, and the second helps when errors need to be easily identified. Please note that if you want all command line arguments passed to the new process, sys.argv[0] should probably be replaced with a function call: subprocess.list2cmdline(sys.argv).
#! /usr/bin/env python3
import ctypes
import enum
import subprocess
import sys
# Reference:
# msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
# noinspection SpellCheckingInspection
class SW(enum.IntEnum):
HIDE = 0
MAXIMIZE = 3
MINIMIZE = 6
RESTORE = 9
SHOW = 5
SHOWDEFAULT = 10
SHOWMAXIMIZED = 3
SHOWMINIMIZED = 2
SHOWMINNOACTIVE = 7
SHOWNA = 8
SHOWNOACTIVATE = 4
SHOWNORMAL = 1
class ERROR(enum.IntEnum):
ZERO = 0
FILE_NOT_FOUND = 2
PATH_NOT_FOUND = 3
BAD_FORMAT = 11
ACCESS_DENIED = 5
ASSOC_INCOMPLETE = 27
DDE_BUSY = 30
DDE_FAIL = 29
DDE_TIMEOUT = 28
DLL_NOT_FOUND = 32
NO_ASSOC = 31
OOM = 8
SHARE = 26
def bootstrap():
if ctypes.windll.shell32.IsUserAnAdmin():
main()
else:
# noinspection SpellCheckingInspection
hinstance = ctypes.windll.shell32.ShellExecuteW(
None,
'runas',
sys.executable,
subprocess.list2cmdline(sys.argv),
None,
SW.SHOWNORMAL
)
if hinstance <= 32:
raise RuntimeError(ERROR(hinstance))
def main():
# Your Code Here
print(input('Echo: '))
if __name__ == '__main__':
bootstrap()
A: Recognizing this question was asked years ago, I think a more elegant solution is offered on github by frmdstryr using his module pywinutils:
Excerpt:
import pythoncom
from win32com.shell import shell,shellcon
def copy(src,dst,flags=shellcon.FOF_NOCONFIRMATION):
""" Copy files using the built in Windows File copy dialog
Requires absolute paths. Does NOT create root destination folder if it doesn't exist.
Overwrites and is recursive by default
@see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx for flags available
"""
# @see IFileOperation
pfo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation,None,pythoncom.CLSCTX_ALL,shell.IID_IFileOperation)
# Respond with Yes to All for any dialog
# @see http://msdn.microsoft.com/en-us/library/bb775799(v=vs.85).aspx
pfo.SetOperationFlags(flags)
# Set the destionation folder
dst = shell.SHCreateItemFromParsingName(dst,None,shell.IID_IShellItem)
if type(src) not in (tuple,list):
src = (src,)
for f in src:
item = shell.SHCreateItemFromParsingName(f,None,shell.IID_IShellItem)
pfo.CopyItem(item,dst) # Schedule an operation to be performed
# @see http://msdn.microsoft.com/en-us/library/bb775780(v=vs.85).aspx
success = pfo.PerformOperations()
# @see sdn.microsoft.com/en-us/library/bb775769(v=vs.85).aspx
aborted = pfo.GetAnyOperationsAborted()
return success is None and not aborted
This utilizes the COM interface and automatically indicates that admin privileges are needed with the familiar dialog prompt that you would see if you were copying into a directory where admin privileges are required and also provides the typical file progress dialog during the copy operation.
A: It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that need those privileges. There are two ways to do this:
*
*Write a manifest file that tells Windows the application might require some privileges
*Run the application with elevated privileges from inside another program
This two articles explain in much more detail how this works.
What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:
When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.
As you describe your program as a "script", I suppose that's enough for your needs.
Cheers.
A: This may not completely answer your question but you could also try using the Elevate Command Powertoy in order to run the script with elevated UAC privileges.
http://technet.microsoft.com/en-us/magazine/2008.06.elevation.aspx
I think if you use it it would look like 'elevate python yourscript.py'
A: You can make a shortcut somewhere and as the target use:
python yourscript.py
then under properties and advanced select run as administrator.
When the user executes the shortcut it will ask them to elevate the application.
A: A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):
def spawn_as_administrator():
""" Spawn ourself with administrator rights and wait for new process to exit
Make the new process use the same console as the old one.
Raise Exception() if we could not get a handle for the new re-run the process
Raise pywintypes.error() if we could not re-spawn
Return the exit code of the new process,
or return None if already running the second admin process. """
#pylint: disable=no-name-in-module,import-error
import win32event, win32api, win32process
import win32com.shell.shell as shell
if '--admin' in sys.argv:
return None
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + ['--admin'])
SEE_MASK_NO_CONSOLE = 0x00008000
SEE_MASK_NOCLOSE_PROCESS = 0x00000040
process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
hProcess = process['hProcess']
if not hProcess:
raise Exception("Could not identify administrator process to install drivers")
# It is necessary to wait for the elevated process or else
# stdin lines are shared between 2 processes: they get one line each
INFINITE = -1
win32event.WaitForSingleObject(hProcess, INFINITE)
exitcode = win32process.GetExitCodeProcess(hProcess)
win32api.CloseHandle(hProcess)
return exitcode
A: This is mostly an upgrade to Jorenko's answer, that allows to use parameters with spaces in Windows, but should also work fairly well on Linux :)
Also, will work with cx_freeze or py2exe since we don't use __file__ but sys.argv[0] as executable
[EDIT]
Disclaimer: The code in this post is outdated.
I have published the elevation code as a python package.
Install with pip install command_runner
Usage:
from command_runner.elevate import elevate
def main():
"""My main function that should be elevated"""
print("Who's the administrator, now ?")
if __name__ == '__main__':
elevate(main)
[/EDIT]
import sys,ctypes,platform
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
raise False
if __name__ == '__main__':
if platform.system() == "Windows":
if is_admin():
main(sys.argv[1:])
else:
# Re-run the program with admin rights, don't use __file__ since py2exe won't know about it
# Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters
lpParameters = ""
# Litteraly quote all parameters which get unquoted when passed to python
for i, item in enumerate(sys.argv[0:]):
lpParameters += '"' + item + '" '
try:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, lpParameters , None, 1)
except:
sys.exit(1)
else:
main(sys.argv[1:])
A: As of 2017, an easy method to achieve this is the following:
import ctypes, sys
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
# Code of your program here
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
If you are using Python 2.x, then you should replace the last line for:
ctypes.windll.shell32.ShellExecuteW(None, u"runas", unicode(sys.executable), unicode(" ".join(sys.argv)), None, 1)
Also note that if you converted you python script into an executable file (using tools like py2exe, cx_freeze, pyinstaller) then you should use sys.argv[1:] instead of sys.argv in the fourth parameter.
Some of the advantages here are:
*
*No external libraries required. It only uses ctypes and sys from standard library.
*Works on both Python 2 and Python 3.
*There is no need to modify the file resources nor creating a manifest file.
*If you don't add code below if/else statement, the code won't ever be executed twice.
*You can get the return value of the API call in the last line and take an action if it fails (code <= 32). Check possible return values here.
*You can change the display method of the spawned process modifying the sixth parameter.
Documentation for the underlying ShellExecute call is here.
A: Just adding this answer in case others are directed here by Google Search as I was.
I used the elevate module in my Python script and the script executed with Administrator Privileges in Windows 10.
https://pypi.org/project/elevate/
A: For one-liners, put the code to where you need UAC.
Request UAC, if failed, keep running:
import ctypes, sys
ctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1) > 32 and exit()
Request UAC, if failed, exit:
import ctypes, sys
ctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1) > 32, exit())
Function style:
# Created by BaiJiFeiLong@gmail.com at 2022/6/24
import ctypes
import sys
def request_uac_or_skip():
ctypes.windll.shell32.IsUserAnAdmin() or ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1) > 32 and sys.exit()
def request_uac_or_exit():
ctypes.windll.shell32.IsUserAnAdmin() or (ctypes.windll.shell32.ShellExecuteW(
None, "runas", sys.executable, " ".join(sys.argv), None, 1) > 32, sys.exit())
A: If your script always requires an Administrator's privileges then:
runas /user:Administrator "python your_script.py"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "121"
}
|
Q: Is a variable named i unacceptable? As far as variable naming conventions go, should iterators be named i or something more semantic like count? If you don't use i, why not? If you feel that i is acceptable, are there cases of iteration where it shouldn't be used?
A: Here's another example of something that's perfectly okay:
foreach (Product p in ProductList)
{
// Do something with p
}
A: I tend to use i, j, k for very localized loops (only exist for a short period in terms of number of source lines). For variables that exist over a larger source area, I tend to use more detailed names so I can see what they're for without searching back in the code.
By the way, I think that the naming convention for these came from the early Fortran language where I was the first integer variable (A - H were floats)?
A: Depends on the context I suppose. If you where looping through a set of Objects in some
collection then it should be fairly obvious from the context what you are doing.
for(int i = 0; i < 10; i++)
{
// i is well known here to be the index
objectCollection[i].SomeProperty = someValue;
}
However if it is not immediately clear from the context what it is you are doing, or if you are making modifications to the index you should use a variable name that is more indicative of the usage.
for(int currentRow = 0; currentRow < numRows; currentRow++)
{
for(int currentCol = 0; currentCol < numCols; currentCol++)
{
someTable[currentRow][currentCol] = someValue;
}
}
A: i is acceptable, for certain. However, I learned a tremendous amount one semester from a C++ teacher I had who refused code that did not have a descriptive name for every single variable. The simple act of naming everything descriptively forced me to think harder about my code, and I wrote better programs after that course, not from learning C++, but from learning to name everything. Code Complete has some good words on this same topic.
A: i is fine, but something like this is not:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
string s = datarow[i][j].ToString(); // or worse
}
}
Very common for programmers to inadvertently swap the i and the j in the code, especially if they have bad eyesight or their Windows theme is "hotdog". This is always a "code smell" for me - it's kind of rare when this doesn't get screwed up.
A: i is so common that it is acceptable, even for people that love descriptive variable names.
What is absolutely unacceptable (and a sin in my book) is using i,j, or k in any other context than as an integer index in a loop.... e.g.
foreach(Input i in inputs)
{
Process(i);
}
A: i is definitely acceptable. Not sure what kind of justification I need to make -- but I do use it all of the time, and other very respected programmers do as well.
Social validation, I guess :)
A: Yes, in fact it's preferred since any programmer reading your code will understand that it's simply an iterator.
A: What is the value of using i instead of a more specific variable name? To save 1 second or 10 seconds or maybe, maybe, even 30 seconds of thinking and typing?
What is the cost of using i? Maybe nothing. Maybe the code is so simple that using i is fine. But maybe, maybe, using i will force developers who come to this code in the future to have to think for a moment "what does i mean here?" They will have to think: "is it an index, a count, an offset, a flag?" They will have to think: "is this change safe, is it correct, will I be off by 1?"
Using i saves time and intellectual effort when writing code but may end up costing more intellectual effort in the future, or perhaps even result in the inadvertent introduction of defects due to misunderstanding the code.
Generally speaking, most software development is maintenance and extension, so the amount of time spent reading your code will vastly exceed the amount of time spent writing it.
It's very easy to develop the habit of using meaningful names everywhere, and once you have that habit it takes only a few seconds more to write code with meaningful names, but then you have code which is easier to read, easier to understand, and more obviously correct.
A: I use i for short loops.
The reason it's OK is that I find it utterly implausible that someone could see a declaration of iterator type, with initializer, and then three lines later claim that it's not clear what the variable represents. They're just pretending, because they've decided that "meaningful variable names" must mean "long variable names".
The reason I actually do it, is that I find that using something unrelated to the specific task at hand, and that I would only ever use in a small scope, saves me worrying that I might use a name that's misleading, or ambiguous, or will some day be useful for something else in the larger scope. The reason it's "i" rather than "q" or "count" is just convention borrowed from mathematics.
I don't use i if:
*
*The loop body is not small, or
*the iterator does anything other than advance (or retreat) from the start of a range to the finish of the loop:
i doesn't necessarily have to go in increments of 1 so long as the increment is consistent and clear, and of course might stop before the end of the iterand, but if it ever changes direction, or is unmodified by an iteration of the loop (including the devilish use of iterator.insertAfter() in a forward loop), I try to remember to use something different. This signals "this is not just a trivial loop variable, hence this may not be a trivial loop".
A: "i" means "loop counter" to a programmer. There's nothing wrong with it.
A: If the "something more semantic" is "iterator" then there is no reason not to use i; it is a well understood idiom.
A: i think i is completely acceptable in for-loop situations. i have always found this to be pretty standard and never really run into interpretation issues when i is used in this instance. foreach-loops get a little trickier and i think really depends on your situation. i rarely if ever use i in foreach, only in for loops, as i find i to be too un-descriptive in these cases. for foreach i try to use an abbreviation of the object type being looped. e.g:
foreach(DataRow dr in datatable.Rows)
{
//do stuff to/with datarow dr here
}
anyways, just my $0.02.
A: It helps if you name it something that describes what it is looping through. But I usually just use i.
A: As long as you are either using i to count loops, or part of an index that goes from 0 (or 1 depending on PL) to n, then I would say i is fine.
Otherwise its probably easy to name i something meaningful it its more than just an index.
A: I should point out that i and j are also mathematical notation for matrix indices. And usually, you're looping over an array. So it makes sense.
A: As long as you're using it temporarily inside a simple loop and it's obvious what you're doing, sure. That said, is there no other short word you can use instead?
i is widely known as a loop iterator, so you're actually more likely to confuse maintenance programmers if you use it outside of a loop, but if you use something more descriptive (like filecounter), it makes code nicer.
A: It depends.
If you're iterating over some particular set of data then I think it makes more sense to use a descriptive name. (eg. filecounter as Dan suggested).
However, if you're performing an arbitrary loop then i is acceptable. As one work mate described it to me - i is a convention that means "this variable is only ever modified by the for loop construct. If that's not true, don't use i"
A: The use of i, j, k for INTEGER loop counters goes back to the early days of FORTRAN.
Personally I don't have a problem with them so long as they are INTEGER counts.
But then I grew up on FORTRAN!
A: my feeling is that the concept of using a single letter is fine for "simple" loops, however, i learned to use double-letters a long time ago and it has worked out great.
i asked a similar question last week and the following is part of my own answer:// recommended style ● // "typical" single-letter style
●
for (ii=0; ii<10; ++ii) { ● for (i=0; i<10; ++i) {
for (jj=0; jj<10; ++jj) { ● for (j=0; j<10; ++j) {
mm[ii][jj] = ii * jj; ● m[i][j] = i * j;
} ● }
} ● }
in case the benefit isn't immediately obvious: searching through code for any single letter will find many things that aren't what you're looking for. the letter i occurs quite often in code where it isn't the variable you're looking for.
i've been doing it this way for at least 10 years.
note that plenty of people commented that either/both of the above are "ugly"...
A: I am going to go against the grain and say no.
For the crowd that says "i is understood as an iterator", that may be true, but to me that is the equivalent of comments like 'Assign the value 5 to variable Y. Variable names like comment should explain the why/what not the how.
To use an example from a previous answer:
for(int i = 0; i < 10; i++)
{
// i is well known here to be the index
objectCollection[i].SomeProperty = someValue;
}
Is it that much harder to just use a meaningful name like so?
for(int objectCollectionIndex = 0; objectCollectionIndex < 10; objectCollectionIndex ++)
{
objectCollection[objectCollectionIndex].SomeProperty = someValue;
}
Granted the (borrowed) variable name objectCollection is pretty badly named too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Can you use Decision Tables in Relational Databases I heard that decision tables in relational database have been researched a lot in academia. I also know that business rules engines use decision tables and that many BPMS use them as well.
I was wondering if people today use decision tables within their relational databases?
A: A decision table is a cluster of conditions and actions. A condition can be simple enough that you can represent it with a simple "match a column against this value" string. Or a condition could be hellishly complex. An action, similarly, could be as simple as "move this value to a column". Or the action could involve multiple parts or steps or -- well -- anything.
A CASE function in a SELECT or WHERE clause is a decision table. This is the first example of decision table "in" a relational database.
You can have a "transformation" table with columns that have old-value and replacement-value. You can then write a small piece of code like the following.
def decision_table( aRow ):
result= connection.execute( "SELECT replacement_value FROM transformation WHERE old_value = ?", aRow['somecolumn'] )
replacement= result.fetchone()
aRow['anotherColumn']= result['replacement_value']
Each row of the decision table has a "match this old_value" and "move this replacement_value" kind of definition.
The "condition" parts of a decision table have to be evaluated somewhere. Your application is where this will happen. You will fetch the condition values from the database. You'll use those values in some function(s) to see if the rule is true.
The "action" parts of a decision table have to be executed somewhere; again, your application does stuff. You'll fetch action values from the database. You'll use those values to insert, update or delete other values.
Decision tables are used all the time; they've always been around in relational databases. Each table requires a highly customized data model. It also requires a unique condition function and action procedure.
It doesn't generalize well. If you want, you could store XML in the database and invoke some rules engine to interpret and execute the BPEL rules. In this case, the rules engine does the condition and action processing.
If you want, you could store Python (or Tcl or something else) in the database. Seriously. You'd write the conditions and actions in Python. You'd fetch it from the database and run the Python code fragment.
Lots of choices. None of the "academic". Indeed, the basic condition - action stuff is done all the time.
A: Wheter or not to put decision tables in a database depends on a number of other questions.
Will your conditions be calculated inside the RDBMS or elsewhere? If the data used for evaluating these conditions, and a suitable method for evaluating them inside the RDBMS can be devised, it is probably a good idea. Maybe your actions also happens inside your database, which would make it even more attractive.
Your conditions, and even execution of your actions might be on the outside of the RDBMS, but you could still keep the connections between combinations of conditions and actions on the inside. Probably because most of you other data is there, and all you have is a web server sitting on top of it.
I can think of two ways to model this, depending on how many conditions you have (and wheter they are binary), and what the capacity for columns per table is.
Let's say you have 6 conditions that are binary, this means you have 2^6 = 64 possible combinations. Then you could have one column for every combination, and one row for every action.
Or you could have 16 conditions which means you would have almost an incalculable number of combinations (actually 65536). Which is a ridiculous number of columns. Better then to have a column for each condition and a column for each action and 65536 rows of what to do in each possible situation. Each row would represent a situation and what to do in that situation. The only datatype you use would be bool. You could also package these bools into bitmasked integers.
Actually, bigger decision tables are better avoided. Divide and rule, and use more tables is a much better way. Usually a subject matter expert will get tired if asked to give opinions on too high a number of conditions.
The strength of the decision table is really in the modelling stage where the developer and the subject matter expert can find out if every possible situation is mapped, and no blind spots can exist.
A: I think they will contribute to the already too much declined state of what used to be "in-person" communications- enough hide behind the screen as it is..... come out of the closet, get out - got the picture.
A: I would look into using an Object database rather than a traditional RDBMS (Relational Database Management System). Object databases are designed to be fast at handling hierarchical relationships between objects, whereas in an RDBMS, you have to represent these relationships across multiple table rows, or even tables so your queries (tree traversals) will be slow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: GDI+ System.Drawing.Bitmap gives error Parameter is not valid intermittently I have some C# code in an ASP.Net application that does this:
Bitmap bmp = new Bitmap(1184, 1900);
And occasionally it throws an exception "Parameter is not valid". Now i've been googling around and apparently GDI+ is infamous for throwing random exceptions, and lots of people have had this problem, but nobody has a solution to it! I've checked the system and it has plenty of both RAM and swap space.
Now in the past if i do an 'iisreset' then the problem goes away, but it comes back in a few days. But i'm not convinced i've caused a memory leak, because as i say above there is plenty of ram+swap free.
Anyone have any solutions?
A: For anyone who's interested, the solution i'm going to use is the Mono.Cairo libraries from the mono C# distribution instead of using system.drawing. If i simply drag the mono.cairo.dll, libcairo-2.dll, libpng13.dll and zlib1.dll files from the windows version of mono into the same folder as my executable, then i can develop in windows using visual studio 2005 and it all works nicely.
Update - i've done the above, and stress tested the application and it all seems to run smoothly now, and uses up to 200mb less ram to boot. Very happy.
A: Everything I've seen to date in my context is related to memory leaks / handle leaks. I recommend you get a fresh pair of eyes to investigate your code.
What actually happens is that the image is disposed at a random point in the future, even if you've created it on the previous line of code. This may be because of a memory/handle leak (cleaning some out of my code appears to improve but not completely resolve this problem).
Because this error happens after the application has been in use for a while, sometimes using lots of memory, sometimes not, I feel the garbage collector doesn't obey the rules because of some special tweaks related to services and that is why Microsoft washes their hands of this problem.
http://blog.lavablast.com/post/2007/11/The-Mysterious-Parameter-Is-Not-Valid-Exception.aspx
A: Stop using GDI+ and start using the WPF Imaging classes (.NET 3.0). These are a major cleanup of the GDI+ classes and tuned for performance. Additionally, it sets up a "bitmap chain" that allows you to easily perform multiple actions on the bitmap in an efficient manner.
Find more by reading about BitmapSource
Here's an example of starting with a blank bitmap just waiting to receive some pixels:
using System.Windows.Media.Imaging;
class Program {
public static void Main(string[] args) {
var bmp = new WriteableBitmap(1184, 1900, 96.0, 96.0, PixelFormat.Bgr32, null);
}
}
A: You not only need enough memory, it needs to be contiguous. Over time memory becomes fragmented and it becomes harder to find big blocks. There aren't a lot of good solutions to this, aside from building up images from smaller bitmaps.
new Bitmap(x, y) pretty much just needs to allocate memory -- assuming that your program isn't corrupted in some way (is there any unsafe code that could corrupt the heap), then I would start with this allocation failing. Needing a contiguous block is how a seemingly small allocation could fail. Fragmentation of the heap is something that is usually solved with a custom allocator -- I don't think this is a good idea in IIS (or possible).
To see what error you get on out of memory, try just allocation a gigantic Bitmap as a test -- see what error it throws.
One strategy I've seen is to pre-allocate some large blocks of memory (in your case Bitmaps) and treat them as a pool (get and return them to the pool). If you only need them for a short period of time, you might be able to get away with just keeping a few in memory and sharing them.
A: I just got a reply from microsoft support. Apparently if you look here:
http://msdn.microsoft.com/en-us/library/system.drawing.aspx
You can see it says "Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service. Attempting to use these classes from within one of these application types may produce unexpected problems, such as diminished service performance and run-time exceptions."
So they're basically washing their hands of the issue.
It appears that they're admitting that this section of the .Net framework is unreliable. I'm a bit disappointed.
Next up - can anyone recommend a similar library to open a gif file, superimpose some text, and save it again?
A: Classes within the System.Drawing namespace are not supported for use within a Windows or ASP.NET service
For a supported alternative, see Windows Imaging Components (msdn), a native library which ironically System.Drawing is based on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: What is dependency injection? There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However,
What is dependency injection and when/why should or shouldn't it be used?
A: Before going to the technical description first visualize it with a real-life example because you will find a lot of technical stuff to learn dependency injection but the majority of the people can't get the core concept of it.
In the first picture, assume that you have a car factory with a lot of units. A car is actually built in the assembly unit but it needs engine, seats as well as wheels. So an assembly unit is dependent on these all units and they are the dependencies of the factory.
You can feel that now it is too complicated to maintain all of the tasks in this factory because along with the main task (assembling a car in the Assembly unit) you have to also focus on other units. It is now very costly to maintain and the factory building is huge so it takes your extra bucks for rent.
Now, look at the second picture. If you find some provider companies that will provide you with the wheel, seat, and engine for cheaper than your self-production cost then now you don't need to make them in your factory. You can rent a smaller building now just for your assembly unit which will lessen your maintenance task and reduce your extra rental cost. Now you can also focus only on your main task (Car assembly).
Now we can say that all the dependencies for assembling a car are injected on the factory from the providers. It is an example of a real-life Dependency Injection (DI).
Now in the technical word, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. So, transferring the task of creating the object to someone else and directly using the dependency is called dependency injection.
This will help you now to learn DI with a technical explanation. This will show when to use DI and when you should not.
.
A: I think since everyone has written for DI, let me ask a few questions..
*
*When you have a configuration of DI where all the actual implementations(not interfaces) that are going to be injected into a class (for e.g services to a controller) why is that not some sort of hard-coding?
*What if I want to change the object at runtime? For example, my config already says when I instantiate MyController, inject for FileLogger as ILogger. But I might want to inject DatabaseLogger.
*Every time I want to change what objects my AClass needs, I need to now look into two places - The class itself and the configuration file. How does that make life easier?
*If Aproperty of AClass is not injected, is it harder to mock it out?
*Going back to the first question. If using new object() is bad, how come we inject the implementation and not the interface? I think a lot of you are saying we're in fact injecting the interface but the configuration makes you specify the implementation of that interface ..not at runtime .. it is hardcoded during compile time.
This is based on the answer @Adam N posted.
Why does PersonService no longer have to worry about GroupMembershipService? You just mentioned GroupMembership has multiple things(objects/properties) it depends on. If GMService was required in PService, you'd have it as a property. You can mock that out regardless of whether you injected it or not. The only time I'd like it to be injected is if GMService had more specific child classes, which you wouldn't know until runtime. Then you'd want to inject the subclass. Or if you wanted to use that as either singleton or prototype. To be honest, the configuration file has everything hardcoded as far as what subclass for a type (interface) it is going to inject during compile time.
EDIT
A nice comment by Jose Maria Arranz on DI
DI increases cohesion by removing any need to determine the direction of dependency and write any glue code.
False. The direction of dependencies is in XML form or as annotations, your dependencies are written as XML code and annotations. XML and annotations ARE source code.
DI reduces coupling by making all of your components modular (i.e. replaceable) and have well-defined interfaces to each other.
False. You do not need a DI framework to build a modular code based on interfaces.
About replaceable: with a very simple .properties archive and Class.forName you can define which classes can change. If ANY class of your code can be changed, Java is not for you, use an scripting language. By the way: annotations cannot be changed without recompiling.
In my opinion there is one only reason for DI frameworks: boiler plate reduction. With a well done factory system you can do the same, more controlled and more predictable as your preferred DI framework, DI frameworks promise code reduction (XML and annotations are source code too). The problem is this boiler plate reduction is just real in very very simple cases (one instance-per class and similar), sometimes in the real world picking the appropriated service object is not as easy as mapping a class to a singleton object.
A: I found this funny example in terms of loose coupling:
Source: Understanding dependency injection
Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.
For example, consider a Car object.
A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object.
Without Dependency Injection (DI):
class Car{
private Wheel wh = new NepaliRubberWheel();
private Battery bt = new ExcideBattery();
//The rest
}
Here, the Car object is responsible for creating the dependent objects.
What if we want to change the type of its dependent object - say Wheel - after the initial NepaliRubberWheel() punctures?
We need to recreate the Car object with its new dependency say ChineseRubberWheel(), but only the Car manufacturer can do that.
Then what does the Dependency Injection do for us...?
When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time).
So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.
After using dependency injection:
Here, we are injecting the dependencies (Wheel and Battery) at runtime. Hence the term : Dependency Injection. We normally rely on DI frameworks such as Spring, Guice, Weld to create the dependencies and inject where needed.
class Car{
private Wheel wh; // Inject an Instance of Wheel (dependency of car) at runtime
private Battery bt; // Inject an Instance of Battery (dependency of car) at runtime
Car(Wheel wh,Battery bt) {
this.wh = wh;
this.bt = bt;
}
//Or we can have setters
void setWheel(Wheel wh) {
this.wh = wh;
}
}
The advantages are:
*
*decoupling the creation of object (in other word, separate usage from the creation of object)
*ability to replace dependencies (eg: Wheel, Battery) without changing the class that uses it(Car)
*promotes "Code to interface not to implementation" principle
*ability to create and use mock dependency during test (if we want to use a Mock of Wheel during test instead of a real instance.. we can create Mock Wheel object and let DI framework inject to Car)
A: The popular answers are unhelpful, because they define dependency injection in a way that isn't useful. Let's agree that by "dependency" we mean some pre-existing other object that our object X needs. But we don't say we're doing "dependency injection" when we say
$foo = Foo->new($bar);
We just call that passing parameters into the constructor. We've been doing that regularly ever since constructors were invented.
"Dependency injection" is considered a type of "inversion of control", which means that some logic is taken out of the caller. That isn't the case when the caller passes in parameters, so if that were DI, DI would not imply inversion of control.
DI means there is an intermediate level between the caller and the constructor which manages dependencies. A Makefile is a simple example of dependency injection. The "caller" is the person typing "make bar" on the command line, and the "constructor" is the compiler. The Makefile specifies that bar depends on foo, and it does a
gcc -c foo.cpp; gcc -c bar.cpp
before doing a
gcc foo.o bar.o -o bar
The person typing "make bar" doesn't need to know that bar depends on foo. The dependency was injected between "make bar" and gcc.
The main purpose of the intermediate level is not just to pass in the dependencies to the constructor, but to list all the dependencies in just one place, and to hide them from the coder (not to make the coder provide them).
Usually the intermediate level provides factories for the constructed objects, which must provide a role that each requested object type must satisfy. That's because by having an intermediate level that hides the details of construction, you've already incurred the abstraction penalty imposed by factories, so you might as well use factories.
A: Dependency Injection means a way (actually any-way) for one part of code (e.g a class) to have access to dependencies (other parts of code, e.g other classes, it depends upon) in a modular way without them being hardcoded (so they can change or be overriden freely, or even be loaded at another time, as needed)
(and ps , yes it has become an overly-hyped 25$ name for a rather simple, concept), my .25 cents
A: Doesn't "dependency injection" just mean using parameterized constructors and public setters?
James Shore's article shows the following examples for comparison.
Constructor without dependency injection:
public class Example {
private DatabaseThingie myDatabase;
public Example() {
myDatabase = new DatabaseThingie();
}
public void doStuff() {
...
myDatabase.getData();
...
}
}
Constructor with dependency injection:
public class Example {
private DatabaseThingie myDatabase;
public Example(DatabaseThingie useThisDatabaseInstead) {
myDatabase = useThisDatabaseInstead;
}
public void doStuff() {
...
myDatabase.getData();
...
}
}
A: From the Book, 'Well-Grounded Java Developer: Vital techniques of Java 7 and polyglot programming
DI is a particular form of IoC, whereby the process of finding your dependencies is
outside the direct control of your currently executing code.
A: Dependency injection is one possible solution to what could generally be termed the "Dependency Obfuscation" requirement. Dependency Obfuscation is a method of taking the 'obvious' nature out of the process of providing a dependency to a class that requires it and therefore obfuscating, in some way, the provision of said dependency to said class. This is not necessarily a bad thing. In fact, by obfuscating the manner by which a dependency is provided to a class then something outside the class is responsible for creating the dependency which means, in various scenarios, a different implementation of the dependency can be supplied to the class without making any changes to the class. This is great for switching between production and testing modes (eg., using a 'mock' service dependency).
Unfortunately the bad part is that some people have assumed you need a specialized framework to do dependency obfuscation and that you are somehow a 'lesser' programmer if you choose not to use a particular framework to do it. Another, extremely disturbing myth, believed by many, is that dependency injection is the only way of achieving dependency obfuscation. This is demonstrably and historically and obviously 100% wrong but you will have trouble convincing some people that there are alternatives to dependency injection for your dependency obfuscation requirements.
Programmers have understood the dependency obfuscation requirement for years and many alternative solutions have evolved both before and after dependency injection was conceived. There are Factory patterns but there are also many options using ThreadLocal where no injection to a particular instance is needed - the dependency is effectively injected into the thread which has the benefit of making the object available (via convenience static getter methods) to any class that requires it without having to add annotations to the classes that require it and set up intricate XML 'glue' to make it happen. When your dependencies are required for persistence (JPA/JDO or whatever) it allows you to achieve 'tranaparent persistence' much easier and with domain model and business model classes made up purely of POJOs (i.e. no framework specific/locked in annotations).
A: Dependency Injection for 5 year olds.
When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open, you might get something Mommy or Daddy doesn't want you to have. You might be even looking for something we don't even have or which has expired.
What you should be doing is stating a need, "I need something to drink with lunch," and then we will make sure you have something when you sit down to eat.
A: To make Dependency Injection concept simple to understand. Let's take an example of switch button to toggle(on/off) a bulb.
Without Dependency Injection
Switch needs to know beforehand which bulb I am connected to (hard-coded dependency). So,
Switch -> PermanentBulb //switch is directly connected to permanent bulb, testing not possible easily
Switch(){
PermanentBulb = new Bulb();
PermanentBulb.Toggle();
}
With Dependency Injection
Switch only knows I need to turn on/off whichever Bulb is passed to me. So,
Switch -> Bulb1 OR Bulb2 OR NightBulb (injected dependency)
Switch(AnyBulb){ //pass it whichever bulb you like
AnyBulb.Toggle();
}
Modifying James Example for Switch and Bulb:
public class SwitchTest {
TestToggleBulb() {
MockBulb mockbulb = new MockBulb();
// MockBulb is a subclass of Bulb, so we can
// "inject" it here:
Switch switch = new Switch(mockBulb);
switch.ToggleBulb();
mockBulb.AssertToggleWasCalled();
}
}
public class Switch {
private Bulb myBulb;
public Switch() {
myBulb = new Bulb();
}
public Switch(Bulb useThisBulbInstead) {
myBulb = useThisBulbInstead;
}
public void ToggleBulb() {
...
myBulb.Toggle();
...
}
}`
A: In simple words dependency injection (DI) is the way to remove dependencies or tight coupling between different object. Dependency Injection gives a cohesive behavior to each object.
DI is the implementation of IOC principal of Spring which says "Don't call us we will call you". Using dependency injection programmer doesn't need to create object using the new keyword.
Objects are once loaded in Spring container and then we reuse them whenever we need them by fetching those objects from Spring container using getBean(String beanName) method.
A: from Book Apress.Spring.Persistence.with.Hibernate.Oct.2010
The purpose of dependency injection is to decouple the work of
resolving external software components from your application business
logic.Without dependency injection, the details of how a component
accesses required services can get muddled in with the component’s
code. This not only increases the potential for errors, adds code
bloat, and magnifies maintenance complexities; it couples components
together more closely, making it difficult to modify dependencies when
refactoring or testing.
A: Dependency Injection (DI) is one from Design Patterns, which uses the basic feature of OOP - the relationship in one object with another object. While inheritance inherits one object to do more complex and specific another object, relationship or association simply creates a pointer to another object from one object using attribute. The power of DI is in combination with other features of OOP as are interfaces and hiding code.
Suppose, we have a customer (subscriber) in the library, which can borrow only one book for simplicity.
Interface of book:
package com.deepam.hidden;
public interface BookInterface {
public BookInterface setHeight(int height);
public BookInterface setPages(int pages);
public int getHeight();
public int getPages();
public String toString();
}
Next we can have many kind of books; one of type is fiction:
package com.deepam.hidden;
public class FictionBook implements BookInterface {
int height = 0; // height in cm
int pages = 0; // number of pages
/** constructor */
public FictionBook() {
// TODO Auto-generated constructor stub
}
@Override
public FictionBook setHeight(int height) {
this.height = height;
return this;
}
@Override
public FictionBook setPages(int pages) {
this.pages = pages;
return this;
}
@Override
public int getHeight() {
// TODO Auto-generated method stub
return height;
}
@Override
public int getPages() {
// TODO Auto-generated method stub
return pages;
}
@Override
public String toString(){
return ("height: " + height + ", " + "pages: " + pages);
}
}
Now subscriber can have association to the book:
package com.deepam.hidden;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Subscriber {
BookInterface book;
/** constructor*/
public Subscriber() {
// TODO Auto-generated constructor stub
}
// injection I
public void setBook(BookInterface book) {
this.book = book;
}
// injection II
public BookInterface setBook(String bookName) {
try {
Class<?> cl = Class.forName(bookName);
Constructor<?> constructor = cl.getConstructor(); // use it for parameters in constructor
BookInterface book = (BookInterface) constructor.newInstance();
//book = (BookInterface) Class.forName(bookName).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return book;
}
public BookInterface getBook() {
return book;
}
public static void main(String[] args) {
}
}
All the three classes can be hidden for it's own implementation. Now we can use this code for DI:
package com.deepam.implement;
import com.deepam.hidden.Subscriber;
import com.deepam.hidden.FictionBook;
public class CallHiddenImplBook {
public CallHiddenImplBook() {
// TODO Auto-generated constructor stub
}
public void doIt() {
Subscriber ab = new Subscriber();
// injection I
FictionBook bookI = new FictionBook();
bookI.setHeight(30); // cm
bookI.setPages(250);
ab.setBook(bookI); // inject
System.out.println("injection I " + ab.getBook().toString());
// injection II
FictionBook bookII = ((FictionBook) ab.setBook("com.deepam.hidden.FictionBook")).setHeight(5).setPages(108); // inject and set
System.out.println("injection II " + ab.getBook().toString());
}
public static void main(String[] args) {
CallHiddenImplBook kh = new CallHiddenImplBook();
kh.doIt();
}
}
There are many different ways how to use dependency injection. It is possible to combine it with Singleton, etc., but still in basic it is only association realized by creating attribute of object type inside another object.
The usefulness is only and only in feature, that code, which we should write again and again is always prepared and done for us forward. This is why DI so closely binded with Inversion of Control (IoC) which means, that our program passes control another running module, which does injections of beans to our code. (Each object, which can be injected can be signed or considered as a Bean.) For example in Spring it is done by creating and initialization ApplicationContext container, which does this work for us. We simply in our code create the Context and invoke initialization the beans. In that moment injection has been done automatically.
A: Dependency Injection (DI) is part of Dependency Inversion Principle (DIP) practice, which is also called Inversion of Control (IoC). Basically you need to do DIP because you want to make your code more modular and unit testable, instead of just one monolithic system. So you start identifying parts of the code that can be separated from the class and abstracted away. Now the implementation of the abstraction need to be injected from outside of the class. Normally this can be done via constructor. So you create a constructor that accepts the abstraction as a parameter, and this is called dependency injection (via constructor). For more explanation about DIP, DI, and IoC container you can read Here
A: From Christoffer Noring, Pablo Deeleman's book “Learning Angular - Second Edition”:
"As our applications grow and evolves, each one of our code entities will internally require instances of other objects, which are better known as dependencies in the world of software engineering. The action of passing such dependencies to the dependent client is known as injection, and it also entails the participation of another code entity, named the injector. The injector will take responsibility for instantiating and bootstrapping the required dependencies so they are ready for use from the very moment they are successfully injected in the client. This is very important since the client knows nothing about how to instantiate its own dependencies and is only aware of the interface they implement in order to use them."
From: Anton Moiseev. book “Angular Development with Typescript, Second Edition.”:
“In short, DI helps you write code in a loosely coupled way and makes your code more testable and reusable.”
A: I would propose a slightly different, short and precise definition of what Dependency Injection is, focusing on the primary goal, not on the technical means (following along from here):
Dependency Injection is the process of creating the static, stateless
graph of service objects, where each service is parametrised by its
dependencies.
The objects that we create in our applications (regardless if we use Java, C# or other object-oriented language) usually fall into one of two categories: stateless, static and global “service objects” (modules), and stateful, dynamic and local “data objects”.
The module graph - the graph of service objects - is typically created on application startup. This can be done using a container, such as Spring, but can also be done manually, by passing parameters to object constructors. Both ways have their pros and cons, but a framework definitely isn’t necessary to use DI in your application.
One requirement is that the services must be parametrised by their dependencies. What this means exactly depends on the language and approach taken in a given system. Usually, this takes the form of constructor parameters, but using setters is also an option. This also means that the dependencies of a service are hidden (when invoking a service method) from the users of the service.
When to use? I would say whenever the application is large enough that encapsulating logic into separate modules, with a dependency graph between the modules gives a gain in readability and explorability of the code.
A: What is Dependency Injection (DI)?
As others have said, Dependency Injection(DI) removes the responsibility of direct creation, and management of the lifespan, of other object instances upon which our class of interest (consumer class) is dependent (in the UML sense). These instances are instead passed to our consumer class, typically as constructor parameters or via property setters (the management of the dependency object instancing and passing to the consumer class is usually performed by an Inversion of Control (IoC) container, but that's another topic).
DI, DIP and SOLID
Specifically, in the paradigm of Robert C Martin's SOLID principles of Object Oriented Design, DI is one of the possible implementations of the Dependency Inversion Principle (DIP). The DIP is the D of the SOLID mantra - other DIP implementations include the Service Locator, and Plugin patterns.
The objective of the DIP is to decouple tight, concrete dependencies between classes, and instead, to loosen the coupling by means of an abstraction, which can be achieved via an interface, abstract class or pure virtual class, depending on the language and approach used.
Without the DIP, our code (I've called this 'consuming class') is directly coupled to a concrete dependency and is also often burdened with the responsibility of knowing how to obtain, and manage, an instance of this dependency, i.e. conceptually:
"I need to create/use a Foo and invoke method `GetBar()`"
Whereas after application of the DIP, the requirement is loosened, and the concern of obtaining and managing the lifespan of the Foo dependency has been removed:
"I need to invoke something which offers `GetBar()`"
Why use DIP (and DI)?
Decoupling dependencies between classes in this way allows for easy substitution of these dependency classes with other implementations which also fulfil the prerequisites of the abstraction (e.g. the dependency can be switched with another implementation of the same interface). Moreover, as others have mentioned, possibly the most common reason to decouple classes via the DIP is to allow a consuming class to be tested in isolation, as these same dependencies can now be stubbed and/or mocked.
One consequence of DI is that the lifespan management of dependency object instances is no longer controlled by a consuming class, as the dependency object is now passed into the consuming class (via constructor or setter injection).
This can be viewed in different ways:
*
*If lifespan control of dependencies by the consuming class needs to be retained, control can be re-established by injecting an (abstract) factory for creating the dependency class instances, into the consumer class. The consumer will be able to obtain instances via a Create on the factory as needed, and dispose of these instances once complete.
*Or, lifespan control of dependency instances can be relinquished to an IoC container (more about this below).
When to use DI?
*
*Where there likely will be a need to substitute a dependency for an equivalent implementation,
*Any time where you will need to unit test the methods of a class in isolation of its dependencies,
*Where uncertainty of the lifespan of a dependency may warrant experimentation (e.g. Hey, MyDepClass is thread safe - what if we make it a singleton and inject the same instance into all consumers?)
Example
Here's a simple C# implementation. Given the below Consuming class:
public class MyLogger
{
public void LogRecord(string somethingToLog)
{
Console.WriteLine("{0:HH:mm:ss} - {1}", DateTime.Now, somethingToLog);
}
}
Although seemingly innocuous, it has two static dependencies on two other classes, System.DateTime and System.Console, which not only limit the logging output options (logging to console will be worthless if no one is watching), but worse, it is difficult to automatically test given the dependency on a non-deterministic system clock.
We can however apply DIP to this class, by abstracting out the the concern of timestamping as a dependency, and coupling MyLogger only to a simple interface:
public interface IClock
{
DateTime Now { get; }
}
We can also loosen the dependency on Console to an abstraction, such as a TextWriter. Dependency Injection is typically implemented as either constructor injection (passing an abstraction to a dependency as a parameter to the constructor of a consuming class) or Setter Injection (passing the dependency via a setXyz() setter or a .Net Property with {set;} defined). Constructor Injection is preferred, as this guarantees the class will be in a correct state after construction, and allows the internal dependency fields to be marked as readonly (C#) or final (Java). So using constructor injection on the above example, this leaves us with:
public class MyLogger : ILogger // Others will depend on our logger.
{
private readonly TextWriter _output;
private readonly IClock _clock;
// Dependencies are injected through the constructor
public MyLogger(TextWriter stream, IClock clock)
{
_output = stream;
_clock = clock;
}
public void LogRecord(string somethingToLog)
{
// We can now use our dependencies through the abstraction
// and without knowledge of the lifespans of the dependencies
_output.Write("{0:yyyy-MM-dd HH:mm:ss} - {1}", _clock.Now, somethingToLog);
}
}
(A concrete Clock needs to be provided, which of course could revert to DateTime.Now, and the two dependencies need to be provided by an IoC container via constructor injection)
An automated Unit Test can be built, which definitively proves that our logger is working correctly, as we now have control over the dependencies - the time, and we can spy on the written output:
[Test]
public void LoggingMustRecordAllInformationAndStampTheTime()
{
// Arrange
var mockClock = new Mock<IClock>();
mockClock.Setup(c => c.Now).Returns(new DateTime(2015, 4, 11, 12, 31, 45));
var fakeConsole = new StringWriter();
// Act
new MyLogger(fakeConsole, mockClock.Object)
.LogRecord("Foo");
// Assert
Assert.AreEqual("2015-04-11 12:31:45 - Foo", fakeConsole.ToString());
}
Next Steps
Dependency injection is invariably associated with an Inversion of Control container(IoC), to inject (provide) the concrete dependency instances, and to manage lifespan instances. During the configuration / bootstrapping process, IoC containers allow the following to be defined:
*
*mapping between each abstraction and the configured concrete implementation (e.g. "any time a consumer requests an IBar, return a ConcreteBar instance")
*policies can be set up for the lifespan management of each dependency, e.g. to create a new object for each consumer instance, to share a singleton dependency instance across all consumers, to share the same dependency instance only across the same thread, etc.
*In .Net, IoC containers are aware of protocols such as IDisposable and will take on the responsibility of Disposing dependencies in line with the configured lifespan management.
Typically, once IoC containers have been configured / bootstrapped, they operate seamlessly in the background allowing the coder to focus on the code at hand rather than worrying about dependencies.
The key to DI-friendly code is to avoid static coupling of classes, and not to use new() for the creation of Dependencies
As per above example, decoupling of dependencies does require some design effort, and for the developer, there is a paradigm shift needed to break the habit of newing dependencies directly, and instead trusting the container to manage dependencies.
But the benefits are many, especially in the ability to thoroughly test your class of interest.
Note : The creation / mapping / projection (via new ..()) of POCO / POJO / Serialization DTOs / Entity Graphs / Anonymous JSON projections et al - i.e. "Data only" classes or records - used or returned from methods are not regarded as Dependencies (in the UML sense) and not subject to DI. Using new to project these is just fine.
A: Dependency injection is the heart of the concept related with Spring Framework.While creating the framework of any project spring may perform a vital role,and here dependency injection come in pitcher.
Actually,Suppose in java you created two different classes as class A and class B, and whatever the function are available in class B you want to use in class A, So at that time dependency injection can be used.
where you can crate object of one class in other,in the same way you can inject an entire class in another class to make it accessible.
by this way dependency can be overcome.
DEPENDENCY INJECTION IS SIMPLY GLUING TWO CLASSES AND AT THE SAME TIME KEEPING THEM SEPARATE.
A: Dependency Injection is a practice where objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally. This means that any object implementing the interface which is required by the object can be substituted in without changing the code, which simplifies testing, and improves decoupling.
For example, consider these clases:
public class PersonService {
public void addManager( Person employee, Person newManager ) { ... }
public void removeManager( Person employee, Person oldManager ) { ... }
public Group getGroupByManager( Person manager ) { ... }
}
public class GroupMembershipService() {
public void addPersonToGroup( Person person, Group group ) { ... }
public void removePersonFromGroup( Person person, Group group ) { ... }
}
In this example, the implementation of PersonService::addManager and PersonService::removeManager would need an instance of the GroupMembershipService in order to do its work. Without Dependency Injection, the traditional way of doing this would be to instantiate a new GroupMembershipService in the constructor of PersonService and use that instance attribute in both functions. However, if the constructor of GroupMembershipService has multiple things it requires, or worse yet, there are some initialization "setters" that need to be called on the GroupMembershipService, the code grows rather quickly, and the PersonService now depends not only on the GroupMembershipService but also everything else that GroupMembershipService depends on. Furthermore, the linkage to GroupMembershipService is hardcoded into the PersonService which means that you can't "dummy up" a GroupMembershipService for testing purposes, or to use a strategy pattern in different parts of your application.
With Dependency Injection, instead of instantiating the GroupMembershipService within your PersonService, you'd either pass it in to the PersonService constructor, or else add a Property (getter and setter) to set a local instance of it. This means that your PersonService no longer has to worry about how to create a GroupMembershipService, it just accepts the ones it's given, and works with them. This also means that anything which is a subclass of GroupMembershipService, or implements the GroupMembershipService interface can be "injected" into the PersonService, and the PersonService doesn't need to know about the change.
A: The whole point of Dependency Injection (DI) is to keep application source code clean and stable:
*
*clean of dependency initialization code
*stable regardless of dependency used
Practically, every design pattern separates concerns to make future changes affect minimum files.
The specific domain of DI is delegation of dependency configuration and initialization.
Example: DI with shell script
If you occasionally work outside of Java, recall how source is often used in many scripting languages (Shell, Tcl, etc., or even import in Python misused for this purpose).
Consider simple dependent.sh script:
#!/bin/sh
# Dependent
touch "one.txt" "two.txt"
archive_files "one.txt" "two.txt"
The script is dependent: it won't execute successfully on its own (archive_files is not defined).
You define archive_files in archive_files_zip.sh implementation script (using zip in this case):
#!/bin/sh
# Dependency
function archive_files {
zip files.zip "$@"
}
Instead of source-ing implementation script directly in the dependent one, you use an injector.sh "container" which wraps both "components":
#!/bin/sh
# Injector
source ./archive_files_zip.sh
source ./dependent.sh
The archive_files dependency has just been injected into dependent script.
You could have injected dependency which implements archive_files using tar or xz.
Example: removing DI
If dependent.sh script used dependencies directly, the approach would be called dependency lookup (which is opposite to dependency injection):
#!/bin/sh
# Dependent
# dependency look-up
source ./archive_files_zip.sh
touch "one.txt" "two.txt"
archive_files "one.txt" "two.txt"
Now the problem is that dependent "component" has to perform initialization itself.
The "component"'s source code is neither clean nor stable because every changes in initialization of dependencies requires new release for "components"'s source code file as well.
Last words
DI is not as largely emphasized and popularized as in Java frameworks.
But it's a generic approach to split concerns of:
*
*application development (single source code release lifecycle)
*application deployment (multiple target environments with independent lifecycles)
Using configuration only with dependency lookup does not help as number of configuration parameters may change per dependency (e.g. new authentication type) as well as number of supported types of dependencies (e.g. new database type).
A: All the above answers are good, my aim is to explain the concept in a simple way so that anyone without a programming knowledge can also understand concept
Dependency injection is one of the design pattern that help us to create complex systems in a simpler manner.
We can see a wide variety of application of this pattern in our day to day life.
Some of the examples are Tape recorder, VCD, CD Drive etc.
The above image is an image of Reel-to-reel portable tape recorder, mid-20th century. Source.
The primary intention of a tape recorder machine is to record or playback sound.
While designing a system it require a reel to record or playback sound or music. There are two possibilities for designing this system
*
*we can place the reel inside the machine
*we can provide a hook for the reel where it can be placed.
If we use the first one we need to open the machine to change the reel.
if we opt for the second one, that is placing a hook for reel, we are getting an added benefit of playing any music by changing the reel. and also reducing the function only to playing whatever in the reel.
Like wise dependency injection is the process of externalizing the dependencies to focus only on the specific functionality of the component so that independent components can be coupled together to form a complex system.
The main benefits we achieved by using dependency injection.
*
*High cohesion and loose coupling.
*Externalizing dependency and looking only on responsibility.
*Making things as components and to combine to form a large systems with high capabilities.
*It helps to develop high quality components since they are independently developed they are properly tested.
*It helps to replace the component with another if one fails.
Now a days these concept forms the basis of well known frameworks in programming world.
The Spring Angular etc are the well-known software frameworks built on the top of this concept
Dependency injection is a pattern used to create instances of objects that other objects rely upon without knowing at compile time which class will be used to provide that functionality or simply the way of injecting properties to an object is called dependency injection.
Example for Dependency injection
Previously we are writing code like this
Public MyClass{
DependentClass dependentObject
/*
At somewhere in our code we need to instantiate
the object with new operator inorder to use it or perform some method.
*/
dependentObject= new DependentClass();
dependentObject.someMethod();
}
With Dependency injection, the dependency injector will take off the instantiation for us
Public MyClass{
/* Dependency injector will instantiate object*/
DependentClass dependentObject
/*
At somewhere in our code we perform some method.
The process of instantiation will be handled by the dependency injector
*/
dependentObject.someMethod();
}
You can also read
Difference between Inversion of Control & Dependency Injection
A: The best definition I've found so far is one by James Shore:
"Dependency Injection" is a 25-dollar
term for a 5-cent concept. [...]
Dependency injection means giving an
object its instance variables. [...].
There is an article by Martin Fowler that may prove useful, too.
Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.
Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g. Spring) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.
A: Dependency Injection is passing dependency to other objects or framework( dependency injector).
Dependency injection makes testing easier. The injection can be done through constructor.
SomeClass() has its constructor as following:
public SomeClass() {
myObject = Factory.getObject();
}
Problem:
If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.
Alternative solution:
*
*Passing myObject in as an argument to the constructor
public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
myObject can be passed directly which makes testing easier.
*
*One common alternative is defining a do-nothing constructor. Dependency injection can be done through setters. (h/t @MikeVella).
*Martin Fowler documents a third alternative (h/t @MarcDix), where classes explicitly implement an interface for the dependencies programmers wish injected.
It is harder to isolate components in unit testing without dependency injection.
In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.
A: Example, we have 2 class Client and Service. Client will use Service
public class Service {
public void doSomeThingInService() {
// ...
}
}
Without Dependency Injection
Way 1)
public class Client {
public void doSomeThingInClient() {
Service service = new Service();
service.doSomeThingInService();
}
}
Way 2)
public class Client {
Service service = new Service();
public void doSomeThingInClient() {
service.doSomeThingInService();
}
}
Way 3)
public class Client {
Service service;
public Client() {
service = new Service();
}
public void doSomeThingInClient() {
service.doSomeThingInService();
}
}
1) 2) 3) Using
Client client = new Client();
client.doSomeThingInService();
Advantages
*
*Simple
Disadvantages
*
*Hard for test Client class
*When we change Service constructor, we need to change code in all place create Service object
Use Dependency Injection
Way 1) Constructor injection
public class Client {
Service service;
Client(Service service) {
this.service = service;
}
// Example Client has 2 dependency
// Client(Service service, IDatabas database) {
// this.service = service;
// this.database = database;
// }
public void doSomeThingInClient() {
service.doSomeThingInService();
}
}
Using
Client client = new Client(new Service());
// Client client = new Client(new Service(), new SqliteDatabase());
client.doSomeThingInClient();
Way 2) Setter injection
public class Client {
Service service;
public void setService(Service service) {
this.service = service;
}
public void doSomeThingInClient() {
service.doSomeThingInService();
}
}
Using
Client client = new Client();
client.setService(new Service());
client.doSomeThingInClient();
Way 3) Interface injection
Check https://en.wikipedia.org/wiki/Dependency_injection
===
Now, this code is already follow Dependency Injection and it is easier for test Client class.
However, we still use new Service() many time and it is not good when change Service constructor. To prevent it, we can use DI injector like
1) Simple manual Injector
public class Injector {
public static Service provideService(){
return new Service();
}
public static IDatabase provideDatatBase(){
return new SqliteDatabase();
}
public static ObjectA provideObjectA(){
return new ObjectA(provideService(...));
}
}
Using
Service service = Injector.provideService();
2) Use library: For Android dagger2
Advantages
*
*Make test easier
*When you change the Service, you only need to change it in Injector class
*If you use use Constructor Injection, when you look at constructor of Client, you will see how many dependency of Client class
Disadvantages
*
*If you use use Constructor Injection, the Service object is created when Client created, sometime we use function in Client class without use Service so created Service is wasted
Dependency Injection definition
https://en.wikipedia.org/wiki/Dependency_injection
A dependency is an object that can be used (Service)
An injection is the passing of a dependency (Service) to a dependent object (Client) that would use it
A: The accepted answer is a good one - but I would like to add to this that DI is very much like the classic avoiding of hardcoded constants in the code.
When you use some constant like a database name you'd quickly move it from the inside of the code to some config file and pass a variable containing that value to the place where it is needed. The reason to do that is that these constants usually change more frequently than the rest of the code. For example if you'd like to test the code in a test database.
DI is analogous to this in the world of Object Oriented programming. The values there instead of constant literals are whole objects - but the reason to move the code creating them out from the class code is similar - the objects change more frequently then the code that uses them. One important case where such a change is needed is tests.
A: Let's try simple example with Car and Engine classes, any car need an engine to go anywhere, at least for now. So below how code will look without dependency injection.
public class Car
{
public Car()
{
GasEngine engine = new GasEngine();
engine.Start();
}
}
public class GasEngine
{
public void Start()
{
Console.WriteLine("I use gas as my fuel!");
}
}
And to instantiate the Car class we will use next code:
Car car = new Car();
The issue with this code that we tightly coupled to GasEngine and if we decide to change it to ElectricityEngine then we will need to rewrite Car class. And the bigger the application the more issues and headache we will have to add and use new type of engine.
In other words with this approach is that our high level Car class is dependent on the lower level GasEngine class which violate Dependency Inversion Principle(DIP) from SOLID. DIP suggests that we should depend on abstractions, not concrete classes. So to satisfy this we introduce IEngine interface and rewrite code like below:
public interface IEngine
{
void Start();
}
public class GasEngine : IEngine
{
public void Start()
{
Console.WriteLine("I use gas as my fuel!");
}
}
public class ElectricityEngine : IEngine
{
public void Start()
{
Console.WriteLine("I am electrocar");
}
}
public class Car
{
private readonly IEngine _engine;
public Car(IEngine engine)
{
_engine = engine;
}
public void Run()
{
_engine.Start();
}
}
Now our Car class is dependent on only the IEngine interface, not a specific implementation of engine.
Now, the only trick is how do we create an instance of the Car and give it an actual concrete Engine class like GasEngine or ElectricityEngine. That's where Dependency Injection comes in.
Car gasCar = new Car(new GasEngine());
gasCar.Run();
Car electroCar = new Car(new ElectricityEngine());
electroCar.Run();
Here we basically inject(pass) our dependency(Engine instance) to Car constructor. So now our classes have loose coupling between objects and their dependencies, and we can easily add new types of engines without changing the Car class.
The main benefit of the Dependency Injection that classes are more loosely coupled, because they do not have hard-coded dependencies. This follows the Dependency Inversion Principle, which was mentioned above. Instead of referencing specific implementations, classes request abstractions (usually interfaces) which are provided to them when the class is constructed.
So in the end Dependency injection is just a technique for
achieving loose coupling between objects and their dependencies.
Rather than directly instantiating dependencies that class needs in
order to perform its actions, dependencies are provided to the class
(most often) via constructor injection.
Also when we have many dependencies it is very good practice to use Inversion of Control(IoC) containers which we can tell which interfaces should be mapped to which concrete implementations for all our dependencies and we can have it resolve those dependencies for us when it constructs our object. For example, we could specify in the mapping for the IoC container that the IEngine dependency should be mapped to the GasEngine class and when we ask the IoC container for an instance of our Car class, it will automatically construct our Car class with a GasEngine dependency passed in.
UPDATE: Watched course about EF Core from Julie Lerman recently and also liked her short definition about DI.
Dependency injection is a pattern to allow your application to inject
objects on the fly to classes that need them, without forcing those
classes to be responsible for those objects. It allows your code to be
more loosely coupled, and Entity Framework Core plugs in to this same
system of services.
A: What is dependency Injection?
Dependency Injection(DI) means to decouple the objects which are dependent on each other. Say object A is dependent on Object B so the idea is to decouple these object from each other. We don’t need to hard code the object using new keyword rather sharing dependencies to objects at runtime in spite of compile time.
If we talk about
How Dependency Injection works in Spring:
We don’t need to hard code the object using new keyword rather define the bean dependency in the configuration file. The spring container will be responsible for hooking up all.
Inversion of Control (IOC)
IOC is a general concept and it can be expressed in many different ways and Dependency Injection is one concrete example of IOC.
Two types of Dependency Injection:
*
*Constructor Injection
*Setter Injection
1. Constructor-based dependency injection:
Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
public class Triangle {
private String type;
public String getType(){
return type;
}
public Triangle(String type){ //constructor injection
this.type=type;
}
}
<bean id=triangle" class ="com.test.dependencyInjection.Triangle">
<constructor-arg value="20"/>
</bean>
2. Setter-based dependency injection:
Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
public class Triangle{
private String type;
public String getType(){
return type;
}
public void setType(String type){ //setter injection
this.type = type;
}
}
<!-- setter injection -->
<bean id="triangle" class="com.test.dependencyInjection.Triangle">
<property name="type" value="equivialteral"/>
NOTE:
It is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies. Note that the if we use annotation based than @Required annotation on a setter can be used to make setters as a required dependencies.
A: The best analogy I can think of is the surgeon and his assistant(s) in an operation theater, where the surgeon is the main person and his assistant who provides the various surgical components when he needs it so that the surgeon can concentrate on the one thing he does best (surgery). Without the assistant the surgeon has to get the components himself every time he needs one.
DI for short, is a technique to remove a common additional responsibility (burden) on components to fetch the dependent components, by providing them to it.
DI brings you closer to the Single Responsibility (SR) principle, like the surgeon who can concentrate on surgery.
When to use DI : I would recommend using DI in almost all production projects ( small/big), particularly in ever changing business environments :)
Why : Because you want your code to be easily testable, mockable etc so that you can quickly test your changes and push it to the market. Besides why would you not when you there are lots of awesome free tools/frameworks to support you in your journey to a codebase where you have more control.
A: It means that objects should only have as many dependencies as is needed to do their job and the dependencies should be few. Furthermore, an object’s dependencies should be on interfaces and not on “concrete” objects, when possible. (A concrete object is any object created with the keyword new.) Loose coupling promotes greater reusability, easier maintainability, and allows you to easily provide “mock” objects in place of expensive services.
The “Dependency Injection” (DI) is also known as “Inversion of Control” (IoC), can be used as a technique for encouraging this loose coupling.
There are two primary approaches to implementing DI:
*
*Constructor injection
*Setter injection
Constructor injection
It’s the technique of passing objects dependencies to its constructor.
Note that the constructor accepts an interface and not concrete object. Also, note that an exception is thrown if the orderDao parameter is null. This emphasizes the importance of receiving a valid dependency. Constructor Injection is, in my opinion, the preferred mechanism for giving an object its dependencies. It is clear to the developer while invoking the object which dependencies need to be given to the “Person” object for proper execution.
Setter Injection
But consider the following example… Suppose you have a class with ten methods that have no dependencies, but you’re adding a new method that does have a dependency on IDAO. You could change the constructor to use Constructor Injection, but this may force you to changes to all constructor calls all over the place. Alternatively, you could just add a new constructor that takes the dependency, but then how does a developer easily know when to use one constructor over the other. Finally, if the dependency is very expensive to create, why should it be created and passed to the constructor when it may only be used rarely? “Setter Injection” is another DI technique that can be used in situations such as this.
Setter Injection does not force dependencies to be passed to the constructor. Instead, the dependencies are set onto public properties exposed by the object in need. As implied previously, the primary motivators for doing this include:
*
*Supporting dependency injection without having to modify the constructor of a legacy class.
*Allowing expensive resources or services to be created as late as possible and only when needed.
Here is the example of how the above code would look like:
public class Person {
public Person() {}
public IDAO Address {
set { addressdao = value; }
get {
if (addressdao == null)
throw new MemberAccessException("addressdao" +
" has not been initialized");
return addressdao;
}
}
public Address GetAddress() {
// ... code that uses the addressdao object
// to fetch address details from the datasource ...
}
// Should not be called directly;
// use the public property instead
private IDAO addressdao;
A: Let's imagine that you want to go fishing:
*
*Without dependency injection, you need to take care of everything yourself. You need to find a boat, to buy a fishing rod, to look for bait, etc. It's possible, of course, but it puts a lot of responsibility on you. In software terms, it means that you have to perform a lookup for all these things.
*With dependency injection, someone else takes care of all the preparation and makes the required equipment available to you. You will receive ("be injected") the boat, the fishing rod and the bait - all ready to use.
A: This is the most simple explanation about Dependency Injection and Dependency Injection Container I have ever seen:
Without Dependency Injection
*
*Application needs Foo (e.g. a controller), so:
*Application creates Foo
*Application calls Foo
*
*Foo needs Bar (e.g. a service), so:
*Foo creates Bar
*Foo calls Bar
*
*Bar needs Bim (a service, a repository,
…), so:
*Bar creates Bim
*Bar does something
With Dependency Injection
*
*Application needs Foo, which needs Bar, which needs Bim, so:
*Application creates Bim
*Application creates Bar and gives it Bim
*Application creates Foo and gives it Bar
*Application calls Foo
*
*Foo calls Bar
*
*Bar does something
Using a Dependency Injection Container
*
*Application needs Foo so:
*Application gets Foo from the Container, so:
*
*Container creates Bim
*Container creates Bar and gives it Bim
*Container creates Foo and gives it Bar
*Application calls Foo
*
*Foo calls Bar
*
*Bar does something
Dependency Injection and dependency Injection Containers are different things:
*
*Dependency Injection is a method for writing better code
*a DI Container is a tool to help injecting dependencies
You don't need a container to do dependency injection. However a container can help you.
A: I know there are already many answers, but I found this very helpful: http://tutorials.jenkov.com/dependency-injection/index.html
No Dependency:
public class MyDao {
protected DataSource dataSource = new DataSourceImpl(
"driver", "url", "user", "password");
//data access methods...
public Person readPerson(int primaryKey) {...}
}
Dependency:
public class MyDao {
protected DataSource dataSource = null;
public MyDao(String driver, String url, String user, String password) {
this.dataSource = new DataSourceImpl(driver, url, user, password);
}
//data access methods...
public Person readPerson(int primaryKey) {...}
}
Notice how the DataSourceImpl instantiation is moved into a constructor. The constructor takes four parameters which are the four values needed by the DataSourceImpl. Though the MyDao class still depends on these four values, it no longer satisfies these dependencies itself. They are provided by whatever class creating a MyDao instance.
A: Dependency Injection is a type of implementation of the "Inversion of Control" principle on which is based Frameworks building.
Frameworks as stated in "Design Pattern" of GoF are classes that implement the main control flow logic raising the developer to do that, in this way Frameworks realize the inversion of control principle.
A way to implement as a technique, and not as class hierarchy, this IoC principle it is just Dependency Injection.
DI consists mainly into delegate the mapping of classes instances and type reference to that instances, to an external "entity": an object, static class, component, framework, etc...
Classes instances are the "dependencies", the external binding of the calling component with the class instance through the reference it is the "injection".
Obviously you can implement this technique in many way as you want from OOP point of view, see for example constructor injection, setter injection, interface injection.
Delegating a third party to carry out the task of match a ref to an object it is very useful when you want to completely separate a component that needs some services from the same services implementation.
In this way, when designing components, you can focus exclusively on their architecture and their specific logic, trusting on interfaces for collaborating with other objects without worry about any type of implementation changes of objects/services used, also if the same object you are using will be totally replaced (obviously respecting the interface).
A: Dependency Injection is the practice to make decoupled component agnostic from some of their dependencies, this follow the SOLID guideline that say
Dependency inversion principle: one should "depend upon abstractions,
not concretions.
The better implementation of Dependency Injection is the Composition Root design pattern, as it's allow your components to be decoupled from the dependency injection container.
I recommand this great article on Composition Root
http://blog.ploeh.dk/2011/07/28/CompositionRoot/
written by Mark Seemann
here is essential points from this article:
A Composition Root is a (preferably) unique location in an application
where modules are composed together.
...
Only applications should have Composition Roots. Libraries and
frameworks shouldn't.
...
A DI Container should only be referenced from the Composition Root.
All other modules should have no reference to the container.
The documentation of Di-Ninja, a dependency injection framework, is a very good example to demonstrate how works the principles of Composition Root and Dependency Injection.
https://github.com/di-ninja/di-ninja
As I know, is the only one DiC in javascript that implement the Composition-Root design pattern.
A: we can achieve a Dependency injection to know it:
class Injector {
constructor() {
this.dependencies = {};
this.register = (key, value) => {
this.dependencies[key] = value;
};
}
resolve(...args) {
let func = null;
let deps = null;
let scope = null;
const self = this;
if (typeof args[0] === 'string') {
func = args[1];
deps = args[0].replace(/ /g, '').split(',');
scope = args[2] || {};
} else {
func = args[0];
deps = func.toString().match(/^function\s*[^\(]*\(\s*([^\)]*)\)/m)[1].replace(/ /g, '').split(',');
scope = args[1] || {};
}
return (...args) => {
func.apply(scope || {}, deps.map(dep => self.dependencies[dep] && dep != '' ? self.dependencies[dep] : args.shift()));
}
}
}
injector = new Injector();
injector.register('module1', () => { console.log('hello') });
injector.register('module2', () => { console.log('world') });
var doSomething1 = injector.resolve(function (module1, module2, other) {
module1();
module2();
console.log(other);
});
doSomething1("Other");
console.log('--------')
var doSomething2 = injector.resolve('module1,module2,', function (a, b, c) {
a();
b();
console.log(c);
});
doSomething2("Other");
above is a implementation by javascript
A: Any nontrivial application is made up of two or more classes that collaborate with each other to perform some business logic. Traditionally, each object is responsible for obtaining its own references to the objects it collaborates with (its dependencies). When applying DI, the objects are given their dependencies at creation time by some external entity that coordinates each object in the system. In other words, dependencies are injected into objects.
For further details please see enter link description here
A: DI is how real objects actually interact with each other without one object being responsible for the existence of another object. Objects should be treated in equality. They are all objects. No one should act like a creator. This is how you do justice to your objects.
Simple example:
if you need a physician, you simply go and find (an existing) one. You will not be thinking of creating a physician from scratch to help you. He already exists and he may serve you or other objects. He has the right to exist whether you (a single object) needs him or not because his purpose is to serve one or more objects. Who decided his existence is Almighty God, not natural selection. Therefore, one advantage of DI is to avoid creating useless redundant objects living without a purpose during the lifetime of your universe (i.e. application).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3548"
}
|
Q: Data visualization in desktop applications I would like to create data visualizations in desktop apps, using frameworks, languages and libraries that help with this kind of task. Visualizations should be interactive: clickable, draggable, customizable, animated...
What I would like to create is something similar to the examples seen here: http://www.visualcomplexity.com/vc/
These are the links I already know: http://delicious.com/laura_laura/visualization?setcount=100
The preferred language is C++/Visual C++ (MFC) because I'm familiar with it, but any other technology is welcome, I would like to make a list from "as similar as possible" to Visual C++ to "very different" from Visual C++.
WPF, flex, Adobe Air, flare, JavaScript (running in a browser as client-side apps with access to local files or as desktop apps) are possibilities, post any good links to examples, tutorials, how-tos, etc. that you know of.
What are the learning curves and complexity for the different options? Which one would you choose and why? Which one have you already worked with and how was your experience? How would you start with a project of this characteristics?
A: Your post has far too many questions in it to be answered easily in one response, so you might try re-posting with specific questions. Data visualization is a HUGE area of study and it's not significantly different for web applications versus desktop applications.
Put simply, it's the display of data in a way that visually tells the story of the data. It's most useful in cases where the volume of data is such that tabular display isn't effective. Trends, outliers, and abnormal occurrences can sometimes only be seen when data is represented visually. Visually can be a simple chart, or it can be more advanced visualizations such as treemaps or thematic mapping/GIS presentations.
If it's an area you're interested in studying, look into:
Edward Tufte - Author, professor, and all-around guru for the display of information
Many Eyes - from IBM AlphaWorks
Processing - A visual "sketching" language based on Java
Visualizing Data - An O'Reilly book by Ben Fry, one of the co-creators of Processing
Beyond that, I think specifics would depend on what you want to accomplish -- what data is being analyzed, who the audience is, and what the desired "message" is.
A: If you're willing to use the Flash/Flex/ActionScript/AIR development platform, then take a look at the "flare" library, from the prefuse project:
http://flare.prefuse.org/
I've only gotten my feet wet with it at this point, but so far I like what I see.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you create tests for "make check" with GNU autotools I'm using GNU autotools for the build system on a particular project. I want to start writing automated tests for verifcation. I would like to just type "make check" to have it automatically run these. My project is in C++, although I am still curious about writing automated tests for other languages as well.
Is this compatible with pretty much every unit testing framework out there (I was thinking of using cppunit)? How do I hook these unit testing frameworks into make check? Can I make sure that I don't require the unit test software to be installed to be able to configure and build the rest of the project?
A: You seem to be asking 2 questions in the first paragraph.
The first is about adding tests to the GNU autotools toolchain - but those tests, if I'm understanding you correctly, are for both validating that the environment necessary to build your application exists (dependent libraries and tools) as well as adapt the build to the environment (platform specific differences).
The second is about unit testing your C++ application and where to invoke those tests, you've proposed doing so from the autotools tool chain, presumably from the configure script. Doing that isn't conventional though - putting a 'test' target in your Makefile is a more conventional way of executing your test suite. The typical steps for building and installing an application with autotools (at least from a user's perspective, not from your, the developer, perspective) is to run the configure script, then run make, then optionally run make test and finally make install.
For the second issue, not wanting cppunit to be a dependency, why not just distribute it with your c++ application? Can you just put it right in what ever archive format you're using (be it tar.gz, tar.bz2 or .zip) along with your source code. I've used cppunit in the past and was happy with it, having used JUnit and other xUnit style frameworks.
A: To make test run when you issue make check, you need to add them to the TESTS variable
Assuming you've already built the executable that runs the unit tests, you just add the name of the executable to the TESTS variable like this:
TESTS=my-test-executable
It should then be automatically run when you make check, and if the executable returns a non-zero value, it will report that as a test failure. If you have multiple unit test executables, just list them all in the TESTS variable:
TESTS=my-first-test my-second-test my-third-test
and they will all get run.
A: Here is a method without dependencies:
#src/Makefile.am
check_PROGRAMS = test1 test2
test1_SOURCES = test/test1.c code_needed_to_test1.h code_needed_to_test1.c
test2_SOURCES = test/test2.c code_needed_to_test2.h code_needed_to_test2.c
TESTS = $(check_PROGRAMS)
The make check will naturally work and show formatted and summarized output:
$ make check
...
PASS: test1
PASS: test2
============================================================================
Testsuite summary for foo 1.0
============================================================================
# TOTAL: 2
# PASS: 2
# SKIP: 0
# XFAIL: 0
# FAIL: 0
# XPASS: 0
# ERROR: 0
============================================================================
*
*When you do a make dist nothing from src/test/* will be
in the tarball. Test code is not in the dist, only source will be.
*When you do a make distcheck it will run make check and run your tests.
A: I'm using Check 0.9.10
configure.ac
Makefile.am
src/Makefile.am
src/foo.c
tests/check_foo.c
tests/Makefile.am
*
*./configure.ac
PKG_CHECK_MODULES([CHECK], [check >= 0.9.10])
*./tests/Makefile.am for test codes
TESTS = check_foo
check_PROGRAMS = check_foo
check_foo_SOURCES = check_foo.c $(top_builddir)/src/foo.h
check_foo_CFLAGS = @CHECK_CFLAGS@
*and write test code, ./tests/check_foo.c
START_TEST (test_foo)
{
ck_assert( foo() == 0 );
ck_assert_int_eq( foo(), 0);
}
END_TEST
/// And there are some tcase_xxx codes to run this test
Using check you can use timeout and raise signal. it is very helpful.
A: You can use Automake's TESTS to run programs generated with check_PROGRAMS but this will assume that you are using a log driver and a compiler for the output. It is probably easier to still use check_PROGRAMS but to invoke the test suite using a local rule in the Makefile:
check_PROGRAMS=testsuite
testsuite_SOURCES=...
testsuite_CFLAGS=...
testsuite_LDADD=...
check-local:
./testsuite
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
}
|
Q: VB.NET - Application has encountered a user-defined breakpoint I'm not that up on VB.NET, the application I'm working on was not written by myself.
It works fine through the IDE but once I run it from the exe it gives me the above error.
Any clues?
This is really hacking me off!
A: The only user defined break point that I can think of is
Debugger.Break()
So, I would suspect that the .exe is compiled in debug mode. I would recommend Reflector to look at the code and find out for sure whether or not there is a Debugger.Break() somewhere in there.
A: Afaik, the only way this could occur if you are compiling under debugging settings. You should be able to fix it by doing the following:
*
*Right-click your solution on the
solution explorer.
*Select configuration properties.
*At the top of the dialog box there should be a
combobox, which will most likely say
"Active(Debug)".
*Click on the dropdown and select release.
*Ok out of everything.
*Build > Rebuild Solution.
Source: p2p.wrox.com
A: I believe the exe file was compiled using the "Debug" setting. Try changing the Build setting to Release and do a full build (rebuild) of the project. Then try to run the executable file. It should then run normally.
The reason you see that error is because when you normally compile and run applications in Visual Studio, it compiles a Debug build of the executable. The different between a debug build and a release build is that the debug build has additional information added to it, by the compiler, so it can be debugged properly.
A: I would suggest looking for stop in your code. That is what generated this error for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Performance penalty on putting classes in aspx and ascx codebehinds What's the performance penalty on defining classes in an aspx/ascx codebehind rather than compiling them into a dll beforehand? I know that this isn't a best practice and that there are numerous problems with this (e.g. difficult to unit test, code is not reusable, etc.), but it does come in very handy when you're dealing with classes that need to be modified on the fly several times a day since those modifications will not require any sort of app restart (e.g. App_Code changes, updating dlls in bin folder).
A: "None." The codebehind classes are compiled into a DLL on the fly, and then that DLL is kept around. So basically the first time you load the page there will be a short delay, but afterwards the speed should be the same as with precompiled classes.
A: You should see no performance issue after the initial compile. It sounds as though you have business logic that is changing frequently, and not necessarily the web pages.
A: The choice of whether to use dynamic compilation or compiled DLLs really has to do with how organized your release process is. If your application is tightly compiled into DLLs than you can expect that you've tested for build errors and expect things to be more sturdy when you release. With dynamic compilation you have the ability to swap out .cs files on the fly (e.g. drag & drop, ftp). This means you may be more agile, but you might not have that extra step of assurance that helps you know you're keeping the build intact.
A: Collateral damage - session resets
From personal experience, users are much more likely to complain about session reset caused by App Domain recycling than about slight performance hit. So if you can shift your changes from code to data and avoid code updates altogether, by all means do it. This will improve your users' performance :)
A: I don't believe there really is a performance penalty after the initial dynamic compilation (which will occur on the first hit to the page whose code-behind was modified). How did you end up having to change classes several times a day? That would suck!
EDIT:
I should've added that this shouldn't affect unit tests or the code-reusability like you stated. There's nothing stopping you from deploying a non-pre-compiled site for maintainability purposes while still being able to run unit tests, deploying compiled assemblies for other projects (if needed), etc. during a check-in/build.
However, if you're not using source control and don't have an automated build, then there's a whole new problem. Our team members used to edit CODE files directly on production servers. shivers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Write VB6 on Visual Studio 2008 without .NET support? I have to continue to support VB6 applications. I've got both VB6 (Visual Studio 6) installed and Visual Studio 2008 as well. Can I read and write to VB6 projects while in Visual Studio 2008? Will it damage or destroy my VB6 application? It would be very cool if I could free up a lot of space and get rid of Visual Studio 6.
A: The VB6 IDE will coexist along side the Visual Studio 2008 quite happily.
The VB.NET LANGUAGE is related but not compatible with VB6. Conversion between VB6 and VB.NET is problematic. There are a lot of subtle and gross differences between the two making them effectively separate languages.
You need to keep both separate IDES and libraries installed on your computer in order to deal with both languages.
If you need for the two interoperate you can do this by creating COM libraries. Both languages can consume COM Libraries created in the other.
A: Visual Studio 2008 can't compile VB6 applications. You could use it as a text editor only (though it will offer you the VB.NET IntelliSense, not VB6). However, you need Visual Studio 6 to be able to build your application.
A: If you remove VB6 you won't be able to build your VB6 apps? VS2002/3/5/8 doesn't know how to compile VB6 projects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: JQuery TypeWatch Functionality in Delphi TypeWatch is a JQuery plugin that monitors the time between key strokes in a text input box.
It allows for features like refreshing of search results as a user types their search terms, as demonstrated in the 'Users' page in Stack Overflow.
If you are typing in the name of a user you wish to seach for and pause typing for half a second the search result for what you have already entered will appear.
Does anyone have any examples or info on how you could monitor an textbox in delphi in a similar manner, as the user is typing trigger another event if this have stopped typing for a certain period of time, say half a second.
A: You can look at the idea behind the AutoComplete feature of the regular ComboBox.
Or implement a Timer that is reset to 0 at each Keypress in your Edit, and fires its onTimer event handler when it reaches the delay you specified (i.e. after no key entry for this interval of time).
I'm pretty sure there are free components available that implement this...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: 3d to 2d Projection Matrix I have 3 points in a 3D space of which I know the exact locations. Suppose they are: (x0,y0,z0), (x1,y1,z1) and (x2,y2,z2).
Also I have a camera that is looking at these 3 points and I know the 2D locations of those three points on camera view plane. So for example (x0,y0,z0) will be (x0',y0'), and (x1,y1,z1) will be (x1',y1') and (x2,y2,z2) will be (x2',y2') from the camera's point of view.
What is the easiest way to find the projection matrix that will project those 3D points into 2D points on camera view plane. We don't know anything about the camera location.
A: Your camera has (at least) 7 degrees of freedom - 3 for position, 3 for orientation and 1 for FOV. I'm sure someone will correct me if I'm wrong, but it doesn't seem like 3 points are enough for a full solution.
For a generalised solution to this problem, look up 'View Correlation' in Graphics Gems II.
A: What you are looking for is called a Pose Estimation algorithm. Have a look at the POSIT implementation in OpenCV: http://opencv.willowgarage.com/documentation/c/calib3d_camera_calibration_and_3d_reconstruction.html#posit
You will need four or more points, and they may not lie in the same plane.
A tutorial for this implementation is here:
http://opencv.willowgarage.com/wiki/Posit
Do take care though: in the tutorial a square viewport is used, so all view-coordinates are in the -1,-1 to 1,1 range. This leads one to assume that these should be in the camera coordinate system (before aspect-ratio correction). This is not the case, so if you use a viewport with e.g. a 4:3 aspect ratio then your input coordinates should be in the -1.3333,-1 to 1.3333,1 range.
By the way, if your points must lie in the same plane, then you can also look at the CameraCalibration algorithm from OpenCV, but this is more involved to set up and requires more points as input. However it will also yield you the distortion information and intrinsic parameters of your camera.
A: This gives you two sets, each of three equations in 3 variables:
a*x0+b*y0+c*z0 = x0'
a*x1+b*y1+c*z1 = x1'
a*x2+b*y2+c*z2 = x2'
d*x0+e*y0+f*z0 = y0'
d*x1+e*y1+f*z1 = y1'
d*x2+e*y2+f*z2 = y2'
Just use whatever method of solving simultaneous equations is easiest in your situation (it isn't even hard to solve these "by hand"). Then your transformation matrix is just ((a,b,c)(d,e,f)).
...
Actually, that is over-simplified and assumes a camera pointed at the origin of your 3D coordinate system and no perspective.
For perspective, the transformation matrix works more like:
( a, b, c, d ) ( xt )
( x, y, z, 1 ) ( e, f, g, h ) = ( yt )
( i, j, k, l ) ( zt )
( xv, yv ) = ( xc+s*xt/zt, yc+s*yt/zt ) if md < zt;
but the 4x3 matrix is more constrained than 12 degrees of freedom since we should have
a*a+b*b+c*c = e*e+f*f+g*g = i*i+j*j+k*k = 1
a*a+e*e+i*i = b*b+f*f+j*j = c*c+g*g+k*k = 1
So you should probably have 4 points to get 8 equations to cover the 6 variables for camera position and angle and 1 more for scaling of the 2-D view points since we'll be able to eliminate the "center" coordinates (xc,yc).
So if you have 4 points and transform your 2-D view points to be relative to the center of your display, then you can get 14 simultaneous equations in 13 variables and solve.
Unfortunately, six of the equations are not linear equations. Fortunately, all of the variables in those equations are restricted to the values between -1 and 1 so it is still probably feasible to solve the equations.
A: I don't think there is enough information to find a definitive solution. Without knowing your camera location and without knowing your view plane, there is an infinite number of matrices that can solve this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: What's the (JavaScript) Regular Expression I should use to ensure a string is a valid file name? I'm still learning RegEx at the moment, but for the time being could someone help me out with this? I have a few special requirements for formatting the string:
*
*No directories. JUST the file name.
*File name needs to be all lowercase.
*Whitespaces need to be replaced with underscores.
Shouldn't be hard, but I'm pressed for time and I'm not sure on the 'correct' way to ensure a valid file name (namely I forget which characters were supposed to be invalid for file names).
A: If you're in a super-quick hurry, you can usually find acceptable regular expressions in the library at http://regexlib.com/.
Edit to say: Here's one that might work for you:
([0-9a-z_-]+[\.][0-9a-z_-]{1,3})$
A: If you're taking a string path from the user (eg. by reading the .value of a file upload field), you can't actually be sure what the path separator character is. It might be a backslash (Windows), forward slash (Linux, OS X, BSD etc.) or something else entirely on old or obscure OSs. Splitting the path on either forward or backslash will cover the common cases, but it's a good idea to include the ability for the user to override the filename in case we guessed wrong.
As for 'invalid characters' these too depend on the operating system. Probably the easiest path is to replace all non-alphanumerics with a placeholder such as an underscore.
Here's what I use:
var parts= path.split('\\');
parts= parts[parts.length-1].split('/');
var filename= parts[parts.length-1].toLowerCase();
filename= filename.replace(new RegExp('[^a-z0-9]+', 'g'), '_');
if (filename=='') filename= '_'
A: And a simple combination of RegExp and other javascript is what I would recommend:
var a = "c:\\some\\path\\to\\a\\file\\with Whitespace.TXT";
a = a.replace(/^.*[\\\/]([^\\\/]*)$/i,"$1");
a = a.replace(/\s/g,"_");
a = a.toLowerCase();
alert(a);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I add a using Element with Prototype in IE6? Using Prototype 1.6's "new Element(...)" I am trying to create a <table> element with both a <thead> and <tbody> but nothing happens in IE6.
var tableProto = new Element('table').update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>');
I'm then trying to inject copies of it like this:
$$('div.question').each(function(o) {
Element.insert(o, { after:$(tableProto.cloneNode(true)) });
});
My current workaround is to create a <div> instead of a <table> element, and then "update" it with all of the table HTML.
How does one successfully do this?
A: As it turns out, there's nothing wrong with the example code I provided in the question--it works in IE6 just fine. The issue I was facing is that I was also specifying a class for the <table> element in the constructor incorrectly, but omitted that from my example.
The "real" code was as follows, and is incorrect:
var tableProto = new Element('table', { class:'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>');
This works correctly in Firefox, but fails in IE6 because it is wrong.
The correct way to add attributes to an element via this constructor is to provides strings, not just attribute names. The following code works in both browsers:
var tableProto = new Element('table', { 'class':'hide-on-screen'} ).update('<thead><tr><th>Situation Task</th><th>Action</th><th>Result</th></tr></thead><tbody><tr><td>a</td><td>b</td><td>c</td></tr></tbody>');
There is an error due to "class" being a reserved word in JavaScript. Doh!
Let this be a lesson to those who don't supply their actual code!
A: If prototypes' .update() method internally tries to set the .innerHTML it will fail in IE. In IE, the .innerHTML of a table element is readonly.
Source:
http://webbugtrack.blogspot.com/2007/12/bug-210-no-innerhtml-support-on-tables.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do you determine Daylight Savings Time in VBA? What function will let us know whether a date in VBA is in DST or not?
A: For non-current dates (DST 2007+):
First, you need a function to find the number of specific weekdays in a month:
Public Function NDow(Y As Integer, M As Integer, _
N As Integer, DOW As Integer) As Date
' Returns Date of Nth Day of the Week in Month
NDow = DateSerial(Y, M, (8 - Weekday(DateSerial(Y, M, 1), _
(DOW + 1) Mod 8)) + ((N - 1) * 7))
End Function
Then, you can check for the DST day versus the following function calls:
Fall: NDow(Year(newdate), 11, 1, 1)
Spring: NDow(Year(newdate), 3, 2, 1)
For the current date:
Call the Windows API function GetTimeZoneInformation,
and it will return an enum (integer) with the status.
I got the code for this from Chip Pearson's great Excel site.
Pearson's site
A: For anyone wondering how to account for daylight saving time in Europe (central europe time), I modified the script from Chip Pearson. The last sunday of March (2 AM to 3 AM) and October (3 AM to 2 AM) are the days when the hour switching occurs.
Following code is the click event of a button in Excel:
Dim dates As String
dates = "A1:A20"
For Each c In Worksheets("Sheet1").Range(dates).Cells
If (IsDateWithinDST(c.Value)) Then
c.Value = DateAdd("h", 1, c.Value)
End If
Next
The module containing the necessary methods are to be found here.
More info on DST in Europe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Global or Singleton for database connection? What is the benefit of using singleton instead of global for database connections in PHP? I feel using singleton instead of global makes the code unnecessarily complex.
Code with Global
$conn = new PDO(...);
function getSomething()
{
global $conn;
.
.
.
}
Code with Singleton
class DB_Instance
{
private static $db;
public static function getDBO()
{
if (!self::$db)
self::$db = new PDO(...);
return self::$db;
}
}
function getSomething()
{
$conn = DB_Instance::getDBO();
.
.
.
}
If there's a better way of initializing database connection other than global or singleton, please mention it and describe the advantages it have over global or singleton.
A: The singleton method was created to make sure there was only one instance of any class. But, because people use it as a way to shortcut globalizing, it becomes known as lazy and/or bad programming.
Therefore, I would ignore global and Singleton since both are not really OOP.
What you were looking for is dependency injection.
You can check on easy to read PHP based information related to dependency injection (with examples) at http://components.symfony-project.org/dependency-injection/trunk/book/01-Dependency-Injection
A: Both patterns achieve the same net effect, providing one single access point for your database calls.
In terms of specific implementation, the singleton has a small advantage of not initiating a database connection until at least one of your other methods requests it. In practice in most applications I've written, this doesn't make much of a difference, but it's a potential advantage if you have some pages/execution paths which don't make any database calls at all, since those pages won't ever request a connection to the database.
One other minor difference is that the global implementation may trample over other variable names in the application unintentionally. It's unlikely that you'll ever accidentally declare another global $db reference, though it's possible that you could overwrite it accidentally ( say, you write if($db = null) when you meant to write if($db == null). The singleton object prevents that.
A: If you're not going to use a persistent connection, and there are cases for not doing that, I find a singleton to be conceptually more palatable than a global in OO design.
In a true OO architecture, a singleton is more effective than creating a new instance the object each time.
A: On the given example, I see no reason to use singletons. As a rule of thumb if my only concern is to allow a single instance of an object, if the language allows it, I prefer to use globals
A: I'm not sure I can answer your specific question, but wanted to suggest that global / singleton connection objects may not be the best idea if this if for a web-based system. DBMSs are generally designed to manage large numbers of unique connections in an efficient manner. If you are using a global connection object, then you are doing a couple of things:
*
*Forcing you pages to do all database
connections sequentially and killing
any attempts at asyncronous page
loads.
*Potentially holding open locks on
database elements longer than
necessary, slowing down overall
database performance.
*Maxing out the total number of
simultaneous connections your
database can support and blocking
new users from accessing the
resources.
I am sure there are other potential consequences as well. Remember, this method will attempt to sustain a database connection for every user accessing the site. If you only have one or two users, not a problem. If this is a public website and you want traffic then scalability will become an issue.
[EDIT]
In larger scaled situations, creating new connections everytime you hit the datase can be bad. However, the answer is not to create a global connection and reuse it for everything. The answer is connection pooling.
With connection pooling, a number of distinct connections are maintained. When a connection is required by the application the first available connection from the pool is retrieved and then returned to the pool once its job is done. If a connection is requested and none are available one of two things will happen: a) if the maximum number of allowed connection is not reached, a new connection is opened, or b) the application is forced to wait for a connection to become available.
Note: In .Net languages, connection pooling is handled by the ADO.Net objects by default (the connection string sets all the required information).
Thanks to Crad for commenting on this.
A: I know this is old, but Dr8k's answer was almost there.
When you are considering writing a piece of code, assume it's going to change. That doesn't mean that you're assuming the kinds of changes it will have hoisted upon it at some point in the future, but rather that some form of change will be made.
Make it a goal mitigate the pain of making changes in the future: a global is dangerous because it's hard to manage in a single spot. What if I want to make that database connection context aware in the future? What if I want it to close and reopen itself every 5th time it was used. What if I decide that in the interest of scaling my app I want to use a pool of 10 connections? Or a configurable number of connections?
A singleton factory gives you that flexibility. I set it up with very little extra complexity and gain more than just access to the same connection; I gain the ability to change how that connection is passed to me later on in a simple manner.
Note that I say singleton factory as opposed to simply singleton. There's precious little difference between a singleton and a global, true. And because of that, there's no reason to have a singleton connection: why would you spend the time setting that up when you could create a regular global instead?
What a factory gets you is a why to get connections, and a separate spot to decide what connections (or connection) you're going to get.
Example
class ConnectionFactory
{
private static $factory;
private $db;
public static function getFactory()
{
if (!self::$factory)
self::$factory = new ConnectionFactory(...);
return self::$factory;
}
public function getConnection() {
if (!$this->db)
$this->db = new PDO(...);
return $this->db;
}
}
function getSomething()
{
$conn = ConnectionFactory::getFactory()->getConnection();
.
.
.
}
Then, in 6 months when your app is super famous and getting dugg and slashdotted and you decide you need more than a single connection, all you have to do is implement some pooling in the getConnection() method. Or if you decide that you want a wrapper that implements SQL logging, you can pass a PDO subclass. Or if you decide you want a new connection on every invocation, you can do do that. It's flexible, instead of rigid.
16 lines of code, including braces, which will save you hours and hours and hours of refactoring to something eerily similar down the line.
Note that I don't consider this "Feature Creep" because I'm not doing any feature implementation in the first go round. It's border line "Future Creep", but at some point, the idea that "coding for tomorrow today" is always a bad thing doesn't jive for me.
A: In general I would use a singleton for a database connection... You don't want to create a new connection everytime you need to interact to the database... This might hurt perfomance and bandwidth of your network... Why create a new one, when there's one available... Just my 2 cents...
RWendi
A: It is quite simple. Never use global OR Singleton.
A: As advice both singleton and global are valid and can be joined within the same system, project, plugin, product, etc ...
In my case, I make digital products for web (plugin).
I use only singleton in the main class and I use it by principle. I almost do not use it because I know that the main class will not instantiate it again
<?php // file0.php
final class Main_Class
{
private static $instance;
private $time;
private final function __construct()
{
$this->time = 0;
}
public final static function getInstance() : self
{
if (self::$instance instanceof self) {
return self::$instance;
}
return self::$instance = new self();
}
public final function __clone()
{
throw new LogicException("Cloning timer is prohibited");
}
public final function __sleep()
{
throw new LogicException("Serializing timer is prohibited");
}
public final function __wakeup()
{
throw new LogicException("UnSerializing timer is prohibited");
}
}
Global use for almost all the secondary classes, example:
<?php // file1.php
global $YUZO;
$YUZO = new YUZO; // YUZO is name class
while at runtime I can use Global to call their methods and attributes in the same instance because I do not need another instance of my main product class.
<?php // file2.php
global $YUZO;
$YUZO->method1()->run();
$YUZO->method2( 'parameter' )->html()->print();
I get with the global is to use the same instance to be able to make the product work because I do not need a factory for instances of the same class, usually the instance factory is for large systems or for very rare purposes.
In conclusion:, you must if you already understand well that is the anti-pattern Singleton and understand the Global, you can use one of the 2 options or mix them but if I recommend not to abuse since there are many programmers who are very exception and faithful to the programming OOP, use it for main and secondary classes that you use a lot within the execution time. (It saves you a lot of CPU).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
}
|
Q: How to build a Debian/Ubuntu package from source? I have the source of a program (taken from cvs/svn/git/...) and I'd like to build a Debian/Ubuntu package for it. The package is present in the repositories, but:
*
*It is an older version (lacking features I need)
*I need slightly different compile options than the default.
What is the easiest way of doing it? I am concerned about a couple of things
*
*How can I check if I have listed all the dependencies correctly? (I can get some hints by looking on what the older version depended, but new dependencies may have been added.)
*How I can I prevent the update system installing the older version in the repo on an update?
*How I can prevent the system installing a newer version (when its out), overwriting my custom package?
A: you can use the special package "checkinstall" for all packages which are not even in debian/ubuntu yet.
You can use "uupdate" (apt-get install devscripts) to build a package from source with existing debian sources:
Example for libdrm2:
apt-get build-dep libdrm2
apt-get source libdrm2
cd libdrm-2.3.1
uupdate ~/Downloads/libdrm-2.4.1.tar.gz
cd ../libdrm-2.4.1
dpkg-buildpackage -us -uc -nc
A: Sample Ubuntu-based build for ccache:
sudo apt-get update
sudo apt-get build-dep ccache
apt-get -b source ccache
sudo dpkg -i ccache*.deb
More details: http://blog.aplikacja.info/2011/11/building-packages-from-sources-in-debianubuntu/
A: For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".
Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing
zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules
Then make the changes you wanted to compile options, and build the package by doing
dpkg-buildpackage -rfakeroot -us -uc
A: I believe this is the Debian package 'bible'.
Well, it's the Debian new maintainer's guide, so a lot of it won't be applicable, but they do cover what goes where.
A: *
*put "debian" directory from original package to your source directory
*use "dch" to update version of package
*use "debuild" to build the package
A: First, the title question:
Assuming the debian directory is already there, be in the source directory (the directory containing the debian directory) and invoke dpkg-buildpackage. I like to run it with these options:
dpkg-buildpackage -us -uc -nc
which mean don't sign the result and don't clean.
How can I check if I have listed all the dependencies correctly?
Getting the dependencies is a black art. The "official" way is to check build depends is if the package builds with only the base system, the "build-essential" packages, and the build dependencies you have specified. Don't know a general answer for regular Dependencies, just wade in :)
How I can I prevent the update system installing the older version in the repo on an update?
How I can prevent the system installing a newer version (when its out), overwriting my custom package?
My knowledge might be out of date on this one, but to address both:
Use dpkg --set-selections. Assuming nullidentd was the package you wanted to stay put, run as root
echo 'nullidentd hold' | dpkg --set-selections
Alternately, since you are building from source, you can use an epoch to set the version number artificially high and never be bothered again. To use an epoch, add a new entry to the debian/changelog file, and put a 99: in front of the version number. Given my nullidentd example, the first line of your updated changelog would read:
nullidentd (99:1.0-4) unstable; urgency=low
Bernard's link is good, especially if you have to create the debian directory yourself - also helpful are the developers reference and the general resource page. Adam's link also looks good but I'm not familiar with it.
A: If you're using Ubuntu, check out the pkgcreator project:
http://code.google.com/p/pkgcreator
A: Here is a tutorial for building a Debian package.
Basically, you need to:
*
*Set up your folder structure
*Create a control file
*Optionally create postinst or prerm scripts
*Run dpkg-deb
I usually do all of this in my Makefile so I can just type make to spit out the binary and package it in one go.
A:
How can I check if I have listed all the dependencies correctly?
The pbuilder is an excellent tool for checking both build dependencies and dependencies by setting up a clean base system within a chroot environment. By compiling the package within pbuilder, you can easily check the build dependencies, and by testing it within a pbuilder environment, you can check the dependencies.
A: If you want a quick and dirty way of installing the build dependencies, use:
apt-get build-dep
This installs the dependencies. You need sources lines in your sources.list for this:
deb-src http://ftp.nl.debian.org/debian/ squeeze-updates main contrib non-free
If you are backporting packages from testing to stable, please be advised that the dependencies might have changed. The command apt-get build-deb installs dependencies for the source packages in your current repository.
But of course, dpkg-buildpackage -us -uc will show you any uninstalled dependencies.
If you want to compile more often, use cowbuilder.
apt-get install cowbuilder
Then create a build-area:
sudo DIST=squeeze ARCH=amd64 cowbuilder --create
Then compile a source package:
apt-get source cowsay
# do your magic editing
dpkg-source -b cowsay-3.03+dfsg1 # build the new source packages
cowbuilder --build cowsay_3.03+dfsg1-2.dsc # build the packages from source
Watch where cowbuilder puts the resulting package.
Good luck!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "118"
}
|
Q: Introduction to C# list comprehensions How can I perform list comprehensions in C#?
A: A List Comprehension is a type of set notation in which the programmer can describe the properties that the members of a set must meet. It is usually used to create a set based on other, already existing, set or sets by applying some type of combination, transform or reduction function to the existing set(s).
Consider the following problem: You have a sequence of 10 numbers from 0 to 9 and you need to extract all the even numbers from that sequence. In a language such a C# version 1.1, you were pretty much confined to the following code to solve this problem:
ArrayList evens = new ArrayList();
ArrayList numbers = Range(10);
int size = numbers.Count;
int i = 0;
while (i < size)
{
if (i % 2 == 0)
{
evens.Add(i);
}
i++;
}
The code above does not show the implementation of the Range function, which is available in the full code listing below. With the advent of C# 3.0 and the .NET Framework 3.5, a List Comprehension notation based on Linq is now available to C# programmers. The above C# 1.1 code can be ported to C# 3.0 like so:
IEnumerable<int> numbers = Enumerable.Range(0, 10);
var evens = from num in numbers where num % 2 == 0 select num;
And technically speaking, the C# 3.0 code above could be written as a one-liner by moving the call to Enumarable.Range to the Linq expression that generates the evens sequence. In the C# List Comprehension I am reducing the set numbers by applying a function (the modulo 2) to that sequence. This produces the evens sequence in a much more concise manner and avoid the use of loop syntax. Now, you may ask yourself: Is this purely syntax sugar? I don't know, but I will definitelly investigate, and maybe even ask the question myself here. I suspect that this is not just syntax sugar and that there are some true optimizations that can be done by utilizing the underlying monads.
The full code listing is available here.
A: Found this when I was looking up how to do list comprehensions in C#...
When someone says list comprehensions I immediately think about Python. The below code generates a list that looks like this:
[0,2,4,6,8,10,12,14,16,18]
The Python way is like this:
list = [2*number for number in range(0,10)]
In C#:
var list2 = from number in Enumerable.Range(0, 10) select 2*number;
Both methods are lazily evaluated.
A: You can use LINQ to make expressions that are similar to list comprehensions. Here's a site explaining it a little:
List Comprehension in C# with LINQ
List Comprehension in C# with LINQ - Part 2
A: @Ian P
return (from user in users
where user.Valid
select user.Name).ToArray();
A: While this isn't a tutorial, here's some code that illustrates the concept:
public List<string> ValidUsers(List<User> users) {
List<string> names = new List<string>();
foreach(User user in users) {
if(user.Valid) {
names.Add(user.Name);
}
}
return names;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "67"
}
|
Q: What is the state of C++ refactor support in Eclipse? Is it at the state where it is actually useful and can do more than rename classes?
A: CDT (C/C++ Development Tools - eclipse project) 5.0 has a bunch of new refactorings
* Declare Method
* Extract Baseclass
* Extract Constant
* Extract Method
* Extract Subclass
* Hide Method
* Implement Method
* Move Field / Method
* Replace Number
* Separate Class
* Generate Getters and Setters
There is a CDT refactoring wiki
A: There have been numerous efforts to provide refactoring tools for C++, most of them failed pretty early, because the creation of such tools requires the full ability to process C++ source code, i.e. you need a working and full c++ compiler in the first place to implement even the most basic forms of automated source to source transformations.
Fortunately, with the introduction of plugins into gcc, it it's finally becoming foreseeable that related efforts may actually be able to leverage an existing C++ compiler for this purpose, instead of having to resort to their own implementations of a C++ compiler.
For a more in depth discussion, you may want to check out this.
For the time being, the most promising candidate to provide widely automated C++ refactoring support, is certainly the Mozilla pork project, along with its related companion project Dehydra.
A: Some C++ refactorings which are supported by for example by Ref++ do not need to fully understand C++ syntax. For example pull up method, push down method etc are quite straightforward. For some reason this kind of refactorings are not implemented to CDT refactorings.
A: Yeah and most of them don't work actually if the code is too complicated. Things like move a method, rename, etc have problems sometimes.
A: C++ is a very hard language to provide refactoring support for. This is because the langauge is very complex and hard to parse but its mostly because of the preprocessor.
The preprocessor is the main reason why C/C++ IDEs lag behind other languages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Keeping a file in the OS block buffer I need to keep as much as I can of large file in the operating system block cache even though it's bigger than I can fit in ram, and I'm continously reading another very very large file. ATM I'll remove large chunk of large important file from system cache when I stream read form another file.
A: Within linux, you can mount a filesystem as the type tmpfs, which uses available swap memory as backing if needed. You should be able to create a filesystem greater than your memory size and it will prioritize the contents of that filesystem in the system cache.
mount -t tmpfs none /mnt/point
See: http://lxr.linux.no/linux/Documentation/filesystems/tmpfs.txt
You may also benefit from the files swapiness and drop_cache within /proc/sys/vm
A: If you're using Windows, consider opening the file you're scanning through with the flag
FILE_FLAG_SEQUENTIAL_SCAN
You could also use
FILE_FLAG_NO_BUFFERING
for that file, but it imposes some restrictions on your read size and buffer alignment.
A: In a POSIX system like Linux or Solaris, try using posix_fadvise.
On the streaming file, do something like this:
posix_fadvise(fd, 0, 0, POSIX_FADV_SEQUENTIAL);
while( bytes > 0 ) {
bytes = pread(fd, buffer, 64 * 1024, current_pos);
current_pos += 64 * 1024;
posix_fadvise(fd, 0, current_pos, POSIX_FADV_DONTNEED);
}
And you can apply POSIX_FADV_WILLNEED to your other file, which should raise its memory priority.
Now, I know that Windows Vista and Server 2008 can also do nifty tricks with memory priorities. Probably older versions like XP can do more basic tricks as well. But I don't know the functions off the top of my head and don't have time to look them up.
A: Some operating systems have ramdisks that you can use to set aside a segment of ram for storage and then mounting it as a file system.
What I don't understand, though, is why you want to keep the operating system from caching the file. Your full question doesn't really make sense to me.
A: Buy more ram (it's relatively cheap!) or let the OS do its thing. I think you'll find that circumventing the OS is going to be more trouble than it's worth. The OS will cache as much of the file as needed, until yours or any other applications needs memory.
I guess you could minimize the number of processes, but it's probably quicker to buy more memory.
A: mlock() and mlockall() respectively lock part or all of the calling process’s virtual address space into RAM, preventing that memory from being paged to the swap area.
(copied from the MLOCK(2) Linux man page)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Design & Coding - top to bottom or bottom to top? When coding, what in your experience is a better approach?
*
*Break the problem down into small enough pieces and then implement each piece.
*Break the problem down, but then implement using a top-down approach.
*Any other?
A: You might want to look over the Agile Manifesto. Top down and bottom up are predicated on Built It All At Once design and construction.
The "Working software over comprehensive documentation" means the first thing you build is the smallest useful thing you can get running. Top? Bottom? Neither.
When I was younger, I worked on projects that were -- by contract -- strictly top down. This doesn't work. Indeed, it can't work. You get mountains of redundant design and code as a result. It was not a sound approach when applied mindlessly.
What I've noticed is that the Agile approach -- small pieces that work -- tends to break the problem down to parts that can be grasped all at once. The top-down/bottom-up no longer matters as much. Indeed, it may not matter at all.
Which leads do: "How do you decompose for Agile development?" The trick is to avoid creating A Big Thing that you must then decompose. If you analyze a problem, you find actors trying to accomplish use cases and failing because they don't have all the information, or they don't have it in time, or they can't execute their decisions, or something like that.
Often, these aren't Big Things that need decomposition. When they are, you need to work through the problem in the Goals Backward direction. From Goals to things that enable you to make that goal to things that enable the enablers, etc. Since goals are often Big Things, this tends to be Top Down -- from general business goal to detailed business process and step.
At some point, we overview these various steps that lead to the goals. We've done the analysis part (breaking things down). Now comes the synthesis part: we reassemble what we have into things we can actually build. Synthesis is Bottom Up. However, let's not get carried away. We have several points of view, each of which is different.
We have a model. This is often built from details into a larger conceptual model. Then, sometimes decomposed again into a model normalized for OLTP. Or decomposed into a star schema normalized for OLAP. Then we work back up to create a ORM mapping from the normalized model. Up - Down - Up.
We have processing. This is often built from summaries of the business processes down into details of processing steps. Then software is designed around the steps. Then the software is broken into classes and methods. Down - Up - Down.
[Digression. With enlightened users, this decomposition defines new job titles and ways of working. With unenlightened users, the old jobs stay and we write mountains of documentation to map old jobs onto new software.]
We have components. We often look at the pieces, look at what we know about available components, and do a kind of matching. This is the randomest process; it's akin to the way crystals form -- there are centers of nucleation and the design kind of solidifies around those centers. Web Services. Database. Transaction Management. Performance. Volume. Different features that somehow help us pick components that implement some or all of our solution. Often feels bottom-up (from feature to product), but sometimes top-down ("I'm holding a hammer, call everything a nail" == use the RDBMS for everything.)
Eventually we have to code. This is bottom up. Kind of. You have to define a package structure. You have to define classes as a whole. That part was top down. You have to write methods within the classes. I often do this bottom-up -- rough out the method, write a unit test, finish the method. Rough out the next method, write a unit test, finish the method.
The driving principle is Agile -- build something that works. The details are all over the map -- up, down, front, back, data, process, actor, subject area, business value.
A: Yes. Do all of those things.
It may seem sarcastic (sorry, I revert to form), but this really is a case where there is no right answer.
A: Also in the agile way, write your test(s) first!
Then all software is a continual cycle of
*
*Red - the code fails the test
*Green - the code passes the test
*Refactor - code improvements that are intention-preserving.
defects, new features, changes. It all follows the same pattern.
A: I tend to design top-down and implement bottom-up.
For implementation, building the smallest functional pieces and assembling them into the higher-level structures seems to be what works best for me. But, for design, I need to start from the overall picture and break it down to determine what those pieces will be.
A: Here's what I do:
Understand the domain first. Understand the problem to be solved. Make sure you and the customer (even if that customer is you!) are on the same page as to what problem is to be solved.
Then a high level solution is proposed to the problem and from that, the design will turn into bubbles or bullets on a page or whatever, but the point is that it will shake out into components that can be designed.
At that point, I write tests for the yet-to-be written classes and then flesh out the classes to pass those tests.
I use a test-first approach and build working, tested components. That is what works for me. When the component interfaces are known and the 'rules' are known for how they talk to each other and provide services to each other, then it becomes generally a straightforward 'hook everything together' exercise.
That's how I do it, and it has worked well for me.
A: Your 2nd option is a reasonable way to go. If you break the problem down into understandable chunks, the top down approach will reveal any major design flaws before you implement all the little details. You can write stubs for lower level functionality to keep everything hanging together.
A: I think there's more to consider than top- verses bottom-down design. You obviously need to break the design up into manageable units of work but you also need to consider prioritisation etc. And in an iterative development project, you will often redefine the problem for the next iteration once you've delivered the solution for the previous one.
A: When designing, I like to do middle-out. I like to model the domain, then design out the classes, move to the database and UI from there. If there are specific features that are UI-based or database-based, I may design those up front as well.
When coding, I generally like to do bottom-up (database first, then business entities, then UI) if at all possible. I find it is a lot easier to keep things straight with this method.
A: I believe that with good software designers (and in my opinion all software developers should also be software designers at some level), the magic is in being able to do top-down and bottom-up simultaneously.
What I was "schooled" to do by my mentors is start by very brief top-down to understand the entities involved, then move to bottom-up to figure out the basic elements I want to create, then to back up and see how I can go one level down, knowing what I know about the results of my bottom up, and so forth until "they meet in the middle".
Hope that helps.
A: Outside-in design.
You start with what you're trying to achieve at the top end, and you know what you've got to work with at the bottom end. Keep working both ends until they meet in the middle.
A: I sort of agree with all of the people saying "neither", but everyone falls somewhere on the spectrum.
I'm more of a top-down kind of guy. I pick one high level feature/point/whatever and implement it as a complete program. This lets me sketch out a basic plan and structure within the confines of the problem domain.
Then I start with another feature and refactor out everything from the original that can be used by the second into new, shared entities. Lather, rinse, repeat until application is complete.
However, I know a lot of people who are bottom up guys, who hear a problem and start thinking about all the support subsystems that they could need to build the application on top of it.
I don't believe either approach is wrong or right. They both can achieve results. I even try and find bottom up guys to work with, as we can attack the problem from two different perspectives.
A: Both are valid approaches. Sometimes one just "feels" more natural than the other. However, there is one big problem: some mainstream languages and especially their frameworks and libraries really heavily on IDE support, such as syntax highlighting, background type checking, background compilation, intelligent code completion, IntelliSense and so on.
However, this doesn't work with top-down coding! In top-down coding, you constantly use variables, fields, constants, functions, procedures, methods, classes, modules, traits, mixins, aspects, packages and types that you haven't implemented yet! So, the IDE will constantly yell at you because of compile errors, there will be red squiggly lines everywhere, you will get no code completion and so on. So, the IDE pretty much prohibits you from doing top-down coding.
A: I do a variant of top-down. I tend to try and do the interface first - I then use that as my list of features. What's good about this version is, it still works with IDE that would otherwise complain. Just comment out the one function call to what's not yet been implemented.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/130933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.