text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to parse a time into a Date object from user input in JavaScript? I am working on a form widget for users to enter a time of day into a text input (for a calendar application). Using JavaScript (we are using jQuery FWIW), I want to find the best way to parse the text that the user enters into a JavaScript Date() object so I can easily perform comparisons and other things on it.
I tried the parse() method and it is a little too picky for my needs. I would expect it to be able to successfully parse the following example input times (in addition to other logically similar time formats) as the same Date() object:
*
*1:00 pm
*1:00 p.m.
*1:00 p
*1:00pm
*1:00p.m.
*1:00p
*1 pm
*1 p.m.
*1 p
*1pm
*1p.m.
*1p
*13:00
*13
I am thinking that I might use regular expressions to split up the input and extract the information I want to use to create my Date() object. What is the best way to do this?
A: A quick solution which works on the input that you've specified:
function parseTime( t ) {
var d = new Date();
var time = t.match( /(\d+)(?::(\d\d))?\s*(p?)/ );
d.setHours( parseInt( time[1]) + (time[3] ? 12 : 0) );
d.setMinutes( parseInt( time[2]) || 0 );
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
It should work for a few other varieties as well (even if a.m. is used, it'll still work - for example). Obviously this is pretty crude but it's also pretty lightweight (much cheaper to use that than a full library, for example).
Warning: The code doe not work with 12:00 AM, etc.
A: All of the examples provided fail to work for times from 12:00 am to 12:59 am. They also throw an error if the regex does not match a time. The following handles this:
function parseTime(timeString) {
if (timeString == '') return null;
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
if (time == null) return null;
var hours = parseInt(time[1],10);
if (hours == 12 && !time[4]) {
hours = 0;
}
else {
hours += (hours < 12 && time[4])? 12 : 0;
}
var d = new Date();
d.setHours(hours);
d.setMinutes(parseInt(time[3],10) || 0);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
This will work for strings which contain a time anywhere inside them. So "abcde12:00pmdef" would be parsed and return 12 pm. If the desired outcome is that it only returns a time when the string only contains a time in them the following regular expression can be used provided you replace "time[4]" with "time[6]".
/^(\d+)(:(\d\d))?\s*((a|(p))m?)?$/i
A: Don't bother doing it yourself, just use datejs.
A: I came across a couple of kinks in implementing John Resig's solution. Here is the modified function that I have been using based on his answer:
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/);
d.setHours( parseInt(time[1]) + ( ( parseInt(time[1]) < 12 && time[4] ) ? 12 : 0) );
d.setMinutes( parseInt(time[3]) || 0 );
d.setSeconds(0, 0);
return d;
} // parseTime()
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
A: Here's a solution more for all of those who are using a 24h clock that supports:
*
*0820 -> 08:20
*32 -> 03:02
*124 -> 12:04
function parseTime(text) {
var time = text.match(/(\d?\d):?(\d?\d?)/);
var h = parseInt(time[1], 10);
var m = parseInt(time[2], 10) || 0;
if (h > 24) {
// try a different format
time = text.match(/(\d)(\d?\d?)/);
h = parseInt(time[1], 10);
m = parseInt(time[2], 10) || 0;
}
var d = new Date();
d.setHours(h);
d.setMinutes(m);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
A: Compilation table of other answers
First of all, I can't believe that there is not a built-in functionality or even a robust third-party library that can handle this. Actually, it's web development so I can believe it.
Trying to test all edge cases with all these different algorithms was making my head spin, so I took the liberty of compiling all the answers and tests in this thread into a handy table.
The code (and resulting table) is pointlessly large to include inline, so I've made a JSFiddle:
http://jsfiddle.net/jLv16ydb/4/show
// heres some filler code of the functions I included in the test,
// because StackOverfleaux wont let me have a jsfiddle link without code
Functions = [
JohnResig,
Qwertie,
PatrickMcElhaney,
Brad,
NathanVillaescusa,
DaveJarvis,
AndrewCetinic,
StefanHaberl,
PieterDeZwart,
JoeLencioni,
Claviska,
RobG,
DateJS,
MomentJS
];
// I didn't include `date-fns`, because it seems to have even more
// limited parsing than MomentJS or DateJS
Please feel free to fork my fiddle and add more algorithms and test cases
I didn't add any comparisons between the result and the "expected" output, because there are cases where the "expected" output could be debated (eg, should 12 be interpreted as 12:00am or 12:00pm?). You will have to go through the table and see which algorithm makes the most sense for you.
Note: The colors do not necessarily indicate quality or "expectedness" of output, they only indicate the type of output:
*
*red = js error thrown
*yellow = "falsy" value (undefined, null, NaN, "", "invalid date")
*green = js Date() object
*light green = everything else
Where a Date() object is the output, I convert it to 24 hr HH:mm format for ease of comparison.
A: This is a more rugged approach that takes into account how users intend to use this type of input. For example, if a user entered "12", they would expect it to be 12pm (noon), and not 12am. The below function handles all of this. It is also available here: http://blog.de-zwart.net/2010-02/javascript-parse-time/
/**
* Parse a string that looks like time and return a date object.
* @return Date object on success, false on error.
*/
String.prototype.parseTime = function() {
// trim it and reverse it so that the minutes will always be greedy first:
var value = this.trim().reverse();
// We need to reverse the string to match the minutes in greedy first, then hours
var timeParts = value.match(/(a|p)?\s*((\d{2})?:?)(\d{1,2})/i);
// This didnt match something we know
if (!timeParts) {
return false;
}
// reverse it:
timeParts = timeParts.reverse();
// Reverse the internal parts:
for( var i = 0; i < timeParts.length; i++ ) {
timeParts[i] = timeParts[i] === undefined ? '' : timeParts[i].reverse();
}
// Parse out the sections:
var minutes = parseInt(timeParts[1], 10) || 0;
var hours = parseInt(timeParts[0], 10);
var afternoon = timeParts[3].toLowerCase() == 'p' ? true : false;
// If meridian not set, and hours is 12, then assume afternoon.
afternoon = !timeParts[3] && hours == 12 ? true : afternoon;
// Anytime the hours are greater than 12, they mean afternoon
afternoon = hours > 12 ? true : afternoon;
// Make hours be between 0 and 12:
hours -= hours > 12 ? 12 : 0;
// Add 12 if its PM but not noon
hours += afternoon && hours != 12 ? 12 : 0;
// Remove 12 for midnight:
hours -= !afternoon && hours == 12 ? 12 : 0;
// Check number sanity:
if( minutes >= 60 || hours >= 24 ) {
return false;
}
// Return a date object with these values set.
var d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + tests[i].parseTime() );
}
This is a string prototype, so you can use it like so:
var str = '12am';
var date = str.parseTime();
A: Lots of answers so one more won't hurt.
/**
* Parse a time in nearly any format
* @param {string} time - Anything like 1 p, 13, 1:05 p.m., etc.
* @returns {Date} - Date object for the current date and time set to parsed time
*/
function parseTime(time) {
var b = time.match(/\d+/g);
// return undefined if no matches
if (!b) return;
var d = new Date();
d.setHours(b[0]>12? b[0] : b[0]%12 + (/p/i.test(time)? 12 : 0), // hours
/\d/.test(b[1])? b[1] : 0, // minutes
/\d/.test(b[2])? b[2] : 0); // seconds
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
To be properly robust, it should check that each value is within range of allowed values, e.g if am/pm hours must be 1 to 12 inclusive, otherwise 0 to 24 inclusive, etc.
A: The time package is 0.9kbs in size. Available with NPM and bower package managers.
Here's an example straight from the README.md:
var t = Time('2p');
t.hours(); // 2
t.minutes(); // 0
t.period(); // 'pm'
t.toString(); // '2:00 pm'
t.nextDate(); // Sep 10 2:00 (assuming it is 1 o'clock Sep 10)
t.format('hh:mm AM') // '02:00 PM'
t.isValid(); // true
Time.isValid('99:12'); // false
A: Most of the regex solutions here throw errors when the string can't be parsed, and not many of them account for strings like 1330 or 130pm. Even though these formats weren't specified by the OP, I find them critical for parsing dates input by humans.
All of this got me to thinking that using a regular expression might not be the best approach for this.
My solution is a function that not only parses the time, but also allows you to specify an output format and a step (interval) at which to round minutes to. At about 70 lines, it's still lightweight and parses all of the aforementioned formats as well as ones without colons.
*
*Demo: http://jsfiddle.net/HwwzS/1/
*Code: https://gist.github.com/claviska/4744736
function parseTime(time, format, step) {
var hour, minute, stepMinute,
defaultFormat = 'g:ia',
pm = time.match(/p/i) !== null,
num = time.replace(/[^0-9]/g, '');
// Parse for hour and minute
switch(num.length) {
case 4:
hour = parseInt(num[0] + num[1], 10);
minute = parseInt(num[2] + num[3], 10);
break;
case 3:
hour = parseInt(num[0], 10);
minute = parseInt(num[1] + num[2], 10);
break;
case 2:
case 1:
hour = parseInt(num[0] + (num[1] || ''), 10);
minute = 0;
break;
default:
return '';
}
// Make sure hour is in 24 hour format
if( pm === true && hour > 0 && hour < 12 ) hour += 12;
// Force pm for hours between 13:00 and 23:00
if( hour >= 13 && hour <= 23 ) pm = true;
// Handle step
if( step ) {
// Step to the nearest hour requires 60, not 0
if( step === 0 ) step = 60;
// Round to nearest step
stepMinute = (Math.round(minute / step) * step) % 60;
// Do we need to round the hour up?
if( stepMinute === 0 && minute >= 30 ) {
hour++;
// Do we need to switch am/pm?
if( hour === 12 || hour === 24 ) pm = !pm;
}
minute = stepMinute;
}
// Keep within range
if( hour <= 0 || hour >= 24 ) hour = 0;
if( minute < 0 || minute > 59 ) minute = 0;
// Format output
return (format || defaultFormat)
// 12 hour without leading 0
.replace(/g/g, hour === 0 ? '12' : 'g')
.replace(/g/g, hour > 12 ? hour - 12 : hour)
// 24 hour without leading 0
.replace(/G/g, hour)
// 12 hour with leading 0
.replace(/h/g, hour.toString().length > 1 ? (hour > 12 ? hour - 12 : hour) : '0' + (hour > 12 ? hour - 12 : hour))
// 24 hour with leading 0
.replace(/H/g, hour.toString().length > 1 ? hour : '0' + hour)
// minutes with leading zero
.replace(/i/g, minute.toString().length > 1 ? minute : '0' + minute)
// simulate seconds
.replace(/s/g, '00')
// lowercase am/pm
.replace(/a/g, pm ? 'pm' : 'am')
// lowercase am/pm
.replace(/A/g, pm ? 'PM' : 'AM');
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
A: Here's an improvement on Joe's version. Feel free to edit it further.
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
d.setHours( parseInt(time[1],10) + ( ( parseInt(time[1],10) < 12 && time[4] ) ? 12 : 0) );
d.setMinutes( parseInt(time[3],10) || 0 );
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
Changes:
*
*Added radix parameter to the parseInt() calls (so jslint won't complain).
*Made the regex case-insenstive so "2:23 PM" works like "2:23 pm"
A: AnyTime.Converter can parse dates/times in many different formats:
http://www.ama3.com/anytime/
A: I have made some modifications to the function above to support a few more formats.
*
*1400 -> 2:00 PM
*1.30 -> 1:30 PM
*1:30a -> 1:30 AM
*100 -> 1:00 AM
Ain't cleaned it up yet but works for everything I can think of.
function parseTime(timeString) {
if (timeString == '') return null;
var time = timeString.match(/^(\d+)([:\.](\d\d))?\s*((a|(p))m?)?$/i);
if (time == null) return null;
var m = parseInt(time[3], 10) || 0;
var hours = parseInt(time[1], 10);
if (time[4]) time[4] = time[4].toLowerCase();
// 12 hour time
if (hours == 12 && !time[4]) {
hours = 12;
}
else if (hours == 12 && (time[4] == "am" || time[4] == "a")) {
hours += 12;
}
else if (hours < 12 && (time[4] != "am" && time[4] != "a")) {
hours += 12;
}
// 24 hour time
else if(hours > 24 && hours.toString().length >= 3) {
if(hours.toString().length == 3) {
m = parseInt(hours.toString().substring(1,3), 10);
hours = parseInt(hours.toString().charAt(0), 10);
}
else if(hours.toString().length == 4) {
m = parseInt(hours.toString().substring(2,4), 10);
hours = parseInt(hours.toString().substring(0,2), 10);
}
}
var d = new Date();
d.setHours(hours);
d.setMinutes(m);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
A: Here's another approach that covers the original answer, any reasonable number of digits, data entry by cats, and logical fallacies. The algorithm follows:
*
*Determine whether meridian is post meridiem.
*Convert input digits to an integer value.
*Time between 0 and 24: hour is the o'clock, no minutes (hours 12 is PM).
*Time between 100 and 2359: hours div 100 is the o'clock, minutes mod 100 remainder.
*Time from 2400 on: hours is midnight, with minutes remainder.
*When hours exceeds 12, subtract 12 and force post meridiem true.
*When minutes exceeds 59, force to 59.
Converting the hours, minutes, and post meridiem to a Date object is an exercise for the reader (numerous other answers show how to do this).
"use strict";
String.prototype.toTime = function () {
var time = this;
var post_meridiem = false;
var ante_meridiem = false;
var hours = 0;
var minutes = 0;
if( time != null ) {
post_meridiem = time.match( /p/i ) !== null;
ante_meridiem = time.match( /a/i ) !== null;
// Preserve 2400h time by changing leading zeros to 24.
time = time.replace( /^00/, '24' );
// Strip the string down to digits and convert to a number.
time = parseInt( time.replace( /\D/g, '' ) );
}
else {
time = 0;
}
if( time > 0 && time < 24 ) {
// 1 through 23 become hours, no minutes.
hours = time;
}
else if( time >= 100 && time <= 2359 ) {
// 100 through 2359 become hours and two-digit minutes.
hours = ~~(time / 100);
minutes = time % 100;
}
else if( time >= 2400 ) {
// After 2400, it's midnight again.
minutes = (time % 100);
post_meridiem = false;
}
if( hours == 12 && ante_meridiem === false ) {
post_meridiem = true;
}
if( hours > 12 ) {
post_meridiem = true;
hours -= 12;
}
if( minutes > 59 ) {
minutes = 59;
}
var result =
(""+hours).padStart( 2, "0" ) + ":" + (""+minutes).padStart( 2, "0" ) +
(post_meridiem ? "PM" : "AM");
return result;
};
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + tests[i].toTime() );
}
With jQuery, the newly defined String prototype is used as follows:
<input type="text" class="time" />
$(".time").change( function() {
var $this = $(this);
$(this).val( time.toTime() );
});
A: I wasn't happy with the other answers so I made yet another one. This version:
*
*Recognizes seconds and milliseconds
*Returns undefined on invalid input such as "13:00pm" or "11:65"
*Returns a local time if you provide a localDate parameter, otherwise returns a UTC time on the Unix epoch (Jan 1, 1970).
*Supports military time like 1330 (to disable, make the first ':' required in the regex)
*Allows an hour by itself, with 24-hour time (i.e. "7" means 7am).
*Allows hour 24 as a synonym for hour 0, but hour 25 is not allowed.
*Requires the time to be at the beginning of the string (to disable, remove ^\s* in the regex)
*Has test code that actually detects when the output is incorrect.
Edit: it's now a package including a timeToString formatter: npm i simplertime
/**
* Parses a string into a Date. Supports several formats: "12", "1234",
* "12:34", "12:34pm", "12:34 PM", "12:34:56 pm", and "12:34:56.789".
* The time must be at the beginning of the string but can have leading spaces.
* Anything is allowed after the time as long as the time itself appears to
* be valid, e.g. "12:34*Z" is OK but "12345" is not.
* @param {string} t Time string, e.g. "1435" or "2:35 PM" or "14:35:00.0"
* @param {Date|undefined} localDate If this parameter is provided, setHours
* is called on it. Otherwise, setUTCHours is called on 1970/1/1.
* @returns {Date|undefined} The parsed date, if parsing succeeded.
*/
function parseTime(t, localDate) {
// ?: means non-capturing group and ?! is zero-width negative lookahead
var time = t.match(/^\s*(\d\d?)(?::?(\d\d))?(?::(\d\d))?(?!\d)(\.\d+)?\s*(pm?|am?)?/i);
if (time) {
var hour = parseInt(time[1]), pm = (time[5] || ' ')[0].toUpperCase();
var min = time[2] ? parseInt(time[2]) : 0;
var sec = time[3] ? parseInt(time[3]) : 0;
var ms = (time[4] ? parseFloat(time[4]) * 1000 : 0);
if (pm !== ' ' && (hour == 0 || hour > 12) || hour > 24 || min >= 60 || sec >= 60)
return undefined;
if (pm === 'A' && hour === 12) hour = 0;
if (pm === 'P' && hour !== 12) hour += 12;
if (hour === 24) hour = 0;
var date = new Date(localDate!==undefined ? localDate.valueOf() : 0);
var set = (localDate!==undefined ? date.setHours : date.setUTCHours);
set.call(date, hour, min, sec, ms);
return date;
}
return undefined;
}
var testSuite = {
'1300': ['1:00 pm','1:00 P.M.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1:00:00PM', '1300', '13'],
'1100': ['11:00am', '11:00 AM', '11:00', '11:00:00', '1100'],
'1359': ['1:59 PM', '13:59', '13:59:00', '1359', '1359:00', '0159pm'],
'100': ['1:00am', '1:00 am', '0100', '1', '1a', '1 am'],
'0': ['00:00', '24:00', '12:00am', '12am', '12:00:00 AM', '0000', '1200 AM'],
'30': ['0:30', '00:30', '24:30', '00:30:00', '12:30:00 am', '0030', '1230am'],
'1435': ["2:35 PM", "14:35:00.0", "1435"],
'715.5': ["7:15:30", "7:15:30am"],
'109': ['109'], // Three-digit numbers work (I wasn't sure if they would)
'': ['12:60', '11:59:99', '-12:00', 'foo', '0660', '12345', '25:00'],
};
var passed = 0;
for (var key in testSuite) {
let num = parseFloat(key), h = num / 100 | 0;
let m = num % 100 | 0, s = (num % 1) * 60;
let expected = Date.UTC(1970, 0, 1, h, m, s); // Month is zero-based
let strings = testSuite[key];
for (let i = 0; i < strings.length; i++) {
var result = parseTime(strings[i]);
if (result === undefined ? key !== '' : key === '' || expected !== result.valueOf()) {
console.log(`Test failed at ${key}:"${strings[i]}" with result ${result ? result.toUTCString() : 'undefined'}`);
} else {
passed++;
}
}
}
console.log(passed + ' tests passed.');
A: Why not use validation to narrow down what a user can put in and simplify the list to only include formats that can be parsed (or parsed after some tweaking).
I don't think it's asking too much to require a user to put a time in a supported format.
dd:dd A(m)/P(m)
dd A(m)/P(m)
dd
A: /(\d+)(?::(\d\d))(?::(\d\d))?\s*([pP]?)/
// added test for p or P
// added seconds
d.setHours( parseInt(time[1]) + (time[4] ? 12 : 0) ); // care with new indexes
d.setMinutes( parseInt(time[2]) || 0 );
d.setSeconds( parseInt(time[3]) || 0 );
thanks
A: An improvement to Patrick McElhaney's solution (his does not handle 12am correctly)
function parseTime( timeString ) {
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*([pP]?)/i);
var h = parseInt(time[1], 10);
if (time[4])
{
if (h < 12)
h += 12;
}
else if (h == 12)
h = 0;
d.setHours(h);
d.setMinutes(parseInt(time[3], 10) || 0);
d.setSeconds(0, 0);
return d;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
A: If you only want seconds here is a one liner
const toSeconds = s => s.split(':').map(v => parseInt(v)).reverse().reduce((acc,e,i) => acc + e * Math.pow(60,i))
A: After thoroughly testing and investigating through my other compilation answer, I concluded that @Dave Jarvis's solution was the closest to what I felt were reasonable outputs and edge-case-handling. For reference, I looked at what Google Calendar's time inputs reformatted the time to after exiting the text box.
Even still, I saw that it didn't handle some (albeit weird) edge cases that Google Calendar did. So I reworked it from the ground up and this is what I came up with. I also added it to my compilation answer.
// attempt to parse string as time. return js date object
function parseTime(string) {
string = String(string);
var am = null;
// check if "apm" or "pm" explicitly specified, otherwise null
if (string.toLowerCase().includes("p")) am = false;
else if (string.toLowerCase().includes("a")) am = true;
string = string.replace(/\D/g, ""); // remove non-digit characters
string = string.substring(0, 4); // take only first 4 digits
if (string.length === 3) string = "0" + string; // consider eg "030" as "0030"
string = string.replace(/^00/, "24"); // add 24 hours to preserve eg "0012" as "00:12" instead of "12:00", since will be converted to integer
var time = parseInt(string); // convert to integer
// default time if all else fails
var hours = 12,
minutes = 0;
// if able to parse as int
if (Number.isInteger(time)) {
// treat eg "4" as "4:00pm" (or "4:00am" if "am" explicitly specified)
if (time >= 0 && time <= 12) {
hours = time;
minutes = 0;
// if "am" or "pm" not specified, establish from number
if (am === null) {
if (hours >= 1 && hours <= 12) am = false;
else am = true;
}
}
// treat eg "20" as "8:00pm"
else if (time >= 13 && time <= 99) {
hours = time % 24;
minutes = 0;
// if "am" or "pm" not specified, force "am"
if (am === null) am = true;
}
// treat eg "52:95" as 52 hours 95 minutes
else if (time >= 100) {
hours = Math.floor(time / 100); // take first two digits as hour
minutes = time % 100; // take last two digits as minute
// if "am" or "pm" not specified, establish from number
if (am === null) {
if (hours >= 1 && hours <= 12) am = false;
else am = true;
}
}
// add 12 hours if "pm"
if (am === false && hours !== 12) hours += 12;
// sub 12 hours if "12:00am" (midnight), making "00:00"
if (am === true && hours === 12) hours = 0;
// keep hours within 24 and minutes within 60
// eg 52 hours 95 minutes becomes 4 hours 35 minutes
hours = hours % 24;
minutes = minutes % 60;
}
// convert to js date object
var date = new Date();
date.setHours(hours);
date.setMinutes(minutes);
date.setSeconds(0);
return date;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '99999', '0000', '0011', '-1', 'mioaw' ];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parseTime(tests[i]) );
}
I feel that this is the closest I can get for my needs, but suggestions are welcome. Note: This is American-centric in that it defaults to am/pm for certain patterns:
*
*1 => 13:00 (1:00pm)
*1100 => 23:00 (11:00pm)
*456 => 16:56 (4:56pm)
A: I've needed a time parser function and based on some of the answers i ended up with this function
function parse(time){
let post_meridiem = time.match(/p/i) !== null;
let result;
time = time.replace(/[^\d:-]/g, '');
let hours = 0;
let minutes = 0;
if (!time) return;
let parts = time.split(':');
if (parts.length > 2) time = parts[0] + ':' + parts[1];
if (parts[0] > 59 && parts.length === 2) time = parts[0];
if (!parts[0] && parts[1] < 60) minutes = parts[1];
else if (!parts[0] && parts[1] >= 60) return;
time = time.replace(/^00/, '24');
time = parseInt(time.replace(/\D/g, ''));
if (time >= 2500) return;
if (time > 0 && time < 24 && parts.length === 1) hours = time;
else if (time < 59) minutes = time;
else if (time >= 60 && time <= 99 && parts[0]) {
hours = ('' + time)[0];
minutes = ('' + time)[1];
} else if (time >= 100 && time <= 2359) {
hours = ~~(time / 100);
minutes = time % 100;
} else if (time >= 2400) {
hours = ~~(time / 100) - 24;
minutes = time % 100;
post_meridiem = false;
}
if (hours > 59 || minutes > 59) return;
if (post_meridiem && hours !== 0) hours += 12;
if (minutes > 59) minutes = 59;
if (hours > 23) hours = 0;
result = ('' + hours).padStart(2, '0') + ':' + ('' + minutes).padStart(2, '0');
return result;
}
var tests = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm','1:00p.m.','1:00p','1 pm',
'1 p.m.','1 p','1pm','1p.m.', '1p', '13:00','13', '1a', '12', '12a', '12p', '12am', '12pm', '2400am', '2400pm', '2400',
'1000', '100', '123', '2459', '2359', '2359am', '1100', '123p',
'1234', '1', '9', '99', '999', '9999', '0000', '0011', '-1', 'mioaw',
"0820",
"32",
"124",
"1330",
"130pm",
"456",
":40",
":90",
"12:69",
"50:90",
"aaa12:34aaa",
"aaa50:00aaa",
];
for ( var i = 0; i < tests.length; i++ ) {
console.log( tests[i].padStart( 9, ' ' ) + " = " + parse(tests[i]) );
}
also it's on Compilation table of other answers here is a fork
Compilation table of other answers
A: The main upvoted and selected answers were causing trouble for me and outputting ridiculous results. Below is my stab at it which seems to solve all the issues most people were having, including mine. An added functionality to mine is the ability to specify 'am' or 'pm' as a time of day to default to should the user input not specify (e.g. 1:00). By default, it's set to 'pm'.
One thing to note is this function assumes the user wants to (and attempted to) provide a string representing a time input. Because of this, the "input validation and sanitation" only goes so far as to rule out anything that would cause an error, not anything that doesn't necessarily look like a time. This is best represented by the final three test entries in the array towards the bottom of the code snippet.
const parseTime = (timeString, assumedTimeOfDay = "pm") => {
// Validate timeString input
if (!timeString) return null
const regex = /(\d{1,2})(\d{2})?([a|p]m?)?/
const noOfDigits = timeString.replace(/[^\d]/g, "").length
if (noOfDigits === 0) return null
// Seconds are unsupported (rare use case in my eyes, feel free to edit)
if (noOfDigits > 4) return null
// Add a leading 0 to prevent bad regex match (i.e. 100 = 1hr 00min, not 10hr 0min)
const sanitized = `${noOfDigits === 3 ? "0" : ""}${timeString}`
.toLowerCase()
.replace(/[^\dapm]/g, "")
const parsed = sanitized.match(regex)
if (!parsed) return null
// Clean up and name parsed data
const {
input,
hours,
minutes,
meridian
} = {
input: parsed[0],
hours: Number(parsed[1] || 0),
minutes: Number(parsed[2] || 0),
// Defaults to pm if user provided assumedTimeOfDay is not am or pm
meridian: /am/.test(`${parsed[3] || assumedTimeOfDay.toLowerCase()}m`) ?
"am" : "pm",
}
// Quick check for valid numbers
if (hours < 0 || hours >= 24 || minutes < 0 || minutes >= 60) return null
// Convert hours to 24hr format
const timeOfDay = hours >= 13 ? "pm" : meridian
const newHours =
hours >= 13 ?
hours :
hours === 12 && timeOfDay === "am" ?
0 :
(hours === 12 && timeOfDay === "pm") || timeOfDay === "am" ?
hours :
hours + 12
// Convert data to Date object and return
return new Date(new Date().setHours(newHours, minutes, 0))
}
const times = [
'12',
'12p',
'12pm',
'12p.m.',
'12 p',
'12 pm',
'12 p.m.',
'12:00',
'12:00p',
'12:00pm',
'12:00p.m.',
'12:00 p',
'12:00 pm',
'12:00 p.m.',
'12:00',
'12:00p',
'12:00pm',
'12:00p.m.',
'12:00 p',
'12:00 pm',
'12:00 p.m.',
'1200',
'1200p',
'1200pm',
'1200p.m.',
'1200 p',
'1200 pm',
'1200 p.m.',
'12',
'1200',
'12:00',
'1',
'1p',
'1pm',
'1p.m.',
'1 p',
'1 pm',
'1 p.m.',
'1:00',
'1:00p',
'1:00pm',
'1:00p.m.',
'1:00 p',
'1:00 pm',
'1:00 p.m.',
'01:00',
'01:00p',
'01:00pm',
'01:00p.m.',
'01:00 p',
'01:00 pm',
'01:00 p.m.',
'0100',
'0100p',
'0100pm',
'0100p.m.',
'0100 p',
'0100 pm',
'0100 p.m.',
'13',
'1300',
'13:00',
'random',
'092fsd9)*(U243',
'092fsd9)*(U'
]
times.map(t => {
const parsed = parseTime(t)
if (parsed) {
console.log(`${parsed.toLocaleTimeString()} from ${t}`)
} else {
console.log(`Invalid Time (${t})`)
}
})
Although I've tested this quite a bit, I'm sure I tunnel-visioned on something. If someone is able to break it (in a reasonable way), please comment and I'll see about updating!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
}
|
Q: How do I find what is using memory in a Python process in a production system? My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a Python memory profiler (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our production system with Heapy because it takes a while to do its thing and its threaded remote interface does not work well in our server.
What I think I want is a way to dump a snapshot of the production Python process (or at least gc.get_objects), and then analyze it offline to see where it is using memory. How do I get a core dump of a python process like this? Once I have one, how do I do something useful with it?
A: Could you record the traffic (via a log) on your production site, then re-play it on your development server instrumented with a python memory debugger? (I recommend dozer: http://pypi.python.org/pypi/Dozer)
A: Make your program dump core, then clone an instance of the program on a sufficiently similar box using gdb. There are special macros to help with debugging python programs within gdb, but if you can get your program to concurrently serve up a remote shell, you could just continue the program's execution, and query it with python.
I have never had to do this, so I'm not 100% sure it'll work, but perhaps the pointers will be helpful.
A: Using Python's gc garbage collector interface and sys.getsizeof() it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak:
rss = psutil.Process(os.getpid()).get_memory_info().rss
# Dump variables if using more than 100MB of memory
if rss > 100 * 1024 * 1024:
memory_dump()
os.abort()
def memory_dump():
dump = open("memory.pickle", 'wb')
xs = []
for obj in gc.get_objects():
i = id(obj)
size = sys.getsizeof(obj, 0)
# referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
if hasattr(obj, '__class__'):
cls = str(obj.__class__)
xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})
cPickle.dump(xs, dump)
Note that I'm only saving data from objects that have a __class__ attribute because those are the only objects I care about. It should be possible to save the complete list of objects, but you will need to take care choosing other attributes. Also, I found that getting the referrers for each object was extremely slow so I opted to save only the referents. Anyway, after the crash, the resulting pickled data can be read back like this:
with open("memory.pickle", 'rb') as dump:
objs = cPickle.load(dump)
Added 2017-11-15
The Python 3.6 version is here:
import gc
import sys
import _pickle as cPickle
def memory_dump():
with open("memory.pickle", 'wb') as dump:
xs = []
for obj in gc.get_objects():
i = id(obj)
size = sys.getsizeof(obj, 0)
# referrers = [id(o) for o in gc.get_referrers(obj) if hasattr(o, '__class__')]
referents = [id(o) for o in gc.get_referents(obj) if hasattr(o, '__class__')]
if hasattr(obj, '__class__'):
cls = str(obj.__class__)
xs.append({'id': i, 'class': cls, 'size': size, 'referents': referents})
cPickle.dump(xs, dump)
A: I will expand on Brett's answer from my recent experience. Dozer package is well maintained, and despite advancements, like addition of tracemalloc to stdlib in Python 3.4, its gc.get_objects counting chart is my go-to tool to tackle memory leaks. Below I use dozer > 0.7 which has not been released at the time of writing (well, because I contributed a couple of fixes there recently).
Example
Let's look at a non-trivial memory leak. I'll use Celery 4.4 here and will eventually uncover a feature which causes the leak (and because it's a bug/feature kind of thing, it can be called mere misconfiguration, cause by ignorance). So there's a Python 3.6 venv where I pip install celery < 4.5. And have the following module.
demo.py
import time
import celery
redis_dsn = 'redis://localhost'
app = celery.Celery('demo', broker=redis_dsn, backend=redis_dsn)
@app.task
def subtask():
pass
@app.task
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
if __name__ == '__main__':
task.delay().get()
Basically a task which schedules a bunch of subtasks. What can go wrong?
I'll use procpath to analyse Celery node memory consumption. pip install procpath. I have 4 terminals:
*
*procpath record -d celery.sqlite -i1 "$..children[?('celery' in @.cmdline)]" to record the Celery node's process tree stats
*docker run --rm -it -p 6379:6379 redis to run Redis which will serve as Celery broker and result backend
*celery -A demo worker --concurrency 2 to run the node with 2 workers
*python demo.py to finally run the example
(4) will finish under 2 minutes.
Then I use sqliteviz (pre-built version) to visualise what procpath has recorder. I drop the celery.sqlite there and use this query:
SELECT datetime(ts, 'unixepoch', 'localtime') ts, stat_pid, stat_rss / 256.0 rss
FROM record
And in sqliteviz I create a line chart trace with X=ts, Y=rss, and add split transform By=stat_pid. The result chart is:
This shape is likely pretty familiar to anyone who fought with memory leaks.
Finding leaking objects
Now it's time for dozer. I'll show non-instrumented case (and you can instrument your code in similar way if you can). To inject Dozer server into target process I'll use Pyrasite. There are two things to know about it:
*
*To run it, ptrace has to be configured as "classic ptrace permissions": echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope, which is may be a security risk
*There are non-zero chances that your target Python process will crash
With that caveat I:
*
*pip install https://github.com/mgedmin/dozer/archive/3ca74bd8.zip (that's to-be 0.8 I mentioned above)
*pip install pillow (which dozer uses for charting)
*pip install pyrasite
After that I can get Python shell in the target process:
pyrasite-shell 26572
And inject the following, which will run Dozer's WSGI application using stdlib's wsgiref's server.
import threading
import wsgiref.simple_server
import dozer
def run_dozer():
app = dozer.Dozer(app=None, path='/')
with wsgiref.simple_server.make_server('', 8000, app) as httpd:
print('Serving Dozer on port 8000...')
httpd.serve_forever()
threading.Thread(target=run_dozer, daemon=True).start()
Opening http://localhost:8000 in a browser there should see something like:
After that I run python demo.py from (4) again and wait for it to finish. Then in Dozer I set "Floor" to 5000, and here's what I see:
Two types related to Celery grow as the subtask are scheduled:
*
*celery.result.AsyncResult
*vine.promises.promise
weakref.WeakMethod has the same shape and numbers and must be caused by the same thing.
Finding root cause
At this point from the leaking types and the trends it may be already clear what's going on in your case. If it's not, Dozer has "TRACE" link per type, which allows tracing (e.g. seeing object's attributes) chosen object's referrers (gc.get_referrers) and referents (gc.get_referents), and continue the process again traversing the graph.
But a picture says a thousand words, right? So I'll show how to use objgraph to render chosen object's dependency graph.
*
*pip install objgraph
*apt-get install graphviz
Then:
*
*I run python demo.py from (4) again
*in Dozer I set floor=0, filter=AsyncResult
*and click "TRACE" which should yield
Then in Pyrasite shell run:
objgraph.show_backrefs([objgraph.at(140254427663376)], filename='backref.png')
The PNG file should contain:
Basically there's some Context object containing a list called _children that in turn is containing many instances of celery.result.AsyncResult, which leak. Changing Filter=celery.*context in Dozer here's what I see:
So the culprit is celery.app.task.Context. Searching that type would certainly lead you to Celery task page. Quickly searching for "children" there, here's what it says:
trail = True
If enabled the request will keep track of subtasks started by this task, and this information will be sent with the result (result.children).
Disabling the trail by setting trail=False like:
@app.task(trail=False)
def task():
for i in range(10_000):
subtask.delay()
time.sleep(0.01)
Then restarting the Celery node from (3) and python demo.py from (4) yet again, shows this memory consumption.
Problem solved!
A: I don't know how to dump an entire python interpreter state and restore it. It would be useful, I'll keep my eye on this answer in case anyone else has ideas.
If you have an idea where the memory is leaking, you can add checks the refcounts of your objects. For example:
x = SomeObject()
... later ...
oldRefCount = sys.getrefcount( x )
suspiciousFunction( x )
if (oldRefCount != sys.getrefcount(x)):
print "Possible memory leak..."
You could also check for reference counts higher than some number that is reasonable for your app. To take it further, you could modify the python interpreter to do these kinds of check by replacing the Py_INCREF and Py_DECREF macros with your own. This might be a bit dangerous in a production app, though.
Here is an essay with more info on debugging these sorts of things. It's more geared for plugin authors but most of it applies.
Debugging Reference Counts
A: The gc module has some functions that might be useful, like listing all objects the garbage collector found to be unreachable but cannot free, or a list of all objects being tracked.
If you have a suspicion which objects might leak, the weakref module could be handy to find out if/when objects are collected.
A: Meliae looks promising:
This project is similar to heapy (in the 'guppy' project), in its attempt to understand how memory has been allocated.
Currently, its main difference is that it splits the task of computing summary statistics, etc of memory consumption from the actual scanning of memory consumption. It does this, because I often want to figure out what is going on in my process, while my process is consuming huge amounts of memory (1GB, etc). It also allows dramatically simplifying the scanner, as I don't allocate python objects while trying to analyze python object memory consumption.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
}
|
Q: Team Foundation Server - Use API to Sync to SVN Has anyone out there used TFS's API to synchronize different types of repositories? I have a SVN repo that I want to sync with a TFS repo. More accurately, I just want to take everything latest from SVN occasionally (nightly) and dump it out to TFS as the latest version.
Any advice?
A: The people who run CodePlex created a bridge between TFS and SVN. It's called SvnBridge. They have 2 versions of the app. One version runs in IIS, and the other version is a client.
You might be able to talk to the project and see if you can do what you want. I believe that the actual flow right now is SVN to TFS, but I don't see it couldn't go the other way.
http://www.codeplex.com/SvnBridge
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Flex Post Event Screen Updates I came across this topic today while investigating something very strange. Doing certain things in our Flex app can cause the number of frames rendered to rocket, from 12fps to ~30fps: loaded animations start playing at high speed and the GUI starts to lock up.
Since everything I've read on Flex/Flash hammers home the point "the frame rate is capped at the fps set in the top level app", it seems the only way these extra renders can be happening is due to some events causing them (no programmatic changes to the stage's framerate are done anywhere). Since it only happens when I put my update logic in the ENTER_FRAME handler, I'm trying to figure out what might be happening which to apparently causing Flex to go render-crazy.
Hypothesis: something in my update function is triggering an immediate screen update, this raises another ENTER_FRAME immediately, which means my update loop gets called, which triggers another immediate screen update, ...
We have Flex components used in our GUI, if this is a factor. I don't really know where to go next on this.
Clarifications:
*
*When I say things speed up, there
are two ways this manifests.
*Firstly, my ENTER_FRAME handler gets
called far more often.
*Secondly, a
loaded Flash SWF with a looping
animation built in suddenly speeds
up to te point it looks silly.
*I am not using updateAfterEvent, I only
found this existed when researching
this problem. Apparently, some
events on Sprite subclasses
automatically call this and I wonder
if that's the root cause.
*I am not doing any direct messsing about with rendering at all. Background animations play automatically as they have timelines built-in from CS3 authoring, all our update function does is change the position of DisPlayObjects or add/remove them etc
Update:
I added a label to my app to print out stage.frameRate, and discovered at certain times, it suddenly changes from 12 to 1000 (the maximum allowed value). While it was trivial to add a line to my ENTER_FRAME handler to reset it that's hardly a big help.
Also, even doing this, the rendering is all messed up. Certain actions (like raising an Alert popup) make it all spring back into life.
Unfortunately, I am not able to view the source of the Stage class to set a breakpoint on the setter property.
That's very interesting about the Flex loading 'set to 1000fps' thing. What we have are several Flex applications which all provide a common interface. A master app is in charge of loading these modules as required through the SWFLoader class. However, the loading process already takes into account the delayed loading... when the SWF loads we then wait for the APPLICATION_COMPLETE from the SystemManager. Once this is received, shouldn't the applications completion have occurred?
A: Flex sets the frame rate to 1000 during "phased instantiation" of Flex components, which occurs only during initial load of a flex swf. This allows it to build all components very quickly.
Are you waiting for the Flex app to be fully loaded and constructed? You should be waiting for FlexEvent.CREATION_COMPLETE before working with your Flex content.
If you would like a reference to where this occcurs, look in the Flex LayoutManager class, line 326 (using Flex SDK 3.0.194161), in the setter for the property usePhasedInstantiation.
Update:
APPLICATION_COMPLETE should have you covered for the initial load.
This actually happens any time components are created directly from MXML. So there are a few other cases to look for. Are you using any Repeaters? Do you use any navigation containers that are building their children on demand?
A: One thing I'm not clear on - are you seeing that the actual screen refreshes are occurring faster than the published framerate? Or is it that your animations are moving faster but the screen refreshes are unchanged? (i.e., it used to move 10 pixels per second, but now it moves faster than that, regardless of how often the screen is drawn.)
An easy way to check this would be to try publishing your content at 1 fps. It should be clear whether the screen is redrawing once per second, but animated elements are being moved more frequently than that, or whether the screen is actually updating more frequently.
If the latter, are you using any updateAfterEvent() methods in your code? This can cause actual screen refreshes to occur faster than the published framerate. It shouldn't affect ENTER_FRAME events though. You should still only get one of those per frame update.
Alternately, are the things you're animating just Sprites and so on, or are you implementing them as Flex components, and trying to redraw them with invalidate() methods and RENDER events and so on?
If you could clarify a few of these points in the question the answer might be clearer. Thanks...
A: Thanks for the clarifications. If a loaded clip with a animation (I assume you mean a frame animation) is speeding up, then that certainly sounds like something is changing your playback framerate, as opposed to other things that could be going on. With that said it's not a problem I've seen crop up before, but I do think there are some things you could try that ought to narrow down where the problem is:
*
*You might as well try tracing out stage.frameRate during the speed-up. Presumably nothing ought to be changing your framerate, but since that would explain your issues you might as well rule it out.
*Try removing as many GUI components as possible and seeing if the problem still occurs, if it's possible to trigger the problem without them.
*One sanity check you could try, if it's feasible, is to copy some of the contents of your game into a fresh project and try it there. Sometimes mysterious issues like this happen because some class or SWC is being imported somewhere that everyone forgot about.
*You could try driving your code from a different event. For example, as far as I know driving it from Event.EXIT_FRAME or Event.FRAME_CONSTRUCTED ought to look the same, but if it doesn't then that's a hint. Alternately, you could try driving it from something like a keyboard event or MouseEvent.MOUSE_MOVE. Then if updates occur even though you're not firing events, you'll know something else is driving things besides your event loop.
Those are the things I'd try, anyway. Hope you track it down...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calculating the elapsed working hours between 2 datetime Given two datetimes. What is the best way to calculate the number of working hours between them. Considering the working hours are Mon 8 - 5.30, and Tue-Fri 8.30 - 5.30, and that potentially any day could be a public holiday.
This is my effort, seem hideously inefficient but in terms of the number of iterations and that the IsWorkingDay method hits the DB to see if that datetime is a public holiday.
Can anyone suggest any optimizations or alternatives.
public decimal ElapsedWorkingHours(DateTime start, DateTime finish)
{
decimal counter = 0;
while (start.CompareTo(finish) <= 0)
{
if (IsWorkingDay(start) && IsOfficeHours(start))
{
start = start.AddMinutes(1);
counter++;
}
else
{
start = start.AddMinutes(1);
}
}
decimal hours;
if (counter != 0)
{
hours = counter/60;
}
return hours;
}
A: Before you start optimizing it, ask yourself two questions.
a) Does it work?
b) Is it too slow?
Only if the answer to both question is "yes" are you ready to start optimizing.
Apart from that
*
*you only need to worry about minutes and hours on the start day and end day. Intervening days will obviously be a full 9/9.5 hours, unless they are holidays or weekends
*No need to check a weekend day to see if it's a holiday
Here's how I'd do it
// Normalise start and end
while start.day is weekend or holiday, start.day++, start.time = 0.00am
if start.day is monday,
start.time = max(start.time, 8am)
else
start.time = max(start.time, 8.30am)
while end.day is weekend or holiday, end.day--, end.time = 11.59pm
end.time = min(end.time, 5.30pm)
// Now we've normalised, is there any time left?
if start > end
return 0
// Calculate time in first day
timediff = 5.30pm - start.time
day = start.day + 1
// Add time on all intervening days
while(day < end.day)
// returns 9 or 9.30hrs or 0 as appropriate, could be optimised to grab all records
// from the database in 1 or 2 hits, by counting all intervening mondays, and all
// intervening tue-fris (non-holidays)
timediff += duration(day)
// Add time on last day
timediff += end.time - 08.30am
if end.day is Monday then
timediff += end.time - 08.00am
else
timediff += end.time - 08.30am
return timediff
You could do something like
SELECT COUNT(DAY) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End GROUP BY DAY
to count the number of holidays falling on Monday, Tuesday, Wednesday, and so forth. Probably a way of getting SQL to count just Mondays and non-Mondays, though can't think of anything at the moment.
A:
especially considering the IsWorkingDay method hits the DB to see if that day is a public holiday
If the problem is the number of queries rather than the amount of data, query the working day data from the data base for the entire day range you need at the beginning instead of querying in each loop iteration.
A: Take a look at the TimeSpan Class. That will give you the hours between any 2 times.
A single DB call can also get the holidays between your two times; something along the lines of:
SELECT COUNT(*) FROM HOLIDAY WHERE HOLIDAY BETWEEN @Start AND @End
Multiply that count by 8 and subtract it from your total hours.
-Ian
EDIT: In response to below, If you're holiday's are not a constant number of hours. you can keep a HolidayStart and a HolidayEnd Time in your DB and and just return them from the call to the db as well. Do an hour count similar to whatever method you settle on for the main routine.
A: There's also the recursive solution. Not necessarily efficient, but a lot of fun:
public decimal ElapseddWorkingHours(DateTime start, DateTime finish)
{
if (start.Date == finish.Date)
return (finish - start).TotalHours;
if (IsWorkingDay(start.Date))
return ElapsedWorkingHours(start, new DateTime(start.Year, start.Month, start.Day, 17, 30, 0))
+ ElapsedWorkingHours(start.Date.AddDays(1).AddHours(DateStartTime(start.Date.AddDays(1)), finish);
else
return ElapsedWorkingHours(start.Date.AddDays(1), finish);
}
A: Building on what @OregonGhost said, rather than using an IsWorkingDay() function at accepts a day and returns a boolean, have a HolidayCount() function that accepts a range and returns an integer giving the number of Holidays in the range. The trick here is if you're dealing with a partial date for your boundry beginning and end days you may still need to determine if those dates are themselves holidays. But even then, you could use the new method to make sure you needed at most three calls the to DB.
A: Try something along these lines:
TimeSpan = TimeSpan Between Date1 And Date2
cntDays = TimeSpan.Days
cntNumberMondays = Iterate Between Date1 And Date2 Counting Mondays
cntdays = cntdays - cntnumbermondays
NumHolidays = DBCall To Get # Holidays BETWEEN Date1 AND Date2
Cntdays = cntdays - numholidays
numberhours = ((decimal)cntdays * NumberHoursInWorkingDay )+((decimal)cntNumberMondays * NumberHoursInMondayWorkDay )
A: The most efficient way to do this is to calculate the total time difference, then subtract the time that is a weekend or holiday. There are quite a few edge cases to consider, but you can simplify that by taking the first and last days of the range and calculating them seperately.
The COUNT(*) method suggested by Ian Jacobs seems like a good way to count the holidays. Whatever you use, it will just handle the whole days, you need to cover the start and end dates separately.
Counting the weekend days is easy; if you have a function Weekday(date) that returns 0 for Monday through 6 for Sunday, it looks like this:
saturdays = ((finish - start) + Weekday(start) + 2) / 7;
sundays = ((finish - start) + Weekday(start) + 1) / 7;
Note: (finish - start) isn't to be taken literally, replace it with something that calculates the time span in days.
A: Use @Ian's query to check between dates to find out which days are not working days. Then do some math to find out if your start time or end time falls on a non-working day and subtract the difference.
So if start is Saturday noon, and end is Monday noon, the query should give you back 2 days, from which you calculate 48 hours (2 x 24). If your query on IsWorkingDay(start) returns false, subtract from 24 the time from start to midnight, which would give you 12 hours, or 36 hours total non-working hours.
Now, if your office hours are the same for every day, you do a similar thing. If your office hours are a bit scattered, you'll have more trouble.
Ideally, make a single query on the database that gives you all of the office hours between the two times (or even dates). Then do the math locally from that set.
A: Dim totalMinutes As Integer = 0
For minute As Integer = 0 To DateDiff(DateInterval.Minute, contextInParameter1, contextInParameter2)
Dim d As Date = contextInParameter1.AddMinutes(minute)
If d.DayOfWeek <= DayOfWeek.Friday AndAlso _
d.DayOfWeek >= DayOfWeek.Monday AndAlso _
d.Hour >= 8 AndAlso _
d.Hour <= 17 Then
totalMinutes += 1
Else
Dim test = ""
End If
Next minute
Dim totalHours = totalMinutes / 60
Piece of Cake!
Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: INotifyPropertyChanged property name - hardcode vs reflection? What is the best way to specify a property name when using INotifyPropertyChanged?
Most examples hardcode the property name as an argument on the PropertyChanged Event. I was thinking about using MethodBase.GetCurrentMethod.Name.Substring(4) but am a little uneasy about the reflection overhead.
A: Yeah I see the use and simplicity of the function you are suggesting, but when considering the running cost due to reflection, yeah that is a bad idea, What I use for this scenario is having a Code snippet added properly to take advantage of the time and error in writing a property with all the Notifyproperty event firing.
A: Don't forget one thing : PropertyChanged event is mainly consumed by components that will use reflection to get the value of the named property.
The most obvious example is databinding.
When you fire PropertyChanged event, passing the name of the property as a parameter, you should know that the subscriber of this event is likely to use reflection by calling, for instance, GetProperty (at least the first time if it uses a cache of PropertyInfo), then GetValue. This last call is a dynamic invocation (MethodInfo.Invoke) of the property getter method, which costs more than the GetProperty which only queries meta data. (Note that data binding relies on the whole TypeDescriptor thing -- but the default implementation uses reflection.)
So, of course using hard code property names when firing PropertyChanged is more efficient than using reflection for dynamically getting the name of the property, but IMHO, it is important to balance your thoughts. In some cases, the performance overhead is not that critical, and you could benefit from some kind on strongly typed event firing mechanism.
Here is what I use sometimes in C# 3.0, when performances would not be a concern :
public class Person : INotifyPropertyChanged
{
private string name;
public string Name
{
get { return this.name; }
set
{
this.name = value;
FirePropertyChanged(p => p.Name);
}
}
private void FirePropertyChanged<TValue>(Expression<Func<Person, TValue>> propertySelector)
{
if (PropertyChanged == null)
return;
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Notice the use of the expression tree to get the name of the property, and the use of the lambda expression as an Expression :
FirePropertyChanged(p => p.Name);
A: Another VERY NICE method I can think of is
Auto-implement INotifyPropertyChanged with Aspects
AOP: Aspect oriented programming
Nice article on codeproject: AOP Implementation of INotifyPropertyChanged
A: You might be interessted in this discussion about
"Best Practices: How to implement INotifyPropertyChanged right?"
too.
A: Since C# 6.0 there is a nameof() keyword it will be evaluated at compile time, so it will has the performance as hardcoded value and is protected against mismatch with notified property.
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string info)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info));
}
public string SelectedItem
{
get
{
return _selectedItem;
}
set
{
if (_selectedItem != value)
{
_selectedItem = value;
NotifyPropertyChanged(nameof(SelectedItem));
}
}
}
private string _selectedItem;
A: In .NET 4.5 (C# 5.0) there is a new attribute called - CallerMemberName it helps avoid hardcoded property names preventing the onset of bugs if developers decide to change a property name, here's an example:
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void OnPropertyChanged([CallerMemberName]string propertyName="")
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
OnPropertyChanged();
}
}
A: Without be irrevelant, between Hardcode and reflection, my choice is : notifypropertyweaver.
This Visual Studio package allow you to have the benefits of reflection (maintainability, readability,..) without have to lose perfs.
Actually, you just have to implement the INotifyPropertyChanged and it add all the "notification stuff" at the compilation.
This is also fully parametrable if you want to fully optimize your code.
For example, with notifypropertyweaver, you will have this code in you editor :
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string GivenNames { get; set; }
public string FamilyName { get; set; }
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
}
Instead of :
public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string givenNames;
public string GivenNames
{
get { return givenNames; }
set
{
if (value != givenNames)
{
givenNames = value;
OnPropertyChanged("GivenNames");
OnPropertyChanged("FullName");
}
}
}
private string familyName;
public string FamilyName
{
get { return familyName; }
set
{
if (value != familyName)
{
familyName = value;
OnPropertyChanged("FamilyName");
OnPropertyChanged("FullName");
}
}
}
public string FullName
{
get
{
return string.Format("{0} {1}", GivenNames, FamilyName);
}
}
public virtual void OnPropertyChanged(string propertyName)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
For french speakers : Améliorez la lisibilité de votre code et simplifiez vous la vie avec notifypropertyweaver
A: The reflection overhead here is pretty much overkill especially since INotifyPropertyChanged gets called a lot. It's best just to hard code the value if you can.
If you aren't concerned about performance then I'd look at the various approached mentioned below and pick that that requires the least amount of coding. If you could do something to completely removes the need for the explicit call then that would be best (e.g. AOP).
A: The performance hit involved in the use of expression trees is due to the repeated resolution of the expression tree.
The following code still uses expression trees and thus has the consequent advantages of being refactoring friendly and obfuscation friendly, but is actually approx 40% faster (very rough tests) than the usual technique - which consists of newing up a PropertyChangedEventArgs object for every change notification.
It's quicker and avoids the performance hit of the expression tree because we cache a static PropertyChangedEventArgs object for each property.
There's one thing which I'm not yet doing - I intend to add some code which checks for debug builds that the property name for the supplied PropertChangedEventArgs object matches the property within which it is being used - at the moment with this code it is still possible for the developer to supply the wrong object.
Check it out:
public class Observable<T> : INotifyPropertyChanged
where T : Observable<T>
{
public event PropertyChangedEventHandler PropertyChanged;
protected static PropertyChangedEventArgs CreateArgs(
Expression<Func<T, object>> propertyExpression)
{
var lambda = propertyExpression as LambdaExpression;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = lambda.Body as UnaryExpression;
memberExpression = unaryExpression.Operand as MemberExpression;
}
else
{
memberExpression = lambda.Body as MemberExpression;
}
var propertyInfo = memberExpression.Member as PropertyInfo;
return new PropertyChangedEventArgs(propertyInfo.Name);
}
protected void NotifyChange(PropertyChangedEventArgs args)
{
if (PropertyChanged != null)
{
PropertyChanged(this, args);
}
}
}
public class Person : Observable<Person>
{
// property change event arg objects
static PropertyChangedEventArgs _firstNameChangeArgs = CreateArgs(x => x.FirstName);
static PropertyChangedEventArgs _lastNameChangeArgs = CreateArgs(x => x.LastName);
string _firstName;
string _lastName;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyChange(_firstNameChangeArgs);
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyChange(_lastNameChangeArgs);
}
}
}
A: Roman:
I'd say you wouldn't even need the "Person" parameter - accordingly, a completely generic snippet like the one below should do:
private int age;
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChanged(() => Age);
}
}
private void OnPropertyChanged<T>(Expression<Func<T>> exp)
{
//the cast will always succeed
MemberExpression memberExpression = (MemberExpression) exp.Body;
string propertyName = memberExpression.Member.Name;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
...however, I prefer sticking to string parameters with conditional validation in Debug builds. Josh Smith posted a nice sample on this:
A base class which implements INotifyPropertyChanged
Cheers :)
Philipp
A: Additionally, we found an issue where getting a method name worked differently in Debug vs. Release builds:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/244d3f24-4cc4-4925-aebe-85f55b39ec92
(The code we were using wasn't exactly reflection in the way you suggested, but it convinced us that hardcoding the property name was the fastest and most reliable solution.)
A: I did something like this once as an experiment, from memory it worked OK, and removed the need to hardcode all the property names in strings. Performance could be in issue if your building a high volume server application, on the desktop you'll probably never notice the difference.
protected void OnPropertyChanged()
{
OnPropertyChanged(PropertyName);
}
protected string PropertyName
{
get
{
MethodBase mb = new StackFrame(1).GetMethod();
string name = mb.Name;
if(mb.Name.IndexOf("get_") > -1)
name = mb.Name.Replace("get_", "");
if(mb.Name.IndexOf("set_") > -1)
name = mb.Name.Replace("set_", "");
return name;
}
}
A: The problem with the reflection based method is that it's rather expensive, and isn't terribly quick. Sure, it is much more flexible, and less brittle towards refactoring.
However, it really can hurt performance, especially when things are called frequently. The stackframe method, also (I believe) has issues in CAS (e.g. restricted trust levels, such as XBAP). It's best to hard code it.
If your looking for fast, flexible property notification in WPF there is a solution -- use DependencyObject :) Thats what it was designed for. If you don't want to take the dependency, or worry about the thread affinity issues, move the property name into a constant, and boom! your good.
A: You might want to avoid INotifyPropertyChanged altogether. It adds unnecessary bookkeeping code to your project. Consider using Update Controls .NET instead.
A: Yet another approach: http://www.codeproject.com/Articles/450688/Enhanced-MVVM-Design-w-Type-Safe-View-Models-TVM
A: Take a look at this blog post:
http://khason.net/dev/inotifypropertychanged-auto-wiring-or-how-to-get-rid-of-redundant-code
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
}
|
Q: How to emulate Emacs’ transpose-words in Vim? Emacs has a useful transpose-words command which lets one exchange the word before the cursor with the word after the cursor, preserving punctuation.
For example, ‘stack |overflow’ + M-t = ‘overflow stack|’ (‘|’ is the cursor position).
<a>|<p> becomes <p><a|>.
Is it possible to emulate it in Vim? I know I can use dwwP, but it doesn’t work well with punctuation.
Update: No, dwwP is really not a solution. Imagine:
SOME_BOOST_PP_BLACK_MAGIC( (a)(b)(c) )
// with cursor here ^
Emacs’ M-t would have exchanged b and c, resulting in (a)(c)(b).
What works is /\w
yiwNviwpnviwgp. But it spoils "" and "/. Is there a cleaner solution?
Update²:
Solved
:nmap gn :s,\v(\w+)(\W*%#\W*)(\w+),\3\2\1\r,<CR>kgJ:nohl<CR>
Imperfect, but works.
Thanks Camflan for bringing the %# item to my attention. Of course, it’s all on the wiki, but I didn’t realize it could solve the problem of exact (Emacs got it completely right) duplication of the transpose-words feature.
A: These are from my .vimrc and work well for me.
" swap two words
:vnoremap <C-X> <Esc>`.``gvP``P
" Swap word with next word
nmap <silent> gw "_yiw:s/\(\%#\w\+\)\(\_W\+\)\(\w\+\)/\3\2\1/<cr><c-o><c-l> *N*
A: Depending on the situation, you can use the W or B commands, as in dWwP. The "capital" versions skip to the next/previous space, including punctuation. The f and t commands can help, as well, for specifying the end of the deleted range.
There's also a discussion on the Vim Tips Wiki about various swapping techniques.
A: In the middle of a line, go to the first letter of the first word, then do
dw wP
At the end of a line (ie the last two words of the line), go to the space between the words and do
2dw bhP
From the handy Equivalence of VIM & Emacs commands
You could add shortcut keys for those by adding something like the following to your vimrc file:
map L dwwP
map M 2dwbhP
In that case, SHIFT-L (in command-mode) would switch words in the middle of the line and SHIFT-M would do it at the end.
NB: This works best with space-separated words and doesn't handle the OP's specific case very well.
A: There's a tip on http://vim.wikia.com/wiki/VimTip10. But I choose to roll my own.
My snippet has two obvious advantages over the method mentioned in the tip: 1) it works when the cursor isn't in a word. 2) it won't high-light the entire screen.
It works almost like emacs 'transpose-words', except that when transposition is impossible, it does nothing. (emacs 'transpose-words' would blink and change cursor position to the beginning of current word.)
"transpose words (like emacs `transpose-words')
function! TransposeWords()
if search('\w\+\%#\w*\W\+\w\+')
elseif search('\w\+\W\+\%#\W*\w\+')
endif
let l:pos = getpos('.')
exec 'silent! :s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/'
call setpos('.', l:pos)
let l:_ = search('\(\%#\w\+\W\+\)\@<=\w\+')
normal el
endfunction
nmap <silent> <M-right> :call TransposeWords()<CR>
imap <silent> <M-right> <C-O>:call TransposeWords()<CR>
A: You can use dwwP or dWwP as Mark and CapnNefarious have said, but I have a few notes of my own:
*
*If the cursor is on the first letter of the second word, as in the example you gave, you can use dwbP (or dWbP to handle punctuation);
*If the cursor is in the middle of the word, you can use dawbP/daWbP.
A: There's a transpose-words script on vim.org that works beautifully.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Dynamic RadioButtons Our resident Flex expert is out for the day and I thought this would be a good chance to test this site out. I have a dropdown with a dataProvider that is working fine:
<ep:ComboBox id="dead_reason" selectedValue="{_data.dead_reason}"
dataProvider="{_data.staticData.dead_reason}"
labelField="@label" width="300"/>
The ComboBox is custom but I'm not sure if that matters for the question. I need to change the combo box to radios (all in one group) but maintain the dynamic options. In other words, what is the best way to generate dynamic RadioButtons?
A: Try using an <mx:Repeater> Something like:
<mx:Repeater dataProvider="{_data.staticData.dead_reason}">
<mx:RadioButton groupName="reasons" ...>
</mx:Repeater>
A: <mx:RadioButtonGroup id="RDO_Group"/>
<mx:Repeater id="myRepeater" dataProvider="{_data.staticData.dead_reason}">
<mx:RadioButton id="rdo" label="{myRepeater.currentItem}" value="{myRepeater.currentItem}" groupName="RDO_Group"/>
</mx:Repeater>
is the best way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Best way to handle block ciphers in C++? (Crypto++) I'm pretty new to both C++ and Block Cipher encryption, and I am currently in the process of writing a decryption function for AES (16 byte seed / 16 byte blocks). All is going well, but my total data size is not always a multiple of my block size. I'm wondering what the best way to handle leftover data at the end of my data.
I'm using Crypto++ for the AES library.
The ProcessBlock() function takes an Input and Output char array. I'm assuming it is expecting them to be at least big enough as the block size.
What would be the best way to process all 16 byte blocks in a block cipher, and then also process the leftover data?
A: It's more than just padding - you need a Mode of Operation. The Good Math, Bad Math blog is writing up an excellent series on what they are and how to use them here. Also see the wikipedia entry. One thing that's really, really important: Never, ever use ECB (Electronic Code Book) mode - where you encrypt each block independently. It's the obvious way to do it, but it provides appallingly poor security.
Ideally, though, you shouldn't even have to do this yourself. Your crypto library should provide it. If it doesn't, I'd suggest changing to something else. like OpenSSL.
A: What you want is a padding system.
Check out this CodeProject article on Crypto++:
When a message is not a multiple of
the cipher's block size, ECB or CBC
mode messages must be padded. The
method and values of padding are a
source of problem with respect to
interoperability between Cryptographic
libraries and APIs. As Garth Lancaster
points out, if you're not aware of the
particulars of padding, use the
StreamTransformationFilter. In this
case, the Crypto++ filter will pad for
you.
A: There's a PKCS standard for what's called "padding"
See the wikipedia page, but it amounts to padding with one of:
01
02 02
03 03 03
04 04 04 04
05 05 05 05 05
This way you know during decryption where the original message ends...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Yahoo GeoPlanet & XPathNavigator C# I am returning XML data from the Yahoo GeoPlanet web service using HttpWebRequest.
I am loading the XML using
XPathDocument doc = new XPathDocument(HttpWebResponse.GetResponseStream())
Next comes:
XPathNavigator nav = doc.CreateNavigator();
If I do nav.Select("places"); or nav.Select("/places"); or nav.Select("//places");, nothing gets returned!
But if I do nav.select("/*");, I get the node and doing node.Name returns places?
A: I know nothing about the format of the Yahoo data but I do know that the most common misstake with C# and XPath is forgetting to add the relevant namespaces to your "NamespaceManager" have a look here http://mydotnet.wordpress.com/2008/05/29/worlds-smallest-xml-xpath-tutorial/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I re-import a subreport into Crystal reports 9.0 without getting an Access Denied error? I'm using Crystal Reports 9.0. It has a subreport which is shared by 2 master reports. I modified the subreport as a result of fixing one of the master reports. When I try to re-import that subreport into my 2nd Master report I'm getting the error: Access denied then Re-importing the subreport failed.
Does anyone know what the problem might be? The 2 master reports and subreport are all "checked" out so it's not a ready only issue. Also when I first say re-import it tells me the file could not be found (pointing to a long dead file path) and I'm required to select it.
A: Do you have both the master reports open at the same time?
If so maybe closing the one you already refreshed, and trying it again. It seems like it has a lock on it for some reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tomcat 6.0.18 service will not start on a windows server I installed Tomcat 6.0.18 on a windows server 2003 box and it will not start as a service.
I'm running it with jdk 1.6.0_07.
It runs when I start it with tomcat6.exe.
I got a vague error in the System Event Log on Windows.
The Apache Tomcat 6 service terminated with service-specific error 0 (0x0).
A: I'll bite it :-)
Tomcat Service on windows is dependent on the MS C Runtime library msvcr71.dll. As long as it is in the path, the service will start just fine.
Just to prevent your other windows to be forced to use this version of the runtime library, you might want to copy the DLL to just the tomcat bin path instead of windows\system32.
A: From gobaco.wordpress.com
Tomcat 6 couldn’t find a file called msvcr71.dll.
I just copied it over from
c:\windows\microsoft.net\framework\v1.1.4322
to
c:\windows\system32
and was able to start tomcat.
I thought this was very strange, so I wanted to post it on SO in case anyone else runs into this problem. If someone wants to post the same answer I'll accept it.
A: i follow the above guide but still the same, error 0,
my process monitor log at http://www.sendspace.com/file/t0tahr
A: I solved the same problem enabling the default java virtual machine in the configuration app.
Assuming you have installed tomcat using:
service install tomcat-6.0.35
execute:
tomcat6w //ES/tomcat-6.0.35
a window pops up, select the java tab and click on "Use default" checkbox.
The service install script (I immagine) selected C:\Program Files(x86)\Java\jre\bin\client\jvm.dll instead.
Environment:
*
*Windows Server standard SP2 64-bin
*Java 1.6.0_23-b05 (Java hotspot 64-bit server vm 19.0-b09 mixed mode)
*Apache tomcat 6.35 (you guessed this didn't you?)
A: I copied the msvcr71.dll from the java home directory to the bin directory of the apache-tomcat install, and the service started after that.
A: Even though it's an older post, I thought I'd share the knowledge about the very same issue I had, but the workaround was different.
The Apache Tomcat 7 service terminated with service-specific error 0 (0x0).
As there was no more information regarding the problem I went back to the Tomcat Control Panel and had a look at the Java path, which was pointed to an earlier installation of Java Virtual Machine:
C:\Program Files\Java\jre6\bin\client\jvm.dll, which no longer existed, so I had to change the JRE version to jre7.
Having done that, the service started up and all running now.
Hope it'll help some of you out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can a transform a polynomial to another coordinate system? Using assorted matrix math, I've solved a system of equations resulting in coefficients for a polynomial of degree 'n'
Ax^(n-1) + Bx^(n-2) + ... + Z
I then evaulate the polynomial over a given x range, essentially I'm rendering the polynomial curve. Now here's the catch. I've done this work in one coordinate system we'll call "data space". Now I need to present the same curve in another coordinate space. It is easy to transform input/output to and from the coordinate spaces, but the end user is only interested in the coefficients [A,B,....,Z] since they can reconstruct the polynomial on their own. How can I present a second set of coefficients [A',B',....,Z'] which represent the same shaped curve in a different coordinate system.
If it helps, I'm working in 2D space. Plain old x's and y's. I also feel like this may involve multiplying the coefficients by a transformation matrix? Would it some incorporate the scale/translation factor between the coordinate systems? Would it be the inverse of this matrix? I feel like I'm headed in the right direction...
Update: Coordinate systems are linearly related. Would have been useful info eh?
A: The problem statement is slightly unclear, so first I will clarify my own interpretation of it:
You have a polynomial function
f(x) = Cnxn + Cn-1xn-1 + ... + C0
[I changed A, B, ... Z into Cn, Cn-1, ..., C0 to more easily work with linear algebra below.]
Then you also have a transformation such as: z = ax + b that you want to use to find coefficients for the same polynomial, but in terms of z:
f(z) = Dnzn + Dn-1zn-1 + ... + D0
This can be done pretty easily with some linear algebra. In particular, you can define an (n+1)×(n+1) matrix T which allows us to do the matrix multiplication
d = T * c ,
where d is a column vector with top entry D0, to last entry Dn, column vector c is similar for the Ci coefficients, and matrix T has (i,j)-th [ith row, jth column] entry tij given by
tij = (j choose i) ai bj-i.
Where (j choose i) is the binomial coefficient, and = 0 when i > j. Also, unlike standard matrices, I'm thinking that i,j each range from 0 to n (usually you start at 1).
This is basically a nice way to write out the expansion and re-compression of the polynomial when you plug in z=ax+b by hand and use the binomial theorem.
A: If I understand your question correctly, there is no guarantee that the function will remain polynomial after you change coordinates. For example, let y=x^2, and the new coordinate system x'=y, y'=x. Now the equation becomes y' = sqrt(x'), which isn't polynomial.
A: Tyler's answer is the right answer if you have to compute this change of variable z = ax+b many times (I mean for many different polynomials). On the other hand, if you have to do it just once, it is much faster to combine the computation of the coefficients of the matrix with the final evaluation. The best way to do it is to symbolically evaluate your polynomial at point (ax+b) by Hörner's method:
*
*you store the polynomial coefficients in a vector V (at the beginning, all coefficients are zero), and for i = n to 0, you multiply it by (ax+b) and add Ci.
*adding Ci means adding it to the constant term
*multiplying by (ax+b) means multiplying all coefficients by b into a vector K1, multiplying all coefficients by a and shifting them away from the constant term into a vector K2, and putting K1+K2 back into V.
This will be easier to program, and faster to compute.
Note that changing y into w = cy+d is really easy. Finally, as mattiast points out, a general change of coordinates will not give you a polynomial.
Technical note: if you still want to compute matrix T (as defined by Tyler), you should compute it by using a weighted version of Pascal's rule (this is what the Hörner computation does implicitely):
ti,j = b ti,j-1 + a ti-1,j-1
This way, you compute it simply, column after column, from left to right.
A: You have the equation:
y = Ax^(n-1) + Bx^(n-2) + ... + Z
In xy space, and you want it in some x'y' space. What you need is transformation functions f(x) = x' and g(y) = y' (or h(x') = x and j(y') = y). In the first case you need to solve for x and solve for y. Once you have x and y, you can substituted those results into your original equation and solve for y'.
Whether or not this is trivial depends on the complexity of the functions used to transform from one space to another. For example, equations such as:
5x = x' and 10y = y'
are extremely easy to solve for the result
y' = 2Ax'^(n-1) + 2Bx'^(n-2) + ... + 10Z
A: If the input spaces are linearly related, then yes, a matrix should be able to transform one set of coefficients to another. For example, if you had your polynomial in your "original" x-space:
ax^3 + bx^2 + cx + d
and you wanted to transform into a different w-space where w = px+q
then you want to find a', b', c', and d' such that
ax^3 + bx^2 + cx + d = a'w^3 + b'w^2 + c'w + d'
and with some algebra,
a'w^3 + b'w^2 + c'w + d' = a'p^3x^3 + 3a'p^2qx^2 + 3a'pq^2x + a'q^3 + b'p^2x^2 + 2b'pqx + b'q^2 + c'px + c'q + d'
therefore
a = a'p^3
b = 3a'p^2q + b'p^2
c = 3a'pq^2 + 2b'pq + c'p
d = a'q^3 + b'q^2 + c'q + d'
which can be rewritten as a matrix problem and solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: If I register for an event in c# while it's dispatching, am I guaranteed to not get called again during that dispatch? In C#, I find myself occasionally wanting to register a method for an event in the middle of a dispatch of that same event. For example, if I have a class that transitions states based on successive dispatches of the same event, I might want the first state's handler to unregister itself and register the second handler. However, I don't want the second handler to be dispatched until the next time the event is fired.
The good news is that it looks like the Microsoft implementation of C# behaves exactly this way. The event registration syntax sugar gets replaced with a call to System.Delegate.Combine, which just concatenates the current invocation list and the new method into a separate list and assigns it to the event property. This gives me exactly the behavior I want.
So, my question is: is this guaranteed behavior by the language standard? I like to be able to run my C# code on other platforms under mono and generally want to make sure I'm not making assumptions about the language standard based on its implementation.
I couldn't find any definitive information on MSDN.
If you'd like a specific example of what I'm talking about, here's an example:
delegate void TestDelegate();
static event TestDelegate TestEvent;
static void Main (string[] args) {
TestEvent += TestDelegateInstanceFirst;
TestEvent();
TestEvent();
}
static void TestDelegateInstanceFirst () {
Console.WriteLine("First");
TestEvent += TestDelegateInstanceSecond;
}
static void TestDelegateInstanceSecond () {
Console.WriteLine("Second");
}
At least on Windows, the output is:
First
First
Second
A: Yes, it's guaranteed.
From the unified C# 3.0 spec, section 15.1:
However, when two non-null delegate
instances are combined, their
invocation lists are concatenated—in
the order left operand then right
operand—to form a new invocation list,
which contains two or more entries.
Note the "new invocation list". And again in section 15.3:
Once instantiated, delegate instances
always refer to the same target object
and method. Remember, when two
delegates are combined, or one is
removed from another, a new delegate
results with its own invocation list;
the invocation lists of the delegates
combined or removed remain unchanged.
Finally, MSDN for System.Delegate states:
Delegates are immutable; once created,
the invocation list of a delegate does
not change.
I suspect there's something in the CLI spec - I'll check if you'd like, but hopefully these three have given you enough confidence :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Gracefully closing a frame (toolbar) around an iframe I've created a tool that is used with a fairly popular music retailer.
The tool provides an enhanced search feature (transparent last.fm results, no ads, no lameness, nothing creepy) and I've found the most useful and unobtrusive way to display the search is as a toolbar using the much maligned iframe. This allows users to load search without stealing the users focus.
Not being a particularly big fan of iframes I thought it would be trivial to add a “close this frame” (ala Google image search) link allowing users to quickly and easily regain control of their browser.
However unlike google, I doen't know what the location of the content in the iframe is (only where it started, via src).
So now I find myself in world of XSS and all the security related concerns.
Using Javascript I've added 'back' and 'forward' buttons with the history object called from links in the parent (when a user does a search the results load into the iframe, so the back button allows them to go back to the primary site after their done using/perusing the search results).
Is there any way to call the current location within the iframe and reload the page (now sans frames) to that location?
I've checked PHP $GLOBAL/$_SERVER variables to see I might get lucky. I understand that there are security concerns, but I don't see how this particular function would be any different then history.back() where the browser makes the call itself without 'notifying' my parent frame.
I know I can retrieve the src location from the iframe itself, but of course that presumes the user doesn't navigate beyond this page, and if they do they don't mind losing their current location and being redirected back to page called initially by the frame (...ah...).
It almost seems like frames are designed to steal windows with no means for gracefully 'breaking out' and preserving integrity of the users session.
No wonder people hate them. :)
A: On Google image search when you remove the frame it functions as you currently propose, by returning to the original frame source. For XSS reasons, finding the current location shouldn't be possible, and if it was it would be considered a bug and fixed in subsequent browser patches, so it might not be best to rely on such a quirk if one existed. A way to elegantly break out without revealing location would be nice, though. This might be something you can propose to the HTML5 group.
A: Not that it would really be all too helpful, but the closest you can come is detecting if someone actually left the original frame source page. When you navigate a frame the history object maintains entries, and if your original history length when the page loads is greater than the history length when someone clicks "Break out of this frame...", then you know they were browsing in the frame.
A: I appreciate both you (hal10001) and Zach taking the time to answer. It appears I'm suck (as I suspected) because of the xss security concerns.
I suppose I could simply wrap all the content within a php based proxy, but that would clearly entering the creepy zone, not to mention the added latency and what-not.
I'll keep spinning the idea incase I do come across something sane and usable, but until then I guess I'll just use the slightly less freindly approach of promoting the original frame and wiping out their current location (and if they don't like I can revisit the iframe/toolbar situation.
Thanks again!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is there a standard implementation for Electronic Signatures on fill-in-form web applications? I have a client who is interested in adding in electronic signature support to a long (40 question) seller application form. I'm a little stumped on whether there is an existing standard or process that's out there that folks in the financial world would expect to see?
I could certainly add in a system where we generate a bunch of text based on their responses, have the applicant sign it with their private key and upload a public key- but that seems like a lot to ask of people. Do non-nerds even have PGP installed these days?
Is there a standard approach to this out there? Anyone work in the financial world that's done this and had it work well?
A: We use Alphatrust's e-Sign Software.
A: What purpose is the signature trying to fill? Are you trying to verify that the form actually came from a specific seller? (If so, you would have to know their public key ahead of time.) Are you trying to hold the seller accountable for their answers at a later date? (In that case, you might need some kind of third-party involved.)
Sometimes people ask for electronic signatures just because they sound neat.
A: If these forms are meant to be shared throught to a general public you'll need to know (and can validate, that's the hardest part) all the producers of these amount of certificates people could use to sign these forms, and it's almost impossible.
With closed environments (like functionaries, doctors...) where all the users are suposed to hold a certificate (with a pre-known CA you trust) and you should be sure the form is sended by someone trusted (non repudation, integrity...) it's a better scenario to sign a form, otherwise I do not recomend you to use signed forms to achieve your goal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I create a status bar item with Cocoa and Python (PyObjC)? I have created a brand new project in XCode and have the following in my AppDelegate.py file:
from Foundation import *
from AppKit import *
class MyApplicationAppDelegate(NSObject):
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setTitle_(u"12%")
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
However, when I launch the application no status bar item shows up. All the other code in main.py and main.m is default.
A: The above usage of .retain() is required because the statusItem is being destroyed upon return from the applicationDidFinishLaunching() method. Bind that variable as a field in instances of MyApplicationAppDelegate using self.statusItem instead.
Here is a modified example that does not require a .xib / etc...
from Foundation import *
from AppKit import *
from PyObjCTools import AppHelper
start_time = NSDate.date()
class MyApplicationAppDelegate(NSObject):
state = 'idle'
def applicationDidFinishLaunching_(self, sender):
NSLog("Application did finish launching.")
self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
self.statusItem.setTitle_(u"Hello World")
self.statusItem.setHighlightMode_(TRUE)
self.statusItem.setEnabled_(TRUE)
# Get the timer going
self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 5.0, self, 'tick:', None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
self.timer.fire()
def sync_(self, notification):
print "sync"
def tick_(self, notification):
print self.state
if __name__ == "__main__":
app = NSApplication.sharedApplication()
delegate = MyApplicationAppDelegate.alloc().init()
app.setDelegate_(delegate)
AppHelper.runEventLoop()
A: I had to do this to make it work:
*
*Open MainMenu.xib. Make sure the class of the app delegate is MyApplicationAppDelegate. I'm not sure if you will have to do this, but I did. It was wrong and so the app delegate never got called in the first place.
*Add statusItem.retain() because it gets autoreleased right away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Advantages of using MSBuild or NAnt versus running DevEnv.exe from command-line Can anyone explain what advantages there are to using a tool like MSBuild (or NAnt) to build a collection of projects versus running DevEnv.exe from the command-line?
A colleague I had worked with in the past had explained that (at least with older versions of Visual Studio) using DevEnv.exe was much slower than the other techniques, but I haven't read any evidence of that or if that is now a moot point now that starting with 2005, Visual Studio uses MSBuild under the hood.
I know one advantage of using MSBuild allows you to build your projects without requiring Visual Studio to be installed on the build machines, but I wasn't sure if there were others.
A: The obvious answer from my team is that not everbody has visual studio installed, in particular we do not install Visual Studio onto our build/CI servers.
A: The prime reason for using an external build tool like NAnt or MsBuild is the ability to automate your build process and thus provide continous feedback on the status of your system. Also they can be used for loads of things besides a "pure" build and that's where you really start to get value from them, it's an extremly valuable thing to be able to build and test your application with a single command.
You can also start adding stuff like collection of metrics, packinging of release binaries and all sorts of nifty stuff like that.
A: As far as C# goes, devenv.exe 2005 runs the compiler in-proc, which may cause out of memory exceptions for sizable solutions. Msbuild resorts to launching csc.exe process for each project. Projects that don't compile with devenv /build work fine with msbuild. Hope you like this reason.
A: One reason is because there's much more to building a product than just compiling it. Tasks such as creating installs, updating version numbers, creating escrows, distributing the final packages, etc. can be much easier because of what these tools (and their extensions) provide.
While you could do all this with regular scripts, using NAnt or MSBuild give you a solid framework for doing all this. There's a lot of community support for both, including additional tasks that can be downloaded (such as the MSBuild Community Tasks Project). Plus, there's support for them in numerous third party and open source products.
If you're just interested in compiling (and not the entire build process), you may find one time saving benefit of MSBuild is the support for building with multiple processors.
A: We are experimenting with switching from DevEnv to a tool (Visual Build Pro) that uses MsBuild under the hood and we got a "Reference required to assembly 'System.Drawing..." error for a project which doesn't need it and which builds fine in Visual Studio.
A: We have a large system consisting of C#, managed C++, and plain old unmanaged C++ assemblies/dlls. There is C++ code that depends on managed C++ code that depends of C# code that depends of managed C++ code that depends on plain old C++ code (whew!). When we were setting up our automated build environment a few years ago we discovered that MSBuild.exe didn't properly handle all of the dependencies that we have.
Working with Microsoft we were able to solve some of the issues but not all of them. If my memory serves me, we never could get the C# assemblies that depended on managed C++ dlls to build. So we ended up making a custom build script that called devenv.exe from the command line and it worked just fine.
Of course, that was with VS2005, it might be fixed now, but the script is still working so we haven't revisited the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Is a JavaScript try-catch ignoring an expected occasional error bad practice? In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?
try{
if(myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip) {
this.setAddress(newInfo);
}
} catch(e) {} // ignore missing args
A: If you expect a particular condition, your code will be easier to maintain if you explicitly test for it. I would write the above as something like
if( myInfo && newInfo
&& myInfo.person && newInfo.person
&& myInfo.person.address && newInfo.person.address
&& ( myInfo.person.name == newInfo.person.name
&& myInfo.person.address.street == newInfo.person.address.street
&& myInfo.person.address.zip == newInfo.person.address.zip
)
)
{
this.setAddress(newInfo);
}
This makes the effect much clearer - for instance, suppose newInfo is all filled out, but parts of myInfo are missing? Perhaps you actually want setAddress() to be called in that case? If so, you'll need to change that logic!
A: Yes. For one, an exception could be thrown for any number of reasons besides missing arguments. The catch-all would hide those cases which probably isn't desired.
A: I would think that if you're going to catch the exception then do something with it. Otherwise, let it bubble up so a higher level can handle it in some way (even if it's just the browser reporting the error to you).
A: On a related note, in IE, even though the specs say you can, you can not use a try/finally combination. In order for your "finally" to execute, you must have a catch block defined, even if it is empty.
//this will [NOT] do the reset in Internet Explorer
try{
doErrorProneAction();
} finally {
//clean up
this.reset();
}
//this [WILL] do the reset in Internet Explorer
try{
doErrorProneAction();
} catch(ex){
//do nothing
} finally {
//clean up
this.reset();
}
A: You could always write a helper function to do the checking for you:
function pathEquals(obj1, obj2, path)
{
var properties = path.split(".");
for (var i = 0, l = properties.length; i < l; i++)
{
var property = properties[i];
if (obj1 === null || typeof obj1[property] == "undefined" ||
obj2 === null || typeof obj2[property] == "undefined")
{
return false;
}
obj1 = obj1[property];
obj2 = obj2[property];
}
return (obj1 === obj2);
}
if (pathEquals(myInfo, newInfo, "person.name") &&
pathEquals(myInfo, newInfo, "person.address.street") &&
pathEquals(myInfo, newInfo, "person.address.zip"))
{
this.setAddress(newInfo);
}
A: For the example given I would say it was bad practice. There are instances however where it may be more efficient to simply trap for an expected error. Validating the format of a string before casting it as a GUID would be a good example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How do I wrap a string in a file in Python? How do I create a file-like object (same duck type as File) with the contents of a string?
A: If your file-like object is expected to contain bytes, the string should first be encoded as bytes, and then a BytesIO object can be used instead. In Python 3:
from io import BytesIO
string_repr_of_file = 'header\n byline\n body\n body\n end'
function_that_expects_bytes(BytesIO(bytes(string_repr_of_file,encoding='utf-8')))
A: In Python 3.0:
import io
with io.StringIO() as f:
f.write('abcdef')
print('gh', file=f)
f.seek(0)
print(f.read())
The output is:
'abcdefgh'
A: For Python 2.x, use the StringIO module. For example:
>>> from cStringIO import StringIO
>>> f = StringIO('foo')
>>> f.read()
'foo'
I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from StringIO".)
For Python 3.x, use the io module.
f = io.StringIO('foo')
A: This works for Python2.7 and Python3.x:
io.StringIO(u'foo')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "126"
}
|
Q: Javascript to detect whether the dropdown of a select element is visible I have a select element in a form, and I want to display something only if the dropdown is not visible. Things I have tried:
*
*Watching for click events, where odd clicks mean the dropdown is visible and even clicks mean the dropdown isn't. Misses other ways the dropdown could disappear (pressing escape, tabbing to another window), and I think this could be hard to get right cross-browser.
*Change events, but these only are triggered when the select box's value changes.
Ideas?
A: here is how I would preferred to do it.
focus and blur is where it is at.
<html>
<head>
<title>SandBox</title>
</head>
<body>
<select id="ddlBox">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<div id="divMsg">some text or whatever goes here.</div>
</body>
</html>
<script type="text/javascript">
window.onload = function() {
var ddlBox = document.getElementById("ddlBox");
var divMsg = document.getElementById("divMsg");
if (ddlBox && divMsg) {
ddlBox.onfocus = function() {
divMsg.style.display = "none";
}
ddlBox.onblur = function() {
divMsg.style.display = "";
}
divMsg.style.display = "";
}
}
</script>
A: Conditional-content, which is what you're asking about, isn't that difficult. The in the following example, I'll use jQuery to accomplish our goal:
<select id="theSelectId">
<option value="dogs">Dogs</option>
<option value="birds">Birds</option>
<option value="cats">Cats</option>
<option value="horses">Horses</option>
</select>
<div id="myDiv" style="width:300px;height:100px;background:#cc0000"></div>
We'll tie a couple events to show/hide #myDiv based upon the selected value of #theSelectId
$("#theSelectId").change(function(){
if ($(this).val() != "dogs")
$("#myDiv").fadeOut();
else
$("#myDiv").fadeIn();
});
A: I don't think there's direct support. You could also sit on the onblur of the select -- it gets called when the select loses focus.
Depending on how important it is, you could try implementing your own control or starting from one like a drop-down menu control which is similar. Usually, unless it's critical to your application, it's not worth doing this. If you decide to go this route, here's a discussion of someone trying to do it using dojo as a basis:
http://dojotoolkit.org/forum/dijit-dijit-0-9/dijit-support/emulating-html-select
A: This rudimentary example demonstrates how to do it with setInterval. It checks once every second for the display state of your select menu, and then hides or shows a piece of content. It works according to the description of your problem, and no matter what hides the select menu, it will display that piece of content accordingly. In other words, the toggleDisplay() was setup just to demonstrate that.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title></title>
<script language="javascript" type="text/javascript">
var STECHZ = {
init : function() {
STECHZ.setDisplayedInterval();
},
setDisplayedInterval : function() {
STECHZ.isDisplayedInterval = window.setInterval(function(){
if ( document.getElementById( "mySelectMenu" ).style.display == "none" ) {
document.getElementById( "myObjectToShow" ).style.display = "block";
} else {
document.getElementById( "myObjectToShow" ).style.display = "none";
}
}, 1000);
},
isDisplayedInterval : null,
toggleDisplay : function() {
var mySelectMenu = document.getElementById( "mySelectMenu" );
if ( mySelectMenu.style.display == "none" ) {
mySelectMenu.style.display = "block";
} else {
mySelectMenu.style.display = "none";
}
}
};
window.onload = function(){
STECHZ.init();
}
</script>
</head>
<body>
<p>
<a href="#" onclick="STECHZ.toggleDisplay();return false;">Click to toggle display.</a>
</p>
<select id="mySelectMenu">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<div id="myObjectToShow" style="display: none;">Only show when mySelectMenu is not showing.</div>
</body>
</html>
A: Keep track of the state using a JavaScript varialbe. We'll call it "openX".
onfocus="openX=true" onblur="openX=false" onchange="openX=false"
A: In jQuery, to test if something is visible:
$('something').css('display')
This will return something like 'block', 'inline', or 'none' (if element is not displayed). This is simply a representation of the CSS 'display' attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to purge expired items from cache? I've got a nice little class built that acts as a cache. Each item has an expiration TimeSpan or DateTime. Each time an attempt to access an item in the cache is made, the item's expiration is checked, and if it's expired, the item is removed from the cache and nothing is returned.
That's great for objects that are accessed frequently, but if an item is put in the cache and never accessed again, it's never removed, even though it's expired.
What's a good methodology for expiring such items from the cache?
Should I have a background thread infinitely enumerating every item in the cache to check if it's expired?
A: The best code is no code. Use the ASP.NET cache instead. You can reference it as System.Web.HttpRuntime.Cache in any application, not just web applications.
A: You can implement an LRU (Least Recently Used) strategy, keep your items sorted by access time, when a new item is inserted into the cache and the cache is full you evicted the item that is last in that list. See Cache algorithms at Wikipedia.
If you want to expire immediately, i would still only do that when things are accessed. I.e. when the cache object is accessed and it's time has expired refetch it.
A: You could also on any change to the cache (re-)start a Timer with the Interval set to the closest expiry timestamp. This will not be accurate to milliseconds and depend on a message pump running, but is not very resource-demanding.
Harald Scheirich's answer is better though, if you don't mind that objects are hanging around forever, when the cache is not updated.
A: You could clear suitably old items out of the cache on the first access after 1 minute after the last time items were cleared.
private DateTime nextFlush;
public object getItem(object key)
{
DateTime now = DateTime.Now
if (now > nextFlush)
{
Flush();
nextFlush = now.AddMinutes(1)
}
return fetchItem(key);
}
A: In my experience, maintaining a custom caching mechanism became more trouble than it was worth. There are several libraries out there that have already solved these problems. I would suggest using one of them. A popular one in .Net is the Enterprise Library, although I have limited experience with its caching abilities.
If you must use a custom caching mechanism, then I see no problem with a watchful thread idea you suggested. That is, if your application is a server-based application and not a web app. If it's a web app, you already have built in sliding expiration. You can then just wrap it in a strongly typed wrapper to avoid referencing cache items by key each time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: jdbc driver for Microsoft SQL Server CE(Compact Edition) 3.5 I want to be able to explore the contents of a DB for this version of the DB. I was thinking of using the Squirrel DB client (which needs a JDBC driver).
Therefore, I'm looking for a JDBC type 4 driver for SQL SERVER 3.5. Can somone point me to a FREE OR open source or trial ware ?
If no JDBC driver, how do MS developers explore a given .SDF file ?
Thank you,
BR,
~A
A: Have you tried SQL Server Management Studio Express?
You can access SQL Server Compact 3.5
databases stored on a smart device or
on the desktop computer by using SQL
Server Management Studio in SQL Server
or SQL Server Management Studio
Express (SSMSE). http://technet.microsoft.com/en-us/library/ms172037.aspx
As for the JDBC Driver, you could take a look at this one, provided by Microsoft. I don't know if it works with the Compact Edition or if you already tried it, but I thought it was worth mentioning.
A: 1- There isn't a JDBC driver and at time of writing, MS has no plans to create one.
2- There isn't a ODBC driver, so the next obvious answer (JDBC to ODBC bridge) won't help you.
3- Some JDBC vendors claim to be able to connect to 'any oledb' data source, so that is yoru most likely best bet-- link, but it won't necessarily be free.
A: Try jTDS, it's a free software JDBC driver for SQL Server and Sybase.
http://jtds.sourceforge.net/
A: JDBC driver uses TCP/IP connection. The compact edition most likely cannot listen on TCP/IP port 1433. Compact Edition is meant to be accessed by an application which has loaded the .dlls necessary to talk to it. It's meant for Visual Studio projects.
You need to uninstall compact edition and install SQL Express 2005/2008 instead. After installation enable the "sa" account, give it a password, enable SQL+NT authentication, and then enable the TCP/IP listener to listen on port 1433 (the default port).
Then, finally, you can connect with JDBC. Jtds is a JDBC3.0 driver and therefore requires JDK1.6+ . I prefer using the Microsoft 2005 JDBC2.0 driver.
A: There is a free program called SQLCeEditor that does it.
I'd still like a JDBC driver though since that would make it easy to use with Eclipse and Java.
A: Use SDF Viewer to explore your .SDF database file, can also import/export data, script and work with tables, indexes and foreign keys.
A: If you're into linq syntax, you can also use LinqPad. There's a free version that allows exploring the data and editing it. You would pay for autocompletion but you can live without it.
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Recursive List Flattening I could probably write this myself, but the specific way I'm trying to accomplish it is throwing me off. I'm trying to write a generic extension method similar to the others introduced in .NET 3.5 that will take a nested IEnumerable of IEnumerables (and so on) and flatten it into one IEnumerable. Anyone have any ideas?
Specifically, I'm having trouble with the syntax of the extension method itself so that I can work on a flattening algorithm.
A: Here is a modified Jon Skeet's answer to allow more than "one level":
static IEnumerable Flatten(IEnumerable enumerable)
{
foreach (object element in enumerable)
{
IEnumerable candidate = element as IEnumerable;
if (candidate != null)
{
foreach (object nested in Flatten(candidate))
{
yield return nested;
}
}
else
{
yield return element;
}
}
}
disclaimer: I don't know C#.
The same in Python:
#!/usr/bin/env python
def flatten(iterable):
for item in iterable:
if hasattr(item, '__iter__'):
for nested in flatten(item):
yield nested
else:
yield item
if __name__ == '__main__':
for item in flatten([1,[2, 3, [[4], 5]], 6, [[[7]]], [8]]):
print(item, end=" ")
It prints:
1 2 3 4 5 6 7 8
A: Isn't that what [SelectMany][1] is for?
enum1.SelectMany(
a => a.SelectMany(
b => b.SelectMany(
c => c.Select(
d => d.Name
)
)
)
);
A: Here's an extension that might help. It will traverse all nodes in your hierarchy of objects and pick out the ones that match a criteria. It assumes that each object in your hierarchy has a collection property that holds its child objects.
Here's the extension:
/// Traverses an object hierarchy and return a flattened list of elements
/// based on a predicate.
///
/// TSource: The type of object in your collection.</typeparam>
/// source: The collection of your topmost TSource objects.</param>
/// selectorFunction: A predicate for choosing the objects you want.
/// getChildrenFunction: A function that fetches the child collection from an object.
/// returns: A flattened list of objects which meet the criteria in selectorFunction.
public static IEnumerable<TSource> Map<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> selectorFunction,
Func<TSource, IEnumerable<TSource>> getChildrenFunction)
{
// Add what we have to the stack
var flattenedList = source.Where(selectorFunction);
// Go through the input enumerable looking for children,
// and add those if we have them
foreach (TSource element in source)
{
flattenedList = flattenedList.Concat(
getChildrenFunction(element).Map(selectorFunction,
getChildrenFunction)
);
}
return flattenedList;
}
Examples (Unit Tests):
First we need an object and a nested object hierarchy.
A simple node class
class Node
{
public int NodeId { get; set; }
public int LevelId { get; set; }
public IEnumerable<Node> Children { get; set; }
public override string ToString()
{
return String.Format("Node {0}, Level {1}", this.NodeId, this.LevelId);
}
}
And a method to get a 3-level deep hierarchy of nodes
private IEnumerable<Node> GetNodes()
{
// Create a 3-level deep hierarchy of nodes
Node[] nodes = new Node[]
{
new Node
{
NodeId = 1,
LevelId = 1,
Children = new Node[]
{
new Node { NodeId = 2, LevelId = 2, Children = new Node[] {} },
new Node
{
NodeId = 3,
LevelId = 2,
Children = new Node[]
{
new Node { NodeId = 4, LevelId = 3, Children = new Node[] {} },
new Node { NodeId = 5, LevelId = 3, Children = new Node[] {} }
}
}
}
},
new Node { NodeId = 6, LevelId = 1, Children = new Node[] {} }
};
return nodes;
}
First Test: flatten the hierarchy, no filtering
[Test]
public void Flatten_Nested_Heirachy()
{
IEnumerable<Node> nodes = GetNodes();
var flattenedNodes = nodes.Map(
p => true,
(Node n) => { return n.Children; }
);
foreach (Node flatNode in flattenedNodes)
{
Console.WriteLine(flatNode.ToString());
}
// Make sure we only end up with 6 nodes
Assert.AreEqual(6, flattenedNodes.Count());
}
This will show:
Node 1, Level 1
Node 6, Level 1
Node 2, Level 2
Node 3, Level 2
Node 4, Level 3
Node 5, Level 3
Second Test: Get a list of nodes that have an even-numbered NodeId
[Test]
public void Only_Return_Nodes_With_Even_Numbered_Node_IDs()
{
IEnumerable<Node> nodes = GetNodes();
var flattenedNodes = nodes.Map(
p => (p.NodeId % 2) == 0,
(Node n) => { return n.Children; }
);
foreach (Node flatNode in flattenedNodes)
{
Console.WriteLine(flatNode.ToString());
}
// Make sure we only end up with 3 nodes
Assert.AreEqual(3, flattenedNodes.Count());
}
This will show:
Node 6, Level 1
Node 2, Level 2
Node 4, Level 3
A: Function:
public static class MyExtentions
{
public static IEnumerable<T> RecursiveSelector<T>(this IEnumerable<T> nodes, Func<T, IEnumerable<T>> selector)
{
if(nodes.Any() == false)
{
return nodes;
}
var descendants = nodes
.SelectMany(selector)
.RecursiveSelector(selector);
return nodes.Concat(descendants);
}
}
Usage:
var ar = new[]
{
new Node
{
Name = "1",
Chilren = new[]
{
new Node
{
Name = "11",
Children = new[]
{
new Node
{
Name = "111",
}
}
}
}
}
};
var flattened = ar.RecursiveSelector(x => x.Children).ToList();
A: Hmm... I'm not sure exactly what you want here, but here's a "one level" option:
public static IEnumerable<TElement> Flatten<TElement,TSequence> (this IEnumerable<TSequence> sequences)
where TSequence : IEnumerable<TElement>
{
foreach (TSequence sequence in sequences)
{
foreach(TElement element in sequence)
{
yield return element;
}
}
}
If that's not what you want, could you provide the signature of what you do want? If you don't need a generic form, and you just want to do the kind of thing that LINQ to XML constructors do, that's reasonably simple - although the recursive use of iterator blocks is relatively inefficient. Something like:
static IEnumerable Flatten(params object[] objects)
{
// Can't easily get varargs behaviour with IEnumerable
return Flatten((IEnumerable) objects);
}
static IEnumerable Flatten(IEnumerable enumerable)
{
foreach (object element in enumerable)
{
IEnumerable candidate = element as IEnumerable;
if (candidate != null)
{
foreach (object nested in candidate)
{
yield return nested;
}
}
else
{
yield return element;
}
}
}
Note that that will treat a string as a sequence of chars, however - you may want to special-case strings to be individual elements instead of flattening them, depending on your use case.
Does that help?
A: Okay here's another version which is combined from about 3 answers above.
Recursive. Uses yield. Generic. Optional filter predicate. Optional selection function. About as concise as I could make it.
public static IEnumerable<TNode> Flatten<TNode>(
this IEnumerable<TNode> nodes,
Func<TNode, bool> filterBy = null,
Func<TNode, IEnumerable<TNode>> selectChildren = null
)
{
if (nodes == null) yield break;
if (filterBy != null) nodes = nodes.Where(filterBy);
foreach (var node in nodes)
{
yield return node;
var children = (selectChildren == null)
? node as IEnumerable<TNode>
: selectChildren(node);
if (children == null) continue;
foreach (var child in children.Flatten(filterBy, selectChildren))
{
yield return child;
}
}
}
Usage:
// With filter predicate, with selection function
var flatList = nodes.Flatten(n => n.IsDeleted == false, n => n.Children);
A: I thought I'd share a complete example with error handling and a single-logic apporoach.
Recursive flattening is as simple as:
LINQ version
public static class IEnumerableExtensions
{
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
return !source.Any() ? source :
source.Concat(
source
.SelectMany(i => selector(i).EmptyIfNull())
.SelectManyRecursive(selector)
);
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
}
Non-LINQ version
public static class IEnumerableExtensions
{
public static IEnumerable<T> SelectManyRecursive<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> selector)
{
if (source == null) throw new ArgumentNullException("source");
if (selector == null) throw new ArgumentNullException("selector");
foreach (T item in source)
{
yield return item;
var children = selector(item);
if (children == null)
continue;
foreach (T descendant in children.SelectManyRecursive(selector))
{
yield return descendant;
}
}
}
}
Design decisions
I decided to:
*
*disallow flattening of a null IEnumerable, this can be changed by removing exception throwing and:
*
*adding source = source.EmptyIfNull(); before return in the 1st version
*adding if (source != null) before foreach in the 2nd version
*allow returning of a null collection by the selector - this way I'm removing responsibility from the caller to assure the children list isn't empty, this can be changed by:
*
*removing .EmptyIfNull() in the first version - note that SelectMany will fail if null is returned by selector
*removing if (children == null) continue; in the second version - note that foreach will fail on a null IEnumerable parameter
*allow filtering children with .Where clause on the caller side or within the children selector rather than passing a children filter selector parameter:
*
*it won't impact the efficiency because in both versions it is a deferred call
*it would be mixing another logic with the method and I prefer to keep the logic separated
Sample use
I'm using this extension method in LightSwitch to obtain all controls on the screen:
public static class ScreenObjectExtensions
{
public static IEnumerable<IContentItemProxy> FindControls(this IScreenObject screen)
{
var model = screen.Details.GetModel();
return model.GetChildItems()
.SelectManyRecursive(c => c.GetChildItems())
.OfType<IContentItemDefinition>()
.Select(c => screen.FindControl(c.Name));
}
}
A: The SelectMany extension method does this already.
Projects each element of a sequence to
an IEnumerable<(Of <(T>)>) and
flattens the resulting sequences into
one sequence.
A: Since yield is not available in VB and LINQ provides both deferred execution and a concise syntax, you can also use.
<Extension()>
Public Function Flatten(Of T)(ByVal objects As Generic.IEnumerable(Of T), ByVal selector As Func(Of T, Generic.IEnumerable(Of T))) As Generic.IEnumerable(Of T)
If(objects.Any()) Then
Return objects.Union(objects.Select(selector).Where(e => e != null).SelectMany(e => e)).Flatten(selector))
Else
Return objects
End If
End Function
public static class Extensions{
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> objects, Func<T, IEnumerable<T>> selector) where T:Component{
if(objects.Any()){
return objects.Union(objects.Select(selector).Where(e => e != null).SelectMany(e => e).Flatten(selector));
}
return objects;
}
}
edited to include:
*
*empty enumerable per https://stackoverflow.com/a/30325216/107683,
*null enumerable per https://stackoverflow.com/a/39338919/107683
*C# implementation.
A: I had to implement mine from scratch because all of the provided solutions would break in case there is a loop i.e. a child that points to its ancestor. If you have the same requirements as mine please take a look at this (also let me know if my solution would break in any special circumstances):
How to use:
var flattenlist = rootItem.Flatten(obj => obj.ChildItems, obj => obj.Id)
Code:
public static class Extensions
{
/// <summary>
/// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the
/// items in the data structure regardless of the level of nesting.
/// </summary>
/// <typeparam name="T">Type of the recursive data structure</typeparam>
/// <param name="source">Source element</param>
/// <param name="childrenSelector">a function that returns the children of a given data element of type T</param>
/// <param name="keySelector">a function that returns a key value for each element</param>
/// <returns>a faltten list of all the items within recursive data structure of T</returns>
public static IEnumerable<T> Flatten<T>(this IEnumerable<T> source,
Func<T, IEnumerable<T>> childrenSelector,
Func<T, object> keySelector) where T : class
{
if (source == null)
throw new ArgumentNullException("source");
if (childrenSelector == null)
throw new ArgumentNullException("childrenSelector");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
var stack = new Stack<T>( source);
var dictionary = new Dictionary<object, T>();
while (stack.Any())
{
var currentItem = stack.Pop();
var currentkey = keySelector(currentItem);
if (dictionary.ContainsKey(currentkey) == false)
{
dictionary.Add(currentkey, currentItem);
var children = childrenSelector(currentItem);
if (children != null)
{
foreach (var child in children)
{
stack.Push(child);
}
}
}
yield return currentItem;
}
}
/// <summary>
/// This would flatten out a recursive data structure ignoring the loops. The end result would be an enumerable which enumerates all the
/// items in the data structure regardless of the level of nesting.
/// </summary>
/// <typeparam name="T">Type of the recursive data structure</typeparam>
/// <param name="source">Source element</param>
/// <param name="childrenSelector">a function that returns the children of a given data element of type T</param>
/// <param name="keySelector">a function that returns a key value for each element</param>
/// <returns>a faltten list of all the items within recursive data structure of T</returns>
public static IEnumerable<T> Flatten<T>(this T source,
Func<T, IEnumerable<T>> childrenSelector,
Func<T, object> keySelector) where T: class
{
return Flatten(new [] {source}, childrenSelector, keySelector);
}
}
A: static class EnumerableExtensions
{
public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> sequence)
{
foreach(var child in sequence)
foreach(var item in child)
yield return item;
}
}
Maybe like this? Or do you mean that it could potentially be infintly deep?
A: class PageViewModel {
public IEnumerable<PageViewModel> ChildrenPages { get; set; }
}
Func<IEnumerable<PageViewModel>, IEnumerable<PageViewModel>> concatAll = null;
concatAll = list => list.SelectMany(l => l.ChildrenPages.Any() ?
concatAll(l.ChildrenPages).Union(new[] { l }) : new[] { l });
var allPages = concatAll(source).ToArray();
A: Basicly, you need to have a master IENumerable that is outside of your recursive function, then in your recursive function (Psuedo-code)
private void flattenList(IEnumerable<T> list)
{
foreach (T item in list)
{
masterList.Add(item);
if (item.Count > 0)
{
this.flattenList(item);
}
}
}
Though I'm really not sure what you mean by IEnumerable nested in an IEnumerable...whats within that? How many levels of nesting? Whats the final type? obviously my code isn't correct, but I hope it gets you thinking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
}
|
Q: How to configure secure RESTful services with WCF using username/password + SSL I'm looking to write a config file that allows for RESTful services in WCF, but I still want the ability to 'tap into' the membership provider for username/password authentication.
The below is part of my current config using basicHttp binding or wsHttp w/out WS Security, how will this change w/ REST based services?
<bindings>
<wsHttpBinding>
<binding name="wsHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false"/>
</security>
</binding>
</wsHttpBinding>
<basicHttpBinding>
<binding name="basicHttp">
<security mode="TransportWithMessageCredential">
<transport/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="NorthwindBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
A: Here's a podcast on securing WCF REST services with the ASP.net membership provider:
http://channel9.msdn.com/posts/rojacobs/endpointtv-Securing-RESTful-services-with-ASPNET-Membership/
A: I agree with Darrel that complex REST scenarios over WCF are a bad idea. It just isn't pretty.
However, Dominick Baier has some good posts about this on his least privilege blog.
If you'd like to see WSSE authentication support with fallback to FormsAuthenticationTicket support on WCF, check out the source code of BlogService.
A: Before you continue down this path of fighting to implement REST over WCF, I suggest you read this post by Tim Ewald. I was especially impacted by the following statement:
I'm not sure I want to build on a
layer designed to factor HTTP in on
top of a layer that was designed to
factor it out.
I've spent the last 12 months developing REST based stuff with WCF and that statement has proven itself to be so true over and over again. IMHO what WCF brings to the table is outweighed by the complexity it introduces for doing REST work.
A: Regardless if the community has opinions against REST on WCF (I'm personally on the fence) Microsoft has taken a swipe at it, http://msdn.microsoft.com/en-us/netframework/cc950529.aspx
A: Yes agreed with Moto, a link off the WCF Starter Kit is the closest thing I saw to authentication of credentials using a custom HTTP header (http://msdn.microsoft.com/en-us/library/dd203052.aspx).
However I could not get the example going.
A: Try custombasicauth @ codeplex
A: UPDATE 01/23/2012
Since I wrote this question I've seen a much better approach to securing REST like web services in the wild. It sounded complex when I first heard about it but the idea is simple and all over the web for both web services and other secure communication.
It requires the use of public/private keys.
1.) each user (customer) of the endpoint will need to register with your REST web service
*
*a.) you give this user a private key that should not be shared with
anyone
*b.) you also generate a public key that can go over the wire
in plain text if need be (this will also be used to identify the client)
2.) each request from the user needs to generate a hash to sign the request
*
*a.) One example of this might look like: private key + a timestamp + encoded payload (if small enough like a simple user info to be updated for example)
*b.) you take these 3 (or whatever you decided on) and generate a 1 way hash (using hmac for example)
*c.) in the request being sent over the wire you include the public key (so the server side knows who is attempting to send this request), the hash that was generated w/ the private key, and the timestamp.
3.) the server endpoint (your REST method) will need to generate a hash using the same inputs used on the client. This step will prove that both client and server knew a private key that matched the public key passed along with the request. (this in turn means that the user sending the request is legit as no one else could know the private key)
*
*a.) lookup the customers private key by the public key being passed along during the request
*b.) take the other params (timestamp and the encoded payload) along with the private key you found in the previous step and use the same algorithm to generate a 1 way hash (again hmac is what I've seen used in the real world)
*c.) the resulting 1 way hash needs to match the hash sent over the wire, if not send back a 400 (or whatever http code you deem to be a "bad request")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Is there an easy way to populate SlugField from CharField? class Foo(models.Model):
title = models.CharField(max_length=20)
slug = models.SlugField()
Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
A: for Admin in Django 1.0 and up, you'd need to use
prepopulated_fields = {'slug': ('title',), }
in your admin.py
Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated.
Outside of admin, you can use the slugify function in your views. In templates, you can use the |slugify filter.
There is also this package which will take care of this automatically: https://pypi.python.org/pypi/django-autoslug
A: Thought I would add a complete and up-to-date answer with gotchas mentioned:
1. Auto-populate forms in Django Admin
If you are only concerned about adding and updating data in the admin, you could simply use the prepopulated_fields attribute
class ArticleAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Article, ArticleAdmin)
2. Auto-populate custom forms in templates
If you have built your own server-rendered interface with forms, you could auto-populate the fields by using either the |slugify tamplate filter or the slugify utility when saving the form (is_valid).
3. Auto-populating slugfields at model-level with django-autoslug
The above solutions will only auto-populate the slugfield (or any field) when data is manipulated through those interfaces (the admin or a custom form). If you have an API, management commands or anything else that also manipulates the data you need to drop down to model-level.
django-autoslug provides the AutoSlugField-fields which extends SlugField and allows you to set which field it should slugify neatly:
class Article(Model):
title = CharField(max_length=200)
slug = AutoSlugField(populate_from='title')
The field uses pre_save and post_save signals to achieve its functionality so please see the gotcha text at the bottom of this answer.
4. Auto-populating slugfields at model-level by overriding save()
The last option is to implement this yourself, which involves overriding the default save() method:
class Article(Model):
title = CharField(max_length=200)
slug = SlugField()
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)
NOTE: Bulk-updates will bypass your code (including signals)
This is a common miss-understanding by beginners to Django. First you should know that the pre_save and post_save signals are directly related to the save()-method. Secondly the different ways to do bulk-updates in Django all circumvent the save()-method to achieve high performance, by operating directly on the SQL-layer. This means that for the example model used in solution 3 or 4 above:
*
*Article.objects.all().update(title='New post') will NOT update the slug of any article
*Using bulk_create or bulk_update on the Article model will NOT update the slug of any article.
*Since the save()-method is not called, no pre_save or post_save signals will be emitted.
To do bulk updates and still utilize code-level constraints the only solution is to iterate objects one by one and call its save()-method, which has drastically less performance than SQL-level bulk operations. You could of course use triggers in your database, though that is a totally different topic.
A: Outside the admin, see this django snippet. Put it in your .save(), and it'll work with objects created programmatically. Inside the admin, as the others have said, use prepopulated_fields.
A: For pre-1.0:
slug = models.SlugField(prepopulate_from=('title',))
should work just fine
For 1.0, use camflan's
A: You can also use pre_save django signal to populate slug outside of django admin code.
See Django signals documentation.
Ajax slug uniqueness validation will be useful too, see As-You-Type Slug Uniqueness Validation @ Irrational Exuberance
A: prepopulated_fields = {'slug': ('title',), }
A: Auto-populating slugfields at model-level with the built-in django slugify:
models.py
from django.db import models
class Place:
name = models.CharField(max_length=50)
slug_name = models.SlugField(max_length=50)
signals.py
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify as django_slugify
from v1 import models
@receiver(pre_save, sender=models.Place)
def validate_slug_name(sender, instance: models.Place, **kwargs):
instance.slug_name = django_slugify(instance.name)
Credits to: https://github.com/justinmayer/django-autoslug/blob/9e3992296544a4fd7417a833a9866112021daa82/autoslug/utils.py#L18
A: autoslug has worked quite well for me in the past. Although I've never tried using it with the admin app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: What open source C++ static analysis tools are available? Java has some very good open source static analysis tools such as FindBugs, Checkstyle and PMD. Those tools are easy to use, very helpful, runs on multiple operating systems and free.
Commercial C++ static analysis products are available. Although having such products are great, the cost is just way too much for students and it is usually rather hard to get trial version.
The alternative is to find open source C++ static analysis tools that will run on multiple platforms (Windows and Unix). By using an open source tool, it could be modified to fit certain needs. Finding the tools has not been easy task.
Below is a short list of C++ static analysis tools that were found or suggested by others.
*
*C++ Check http://sf.net/projects/cppcheck/
*Oink http://danielwilkerson.com/oink/index.html
*C and C++ Code Counter http://sourceforge.net/projects/cccc/
*Splint (from answers)
*Mozilla's Pork (from answers) (This is now part of Oink)
*Mozilla's Dehydra (from answers)
*Use option -Weffc++ for GNU g++ (from answers)
What are some other portable open source C++ static analysis tools that anyone knows of and can be recommended?
Some related links.
*
*http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis
*http://www.chris-lott.org/resources/cmetrics/
*A free tool to check C/C++ source code against a set of coding standards?
*http://spinroot.com/static/
*Choosing a static code analysis tool
A: CppCheck is open source and cross-platform.
Mac OSX:
brew install cppcheck
A: If by Open Source, you really meant "free", then Microsoft's prefast analysis is a good one. Windows-only ofcourse. It is fully integrated in Visual Studio & the compiler. e.g.:
cl /analyze Sample.cpp
A: Mozilla's static analysis work is probably worth a look.
A: Concerning the GNU compiler, gcc has already a builtin option that enables additional warning to those of -Wall. The option is -Weffc++ and it's about the violations of some guidelines of Scott Meyers published in his books "Effective and More Effective C++".
In particular the option detects the following items:
*
*Define a copy constructor and an assignment operator for classes with dynamically allocated memory.
*Prefer initialization to assignment in constructors.
*Make destructors virtual in base classes.
*Have "operator=" return a reference to *this.
*Don’t try to return a reference when you must return an object.
*Distinguish between prefix and postfix forms of increment and decrement operators.
*Never overload "&&", "||", or ",".
A: Splint seems to fill the bill for C.
If you didn't specify open source I'd say Gimpel Software's PCLint is probably one of the best tools available for static code checking in C++. But, of course, it's not open source.
Mac OSX:
brew install splint
A: Microsoft's PREFast is also available in the Windows Driver Kit. Version 7.0 is downloadable here.
The Microsoft docs state that it should only be run against driver code but this (old) blog post lays out steps to run it. Perhaps it can be integrated into a normal build process?
A: Under development for now, but clang does C analysis and is targeted to handle C++ over time. It's part of the LLVM project.
Update: While the landing page says "The analyzer is a continuous work-in-progress", it is nevertheless now documented as a static analyzer for both C and C++.
Question: How can I run GCC/Clang for static analysis? (warnings only)
Compiler option: -fsyntax-only
A: Oink is a tool built on top of the Elsa C++ front-end. Mozilla's Pork is a fork of Elsa/Oink.
See: http://danielwilkerson.com/oink/index.html
A: We have been working on an Eclipse CDT plug-in called metriculator. Its still under development but some major metrics (e.g. LSLOC, McCabe, EfferentCoupling) are already implemented.
See http://sinv-56013.edu.hsr.ch/redmine/projects/metricular/wiki/Documentation for more details like video demonstration and documentation.
The latest nightly build is available for installation via update site at: http://sinv-56013.edu.hsr.ch/metriculator/updatesite-nightly/site/
Further Description
Metriculator statically analysis C++ source code and generates software metrics. Metrics are implemented as
Codan checkers. The analysis results can be explored in a separate view. Each
metric has configurable properties (e.g. a threshold for 'max lines of code per
function'). Exceeding these threshold will report a problem and create a marker
in the source code editor.
with metriculator you can:
*
*analyse C++ files / folders / projects
*define metric thresholds and enable / disable metric using Codans preference page
*have problem markers in source code editors
*explore metric results
*export metric results as tag cloud (available as optional feature via update site)
Currently metriculator comes with the following metrics:
*
*McCabe (Cyclomatic Complexity)
*EfferentCoupling per Type
*Logical Source Lines of Code
*Number of Members per Type
*Number of Parameters per Function
A: Someone else mentioned -Weffc++, but that is actually one of the only GCC warnings I do not turn on by default. However, the set of warnings that I do turn on is the most important static analysis tool in my kit. You can see the complete list of recommended warnings.
In summary:
-pedantic -Wall -Wextra -Wcast-align -Wcast-qual -Wctor-dtor-privacy -Wdisabled-optimization -Wformat=2 -Winit-self -Wlogical-op -Wmissing-declarations -Wmissing-include-dirs -Wnoexcept -Wold-style-cast -Woverloaded-virtual -Wredundant-decls -Wshadow -Wsign-conversion -Wsign-promo -Wstrict-null-sentinel -Wstrict-overflow=5 -Wswitch-default -Wundef -Werror -Wno-unused
Note that some of these require a new version of gcc, so you may need to eliminate them from your list if you are stuck back on 4.5 or something.
A: John Carmack also mentions PVS-Studio in this interesting blog post on "Static Code Analysis".
A: You should try oo-browser it has awesome integration with xemacs
A: One can also code extensions of GCC in MELT (a domain specific language designed for extending GCC) or GCC plugins in C (much harder) to do some custom analysis.
A: Doxygen does some control flow analysis and generates graphs. Those may not be what you're looking for, but I've foudn them useful to look at.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "306"
}
|
Q: Any Java libraries out there that validate SQL syntax? I'm not sure if this even exists or not, so I figured I would tap the wisdom of others..
I was wondering if there are any Java libraries out there that can be used to validate a SQL query's syntax. I know that there are many deviations from common SQL spec, so it would probably only work against something like SQL:2006, but that would certainly suffice.
My goal is to use this for unit-testing purposes without needing to attempt the execution against the DB. I know it's of limited use, but it would still be useful.
Thanks!
A: Perhaps you can use Antlr, it has a number of SQL grammars and a Java library, as well as plugins for various Java IDEs.
Or as advised, use the parser of open source SQL utilities like SQuirreL SQL Client.
A: General SQL Parser can do offline SQL syntax check. Supported databases: Oracle, DB2, MySQL, SQL Server, Teradata and PostgreSQL.
A: I don't think there are such libraries. The SQL syntax has too many derivatives.
A possible solution would be to use parts of an open source pure Java DBMS like SmallSQL. In this project you can create an instance of the SQLParser. The needed references to the connection can be removed very easily.
A: Try JSQL parser.
In addition to validating, you obtain a meaningful representation of the query.
This allows you, for example, to only accept "certain" commands; manipulate
the query, "prettify" it, etc.
A: You might be able to extract the parsing code out from HSQL, which is java and open source.
A: Apache Derby is an open source SQL database implemented entirely in Java and available under the Apache License, Version 2.0. It was formerly known as IBM Cloudscape.
You may try to reuse it's parsing code from org.apache.derby.impl.sql.
A: With JOOQ you will never make a mistake in SQL. Java compiler will take care of that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Visual Studio 2008 source control for small teams I work on a small web team where I am the only .NET developer currently using Visual Studio 2008 Professional to build and maintain a few web applications. I am about to start training another member of our team so we purchased him a copy of Visual Studio 2008 Professional. I've looked into Visual Source Safe, but I'm dubious. I don't like that is file system based. Ideally, the system would work with SQL Server 2005 and plug into Visual Studio. Windows based solutions are the best because of the IT environment of the organization I work for.
What are my options for a source control system?
(Forgive me if the answer exists in another thread.)
A: Has any body given Git any thought? There is a very usable solution for windows called GitExtensions here. It integrates with Visual Studio Professional trough an extra menu and optional toolbar. Unlike Subversion, Git is distributed, which means you can commit locally to your copy of the repository, and afterwards push the changes to the server. The bottom line? Git is FAST! It's storage is also more efficient than subversion, which means your repository takes up less space.
A: Subversion. Free. Visual SVN is a great add on, and is fairly inexpensive.
A: Definitely, as most people says, Subversion + VisualSVN.
VisualSVN is a fairly cheap addon at $49, subversion is free and very stable. We use that for teams of 10-15 people and it works really well for us. The only con is that it is file-system based.
On the other hand, if you have a very specific need for it not to be on the file system i would NOT recommend Visual Source Safe, on my last job we had a lot of trouble with it and lost precious days of work. If you want to go that way get something like sourcegear vault which is database based. There is also Team Foundation Server from Microsoft but I believe it is really expensive (and heavy) for small teams.
A: Subversion has good integration with Visual Studio 2008 through VisualSVN and Ankh.
SourceSafe is dangerous. You're right that a filesharing-based SCM is a bad idea, and Microsoft themselves have downplayed it and replaced it with a new SCM that comes with the Team edition of Visual Studio.
A: Visual SVN
might work for you, it is supposed to integrate well and is relatively cheap at ~$50 per license. I've been considering buying it myself, so far I just use Tortoise SVN as I do relatively little non-Eclipse work right now.
A: Team Foundation Server does satisfy your requirements of working with SQL Server, but is probably overkill for such a small development team.
I would recommend using Subversion (free) for source control along with VisualSVN ($49) for the visual studio integration. There is also an excellent Subversion client for windows explorer called TortoiseSVN, which is awesome.
The nice thing about giving something like Subversion a try is that it is free and very easy to set up. It will also scale up to a pretty large team. It is worth a shot before investing effort in MSFTs Team Foundation Server.
A: I can't believe nobody has mentioned SourceGear Vault. It stores your code in SQL Server, integrates extremely well into VS, and is an excellent replacement/alternative to Source Safe. Since their single-user license is free, I even use it when coding at home. Plus, it's the company founded/run by Eric Sink.
A: Microsoft's Team Foundation Server integrates fully into VS2008 and uses SQL Server for its back end. The downside is that it's a very expensive solution.
A: Why not use a SVN server? That way, all your developers can use it, and there is a very good free Windows Client for it (TortoiseSVN). You can integrate SVN support with TortoiseSVN into Visual Studio with VisualSVN, which is commercial, but not actually expensive.
A: We switched over from SourceSafe to tfs recently and have found it to work quite capably.
The only notable exception in features we exercised is file linking.
To keep the costs down, we make sure that we get the Gold Certified Partner status.
A: I recommend subversion, coupled with AnkhSVN, a plugin (Free!) that integrates Subversion with the Visual Studio IDE.
If you use the svnserve distribution that's free from CollabNet (Windows binaries: here), setup is very simple. Administration is very easy. And the product works very well.
It is still file-system based, but that isn't really a problem. Make sure that you back-up regularly, both full dumps and hot-copies (both of which are explained in detail in the documentation).
A: Visual Source Safe has a bad rap from it's earlier incarnations. They came out with a new version in 2005, and it solves many of the problems of earlier versions. I don't think they've solved the branching problems though. They have a client/server portion now (well, it's http based) so that solves some of the remote issues.
SVN is probably a better solution, but VSS isn't as bad as it once was.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Does anyone know when the ASP.NET MVC will be fully released? When do you think we can expect the full release version of ASP.NET MVC?
A: EDIT (16/Jul/2009)
Updating to ensure this page contains the most recent details.
ASP.NET MVC is now fully released http://www.asp.net/mvc/.
EDIT (28/Jan/2009)
ASP.NET MVC 1.0 RC Now Available.... final next month (From ScottGu's Blog)
Today’s RC is the last public release
of ASP.NET MVC that we’ll ship prior
to the final “1.0” release. We expect
to ship the final ASP.NET MVC 1.0
release next month.
Last I heard, Q4 2008.
Scott Hanselman posted this in his blog about 3.5 SP1
What about ASP.NET MVC?
There is likely some confusion around
MVC as a few people expected ASP.NET
MVC to ship in SP1. This is probably
because MVC was included in 3.5
"Extensions Preview." However, the
plan was always to ship in Q4CY08.
(That date is marketing speak, I've
just learned. I tell people what Eilon
told me - it'll ship in a month ending
in "-ber." Possible "March-ber" but
also maybe "next June-ber.")
Anyway, Phil has always said that MVC
is on its own schedule and will ship
when its done. Possibly when Duke
Nukem Forever ships.
A: There can be only speculations right now. I will then speculate that we will have a Beta in December (they said the next preview will be the Beta) and a full Release in February-March 2009.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which php variable debugging function do you use? var_dump, print_r, var_export, other? I personally use var_dump, but lots of people like print_r.
What does everyone use? Pros and Cons?
Does someone have a special home brew function of their own?
A: I use print_r() because I like the pretty array structure... but var_dump does give you a bit more information (like types)
$obj = (object) array(1, 2, 3);
// output of var_dump:
object(stdClass)#1 (3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
// output of print_r
stdClass Object
(
[0] => 1
[1] => 2
[2] => 3
)
A: I use these custom functions depending on whether I'm dealing with an array or a single value:
function show($array)
{
echo '<pre>';
print_r($array);
echo '</pre>';
}
function prn($var)
{
echo '<br/>' . $var . '<br/>';
}
I find that these functions simplify troubleshooting because I generally end up needing to format the output so that I can go through it easily right on screen.
For more complex troubleshooting, we use an extended version of the Exception class that will email a stack trace along with a specific error message. This gives me the functions that were involved, what files were involved and what line or lines were involved in the error as well as whatever custom message I created so that I know exactly what's going on. For an added layer of troubleshooting, we also log these errors in the database being accessed.
A: I always use the Xdebug extended var_dump. It gives out a lot of verbose output.
See: http://xdebug.org/docs/display for more details.
A: I just user print_r, along with a couple of wrapper functions to store the various DebugPrint I put in my code and one on the footer to dump the stack in the page (or in a file).
I now try to use XDebug too... :-D
OK, for the record, I give my little functions...
// Primitive debug message storage
// $level = "Info", "Warn", "Error", "Title"
function DebugPrint($toDump, $level = "Info") {
global $debugMode, $debugDump, $debugCount;
if ($debugMode != 'N') {
$debugDump[$debugCount++] = "<div class='Dbg$level'>" . $toDump . "</div>\n";
}
}
// Initialize debug information collection
$debugMode = 'N'; // N=no, desactivated, P=dump to Web page, F=dump to file
$debugSavePath = 'C:\www\App\log_debug.txt'; // If mode F
$debugDump = array();
$debugCount = 0;
// Primitive debug message dump
function DebugDump() {
global $debugMode, $debugSavePath, $debugDump, $debugCount;
if ($debugMode == 'F') {
$fp = fopen($debugSavePath, "a"); #open for writing
}
if ($debugCount > 0) {
switch ($debugMode) {
case 'P':
echo '<div style="color: red; background: #8FC; font-size: 24px;">Debug:<br />
';
for ($i = 0; $i < $debugCount; $i++) {
echo $debugDump[$i];
}
echo '</div>
';
break;
case 'F':
for ($i = 0; $i < $debugCount; $i++) {
fputs($fp, $debugDump[$i]);
}
break;
//~ default:
//~ echo "debugMode = $debugMode<br />\n";
}
}
if ($fp != null) {
fputs($fp, "-----\n");
fclose($fp);
}
}
// Pre array dump
function DebugArrayPrint($array) {
global $debugMode;
if ($debugMode != 'N') {
return "<pre class='ArrayPrint'>" . print_r($array, true) . "</pre>";
} else return ""; // Gain some microseconds...
}
The interest is to delay the output to the end of the page, avoiding to clutter the real page.
A: If you want to avoid sending errors to the browser but want the advantage of var_dump and print_r then take a look at output buffering:
ob_start();
var_dump($this); echo $that; print_r($stuff);
$out = ob_get_contents();
ob_end_clean();
user_error($out);
some good reading in http://www.php.net/manual/en/book.outcontrol.php
A: There is something I find very useful that lacks from the standard PHP implementations of variable dump functions, i.e. the ability to just print part of an expression.
Here is a function that solves this:
function dump($val) {
echo '<pre>'.var_export($val,true).'</pre>';
return $val;
}
Now I can just put a function call around the expression I need to know the value of without distrupting usual code execution flow like this:
$a=2+dump(2*2);
With use of less-known var_export I also eliminated the need to implement output buffering to post-process the result.
A: When you generate a binary answer (i.e. an image using GD library), then you can use a valid tuned header:
header('X-eleg:'.serialize($yourstuff));
and use the Http-header extension for Firefox to "spy" it.
A: print_r() usually, but var_dump() provides better information for primitives.
That being said, I do most of my actual debugging with the Zend Server Debugger.
A: var_dump. With XDebug installed it formats and colors the output nicely (no having to put <pre> tags around it).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Windows clipboard CRLF/LF passing wrong for one user We have a pair of applications. One is written in C# and uses something like:
string s = "alpha\r\nbeta\r\ngamma\r\ndelta";
// Actually there's wrapper code here to make sure this works.
System.Windows.Forms.Clipboard.SetDataObject(s, true);
To put a list of items onto the clipboard. Another application (in WinBatch) then picks up the list using a ClipGet() function. (We use the clipboard functions to give people the option of editing the list in notepad or something, without having to actually cut-and-paste every time.)
In this particular environment, we have many users on one system via Citrix. Many using these pairs of programs.
Just one user is having the problem where the line delimiters in the text are getting switched from CRLF to LF somewhere between the SetDataObject() and the CLipGet(). I could explain this in a mixed Unix/Windows environment, but there is no Unix here. No unix-y utilities anywhere near this system either. Other users on the same server, no problems at all. It's like something in Windows/Citrix is being "helpful" when we really don't want it, but just for this one guy.
Ideas?
A: Have you tried clearing their profile on Citrix? That seems to be the solution to many many user specific Citrix problems.
A: Does Environment.NewLine behave differently on Citrix environments? If so, it may give you a good option that works for all users instead of \r\n.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are bitwise shift (bit-shift) operators and how do they work? I've been attempting to learn C in my spare time, and other languages (C#, Java, etc.) have the same concept (and often the same operators)...
At a core level, what does bit-shifting (<<, >>, >>>) do, what problems can it help solve, and what gotchas lurk around the bend? In other words, an absolute beginner's guide to bit shifting in all its goodness.
A: Note that in the Java implementation, the number of bits to shift is mod'd by the size of the source.
For example:
(long) 4 >> 65
equals 2. You might expect shifting the bits to the right 65 times would zero everything out, but it's actually the equivalent of:
(long) 4 >> (65 % 64)
This is true for <<, >>, and >>>. I have not tried it out in other languages.
A: Bit Masking & Shifting
Bit shifting is often used in low-level graphics programming. For example, a given pixel color value encoded in a 32-bit word.
Pixel-Color Value in Hex: B9B9B900
Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000
For better understanding, the same binary value labeled with what sections represent what color part.
Red Green Blue Alpha
Pixel-Color Value in Binary: 10111001 10111001 10111001 00000000
Let's say for example we want to get the green value of this pixel's color. We can easily get that value by masking and shifting.
Our mask:
Red Green Blue Alpha
color : 10111001 10111001 10111001 00000000
green_mask : 00000000 11111111 00000000 00000000
masked_color = color & green_mask
masked_color: 00000000 10111001 00000000 00000000
The logical & operator ensures that only the values where the mask is 1 are kept. The last thing we now have to do, is to get the correct integer value by shifting all those bits to the right by 16 places (logical right shift).
green_value = masked_color >>> 16
Et voilà, we have the integer representing the amount of green in the pixel's color:
Pixels-Green Value in Hex: 000000B9
Pixels-Green Value in Binary: 00000000 00000000 00000000 10111001
Pixels-Green Value in Decimal: 185
This is often used for encoding or decoding image formats like jpg, png, etc.
A: Some useful bit operations/manipulations in Python.
I implemented Ravi Prakash's answer in Python.
# Basic bit operations
# Integer to binary
print(bin(10))
# Binary to integer
print(int('1010', 2))
# Multiplying x with 2 .... x**2 == x << 1
print(200 << 1)
# Dividing x with 2 .... x/2 == x >> 1
print(200 >> 1)
# Modulo x with 2 .... x % 2 == x & 1
if 20 & 1 == 0:
print("20 is a even number")
# Check if n is power of 2: check !(n & (n-1))
print(not(33 & (33-1)))
# Getting xth bit of n: (n >> x) & 1
print((10 >> 2) & 1) # Bin of 10 == 1010 and second bit is 0
# Toggle nth bit of x : x^(1 << n)
# take bin(10) == 1010 and toggling second bit in bin(10) we get 1110 === bin(14)
print(10^(1 << 2))
A: The Bitwise operators are used to perform operations a bit-level or to manipulate bits in different ways. The bitwise operations are found to be much faster and are some times used to improve the efficiency of a program.
Basically, Bitwise operators can be applied to the integer types: long, int, short, char and byte.
Bitwise Shift Operators
They are classified into two categories left shift and the right shift.
*
*Left Shift(<<): The left shift operator, shifts all of the bits in value to the left a specified number of times. Syntax: value << num. Here num specifies the number of position to left-shift the value in value. That is, the << moves all of the bits in the specified value to the left by the number of bit positions specified by num. For each shift left, the high-order bit is shifted out (and ignored/lost), and a zero is brought in on the right. This means that when a left shift is applied to 32-bit compiler, bits are lost once they are shifted past bit position 31. If the compiler is of 64-bit then bits are lost after bit position 63.
Output: 6, Here the binary representation of 3 is 0...0011(considering 32-bit system) so when it shifted one time the leading zero is ignored/lost and all the rest 31 bits shifted to left. And zero is added at the end. So it became 0...0110, the decimal representation of this number is 6.
*
*In the case of a negative number:
Output: -2, In java negative number, is represented by 2's complement. SO, -1 represent by 2^32-1 which is equivalent to 1....11(Considering 32-bit system). When shifted one time the leading bit is ignored/lost and the rest 31 bits shifted to left and zero is added at the last. So it becomes, 11...10 and its decimal equivalent is -2.
So, I think you get enough knowledge about the left shift and how its work.
*
*Right Shift(>>): The right shift operator, shifts all of the bits in value to the right a specified of times. Syntax: value >> num, num specifies the number of positions to right-shift the value in value. That is, the >> moves/shift all of the bits in the specified value of the right the number of bit positions specified by num.
The following code fragment shifts the value 35 to the right by two positions:
Output: 8, As a binary representation of 35 in a 32-bit system is 00...00100011, so when we right shift it two times the first 30 leading bits are moved/shifts to the right side and the two low-order bits are lost/ignored and two zeros are added at the leading bits. So, it becomes 00....00001000, the decimal equivalent of this binary representation is 8.
Or there is a simple mathematical trick to find out the output of this following code: To generalize this we can say that, x >> y = floor(x/pow(2,y)). Consider the above example, x=35 and y=2 so, 35/2^2 = 8.75 and if we take the floor value then the answer is 8.
Output:
But remember one thing this trick is fine for small values of y if you take the large values of y it gives you incorrect output.
*
*In the case of a negative number:
Because of the negative numbers the Right shift operator works in two modes signed and unsigned. In signed right shift operator (>>), In case of a positive number, it fills the leading bits with 0. And In case of a negative number, it fills leading bits with 1. To keep the sign. This is called 'sign extension'.
Output: -5, As I explained above the compiler stores the negative value as 2's complement. So, -10 is represented as 2^32-10 and in binary representation considering 32-bit system 11....0110. When we shift/ move one time the first 31 leading bits got shifted in the right side and the low-order bit got lost/ignored. So, it becomes 11...0011 and the decimal representation of this number is -5 (How I know the sign of number? because the leading bit is 1).
It is interesting to note that if you shift -1 right, the result always remains -1 since sign extension keeps bringing in more ones in the high-order bits.
*
*Unsigned Right Shift(>>>): This operator also shifts bits to the right. The difference between signed and unsigned is the latter fills the leading bits with 1 if the number is negative and the former fills zero in either case. Now the question arises why we need unsigned right operation if we get the desired output by signed right shift operator. Understand this with an example, If you are shifting something that does not represent a numeric value, you may not want sign extension to take place. This situation is common when you are working with pixel-based values and graphics. In these cases, you will generally want to shift a zero into the high-order bit no matter what it's the initial value was.
Output: 2147483647, Because -2 is represented as 11...10 in a 32-bit system. When we shift the bit by one, the first 31 leading bit is moved/shifts in right and the low-order bit is lost/ignored and the zero is added to the leading bit. So, it becomes 011...1111 (2^31-1) and its decimal equivalent is 2147483647.
A: One gotcha is that the following is implementation dependent (according to the ANSI standard):
char x = -1;
x >> 1;
x can now be 127 (01111111) or still -1 (11111111).
In practice, it's usually the latter.
A: I am writing tips and tricks only. It may be useful in tests and exams.
*
*n = n*2: n = n<<1
*n = n/2: n = n>>1
*Checking if n is power of 2 (1,2,4,8,...): check !(n & (n-1))
*Getting xth bit of n: n |= (1 << x)
*Checking if x is even or odd: x&1 == 0 (even)
*Toggle the nth bit of x: x ^ (1<<n)
A: Let's say we have a single byte:
0110110
Applying a single left bitshift gets us:
1101100
The leftmost zero was shifted out of the byte, and a new zero was appended to the right end of the byte.
The bits don't rollover; they are discarded. That means if you left shift 1101100 and then right shift it, you won't get the same result back.
Shifting left by N is equivalent to multiplying by 2N.
Shifting right by N is (if you are using ones' complement) is the equivalent of dividing by 2N and rounding to zero.
Bitshifting can be used for insanely fast multiplication and division, provided you are working with a power of 2. Almost all low-level graphics routines use bitshifting.
For example, way back in the olden days, we used mode 13h (320x200 256 colors) for games. In Mode 13h, the video memory was laid out sequentially per pixel. That meant to calculate the location for a pixel, you would use the following math:
memoryOffset = (row * 320) + column
Now, back in that day and age, speed was critical, so we would use bitshifts to do this operation.
However, 320 is not a power of two, so to get around this we have to find out what is a power of two that added together makes 320:
(row * 320) = (row * 256) + (row * 64)
Now we can convert that into left shifts:
(row * 320) = (row << 8) + (row << 6)
For a final result of:
memoryOffset = ((row << 8) + (row << 6)) + column
Now we get the same offset as before, except instead of an expensive multiplication operation, we use the two bitshifts...in x86 it would be something like this (note, it's been forever since I've done assembly (editor's note: corrected a couple mistakes and added a 32-bit example)):
mov ax, 320; 2 cycles
mul word [row]; 22 CPU Cycles
mov di,ax; 2 cycles
add di, [column]; 2 cycles
; di = [row]*320 + [column]
; 16-bit addressing mode limitations:
; [di] is a valid addressing mode, but [ax] isn't, otherwise we could skip the last mov
Total: 28 cycles on whatever ancient CPU had these timings.
Vrs
mov ax, [row]; 2 cycles
mov di, ax; 2
shl ax, 6; 2
shl di, 8; 2
add di, ax; 2 (320 = 256+64)
add di, [column]; 2
; di = [row]*(256+64) + [column]
12 cycles on the same ancient CPU.
Yes, we would work this hard to shave off 16 CPU cycles.
In 32 or 64-bit mode, both versions get a lot shorter and faster. Modern out-of-order execution CPUs like Intel Skylake (see http://agner.org/optimize/) have very fast hardware multiply (low latency and high throughput), so the gain is much smaller. AMD Bulldozer-family is a bit slower, especially for 64-bit multiply. On Intel CPUs, and AMD Ryzen, two shifts are slightly lower latency but more instructions than a multiply (which may lead to lower throughput):
imul edi, [row], 320 ; 3 cycle latency from [row] being ready
add edi, [column] ; 1 cycle latency (from [column] and edi being ready).
; edi = [row]*(256+64) + [column], in 4 cycles from [row] being ready.
vs.
mov edi, [row]
shl edi, 6 ; row*64. 1 cycle latency
lea edi, [edi + edi*4] ; row*(64 + 64*4). 1 cycle latency
add edi, [column] ; 1 cycle latency from edi and [column] both being ready
; edi = [row]*(256+64) + [column], in 3 cycles from [row] being ready.
Compilers will do this for you: See how GCC, Clang, and Microsoft Visual C++ all use shift+lea when optimizing return 320*row + col;.
The most interesting thing to note here is that x86 has a shift-and-add instruction (LEA) that can do small left shifts and add at the same time, with the performance as an add instruction. ARM is even more powerful: one operand of any instruction can be left or right shifted for free. So scaling by a compile-time-constant that's known to be a power-of-2 can be even more efficient than a multiply.
OK, back in the modern days... something more useful now would be to use bitshifting to store two 8-bit values in a 16-bit integer. For example, in C#:
// Byte1: 11110000
// Byte2: 00001111
Int16 value = ((byte)(Byte1 >> 8) | Byte2));
// value = 000011111110000;
In C++, compilers should do this for you if you used a struct with two 8-bit members, but in practice they don't always.
A: The bit shifting operators do exactly what their name implies. They shift bits. Here's a brief (or not-so-brief) introduction to the different shift operators.
The Operators
*
*>> is the arithmetic (or signed) right shift operator.
*>>> is the logical (or unsigned) right shift operator.
*<< is the left shift operator, and meets the needs of both logical and arithmetic shifts.
All of these operators can be applied to integer values (int, long, possibly short and byte or char). In some languages, applying the shift operators to any datatype smaller than int automatically resizes the operand to be an int.
Note that <<< is not an operator, because it would be redundant.
Also note that C and C++ do not distinguish between the right shift operators. They provide only the >> operator, and the right-shifting behavior is implementation defined for signed types. The rest of the answer uses the C# / Java operators.
(In all mainstream C and C++ implementations including GCC and Clang/LLVM, >> on signed types is arithmetic. Some code assumes this, but it isn't something the standard guarantees. It's not undefined, though; the standard requires implementations to define it one way or another. However, left shifts of negative signed numbers is undefined behaviour (signed integer overflow). So unless you need arithmetic right shift, it's usually a good idea to do your bit-shifting with unsigned types.)
Left shift (<<)
Integers are stored, in memory, as a series of bits. For example, the number 6 stored as a 32-bit int would be:
00000000 00000000 00000000 00000110
Shifting this bit pattern to the left one position (6 << 1) would result in the number 12:
00000000 00000000 00000000 00001100
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled with a zero. You might also note that shifting left is equivalent to multiplication by powers of 2. So 6 << 1 is equivalent to 6 * 2, and 6 << 3 is equivalent to 6 * 8. A good optimizing compiler will replace multiplications with shifts when possible.
Non-circular shifting
Please note that these are not circular shifts. Shifting this value to the left by one position (3,758,096,384 << 1):
11100000 00000000 00000000 00000000
results in 3,221,225,472:
11000000 00000000 00000000 00000000
The digit that gets shifted "off the end" is lost. It does not wrap around.
Logical right shift (>>>)
A logical right shift is the converse to the left shift. Rather than moving bits to the left, they simply move to the right. For example, shifting the number 12:
00000000 00000000 00000000 00001100
to the right by one position (12 >>> 1) will get back our original 6:
00000000 00000000 00000000 00000110
So we see that shifting to the right is equivalent to division by powers of 2.
Lost bits are gone
However, a shift cannot reclaim "lost" bits. For example, if we shift this pattern:
00111000 00000000 00000000 00000110
to the left 4 positions (939,524,102 << 4), we get 2,147,483,744:
10000000 00000000 00000000 01100000
and then shifting back ((939,524,102 << 4) >>> 4) we get 134,217,734:
00001000 00000000 00000000 00000110
We cannot get back our original value once we have lost bits.
Arithmetic right shift (>>)
The arithmetic right shift is exactly like the logical right shift, except instead of padding with zero, it pads with the most significant bit. This is because the most significant bit is the sign bit, or the bit that distinguishes positive and negative numbers. By padding with the most significant bit, the arithmetic right shift is sign-preserving.
For example, if we interpret this bit pattern as a negative number:
10000000 00000000 00000000 01100000
we have the number -2,147,483,552. Shifting this to the right 4 positions with the arithmetic shift (-2,147,483,552 >> 4) would give us:
11111000 00000000 00000000 00000110
or the number -134,217,722.
So we see that we have preserved the sign of our negative numbers by using the arithmetic right shift, rather than the logical right shift. And once again, we see that we are performing division by powers of 2.
A: Bitwise operations, including bit shift, are fundamental to low-level hardware or embedded programming. If you read a specification for a device or even some binary file formats, you will see bytes, words, and dwords, broken up into non-byte aligned bitfields, which contain various values of interest. Accessing these bit-fields for reading/writing is the most common usage.
A simple real example in graphics programming is that a 16-bit pixel is represented as follows:
bit | 15| 14| 13| 12| 11| 10| 9 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
| Blue | Green | Red |
To get at the green value you would do this:
#define GREEN_MASK 0x7E0
#define GREEN_OFFSET 5
// Read green
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
Explanation
In order to obtain the value of green ONLY, which starts at offset 5 and ends at 10 (i.e. 6-bits long), you need to use a (bit) mask, which when applied against the entire 16-bit pixel, will yield only the bits we are interested in.
#define GREEN_MASK 0x7E0
The appropriate mask is 0x7E0 which in binary is 0000011111100000 (which is 2016 in decimal).
uint16_t green = (pixel & GREEN_MASK) ...;
To apply a mask, you use the AND operator (&).
uint16_t green = (pixel & GREEN_MASK) >> GREEN_OFFSET;
After applying the mask, you'll end up with a 16-bit number which is really just a 11-bit number since its MSB is in the 11th bit. Green is actually only 6-bits long, so we need to scale it down using a right shift (11 - 6 = 5), hence the use of 5 as offset (#define GREEN_OFFSET 5).
Also common is using bit shifts for fast multiplication and division by powers of 2:
i <<= x; // i *= 2^x;
i >>= y; // i /= 2^y;
A: Be aware of that only 32 bit version of PHP is available on the Windows platform.
Then if you for instance shift << or >> more than by 31 bits, results are unexpectable. Usually the original number instead of zeros will be returned, and it can be a really tricky bug.
Of course if you use 64 bit version of PHP (Unix), you should avoid shifting by more than 63 bits. However, for instance, MySQL uses the 64-bit BIGINT, so there should not be any compatibility problems.
UPDATE: From PHP 7 Windows, PHP builds are finally able to use full 64 bit integers:
The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1515"
}
|
Q: MVC n-level route building I want to create a productcatalog with N-Level Categories
e.g.
/Catalog/Category1/Category2/../SubCategoryN/Product/{ProductActions}/{ID}
And at the same time be able to
/Catalog/Category1/Category2/../SubCategoryN/{CategoryActions}
Is that possible and if Yes how?
A: Not with the default Route class, but you can make your own route class by deriving from RouteBase. You basically end up having to do all the work yourself of parsing the URL, but you can use the source from Route to help you get started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to overload __init__ method based on argument type? Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type by looking at __class__?
Is there some trick I might be missing?
I'm used to C++ where overloading by argument type is easy.
A: A much neater way to get 'alternate constructors' is to use classmethods. For instance:
>>> class MyData:
... def __init__(self, data):
... "Initialize MyData from a sequence"
... self.data = data
...
... @classmethod
... def fromfilename(cls, filename):
... "Initialize MyData from a file"
... data = open(filename).readlines()
... return cls(data)
...
... @classmethod
... def fromdict(cls, datadict):
... "Initialize MyData from a dict's items"
... return cls(datadict.items())
...
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]
The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.
A: Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:
Here's a sample (this is a read method and not a constructor, but the idea is the same):
def read(self, str=None, filename=None, addr=0):
""" Read binary data and return a store object. The data
store is also saved in the interal 'data' attribute.
The data can either be taken from a string (str
argument) or a file (provide a filename, which will
be read in binary mode). If both are provided, the str
will be used. If neither is provided, an ArgumentError
is raised.
"""
if str is None:
if filename is None:
raise ArgumentError('Please supply a string or a filename')
file = open(filename, 'rb')
str = file.read()
file.close()
...
... # rest of code
The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:
obj.read(filename="blob.txt")
And to read it from a string, I say:
obj.read(str="\x34\x55")
This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex
A: with python3, you can use Implementing Multiple Dispatch with Function Annotations as Python Cookbook wrote:
import time
class Date(metaclass=MultipleMeta):
def __init__(self, year:int, month:int, day:int):
self.year = year
self.month = month
self.day = day
def __init__(self):
t = time.localtime()
self.__init__(t.tm_year, t.tm_mon, t.tm_mday)
and it works like:
>>> d = Date(2012, 12, 21)
>>> d.year
2012
>>> e = Date()
>>> e.year
2018
A: You should use isinstance
isinstance(...)
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
A: You probably want the isinstance builtin function:
self.data = data if isinstance(data, list) else self.parse(data)
A: Quick and dirty fix
class MyData:
def __init__(string=None,list=None):
if string is not None:
#do stuff
elif list is not None:
#do other stuff
else:
#make data empty
Then you can call it with
MyData(astring)
MyData(None, alist)
MyData()
A: A better way would be to use isinstance and type conversion. If I'm understanding you right, you want this:
def __init__ (self, filename):
if isinstance (filename, basestring):
# filename is a string
else:
# try to convert to a list
self.path = list (filename)
A: OK, great. I just tossed together this example with a tuple, not a filename, but that's easy. Thanks all.
class MyData:
def __init__(self, data):
self.myList = []
if isinstance(data, tuple):
for i in data:
self.myList.append(i)
else:
self.myList = data
def GetData(self):
print self.myList
a = [1,2]
b = (2,3)
c = MyData(a)
d = MyData(b)
c.GetData()
d.GetData()
[1, 2]
[2, 3]
A: My preferred solution is:
class MyClass:
_data = []
__init__(self,data=None):
# do init stuff
if not data: return
self._data = list(data) # list() copies the list, instead of pointing to it.
Then invoke it with either MyClass() or MyClass([1,2,3]).
Hope that helps. Happy Coding!
A: Why don't you go even more pythonic?
class AutoList:
def __init__(self, inp):
try: ## Assume an opened-file...
self.data = inp.read()
except AttributeError:
try: ## Assume an existent filename...
with open(inp, 'r') as fd:
self.data = fd.read()
except:
self.data = inp ## Who cares what that might be?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "417"
}
|
Q: What are the pitfalls of inserting millions of records into SQL Server from flat file? I am about to start on a journey writing a windows forms application that will open a txt file that is pipe delimited and about 230 mb in size. This app will then insert this data into a sql server 2005 database (obviously this needs to happen swiftly). I am using c# 3.0 and .net 3.5 for this project.
I am not asking for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?).
Thank you, and I will edit the question for clarity if anyone needs it.
A: Do you have to write a winforms app? It might be much easier and faster to use SSIS. There are some built-in tasks available especially Bulk Insert task.
Also, worth checking Flat File Bulk Import methods speed comparison in SQL Server 2005.
Update: If you are new to SSIS, check out some of these sites to get you on fast track. 1) SSIS Control Flow Basics 2) Getting Started with SQL Server Integration Services
This is another How to: on importing Excel file into SQL 2005.
A: This is going to be a streaming endeavor.
If you can, do not use transactions here. The transactional cost will simply be too great.
So what you're going to do is read the file a line at a time and insert it in a line at a time. You should dump failed inserts into another file that you can diagnose later and see where they failed.
At first I would go ahead and try a bulk insert of a couple of hundred rows just to see that the streaming is working properly and then you can open up all you want.
A: You could try using SqlBulkCopy. It lets you pull from "any data source".
A: Just as a side note, it's sometimes faster to drop the indices of your table and recreate them after the bulk insert operation.
A: You might consider switching from full recovery to bulk-logged. This will help to keep your backups a reasonable size.
A: I totally recommend SSIS, you can read in millions of records and clean them up along the way in relatively little time.
You will need to set aside some time to get to grips with SSIS, but it should pay off. There are a few other threads here on SO which will probably be useful:
What's the fastest way to bulk insert a lot of data in SQL Server (C# client)
What are the recommended learning material for SSIS?
You can also create a package from C#. I have a C# program which reads a 3GL "master file" from a legacy system (parses into an object model using an API I have for a related project), takes a package template and modifies it to generate a package for the ETL.
A: If the column format of the file matches the target table where the data needs to end up, I prefer using the command line utility bcp to load the data file. It's blazingly fast and you can specify and error file for any "odd" records that fail to be inserted.
Your app could kick off the command if you need to store the command line parameters for it (server, database, username / password or trusted connection, table, error file etc.).
I like this method better than running a BULK INSERT SQL command because the data file isn't required to be on a system accessible by the database server. To use bulk insert you have to specify the path to the data file to load, so it must be a path visible and readable by the system user on the database server that is running the load. Too much hassle for me usually. :-)
A: The size of data you're talking about actually isn't that gigantic. I don't know what your efficiency concerns are, but if you can wait a few hours for it to insert, you might be surprised at how easy this would be to accomplish with a really naive technique of just INSERTing each row one at a time. Batching together a thousand or so rows at a time and submitting them to SQL server may make it quite a bit faster as well.
Just a suggestion that could save you some serious programming time, if you don't need it to be as fast as conceivable. Depending on how often this import has to run, saving a few days of programming time could easily be worth it in exchange for waiting a few hours while it runs.
A: You could use SSIS for the read & insert, but call it as a package from your WinForms app. Then you could pass in things like source, destination, connection strings etc as parameter/configurations.
HowTo: http://msdn.microsoft.com/en-us/library/aa337077.aspx
You can set up transforms and error handling inside SSIS and even create logical branching based on input parameters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Should try...catch go inside or outside a loop? I have a loop that looks something like this:
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
This is the main content of a method whose sole purpose is to return the array of floats. I want this method to return null if there is an error, so I put the loop inside a try...catch block, like this:
try {
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
} catch (NumberFormatException ex) {
return null;
}
But then I also thought of putting the try...catch block inside the loop, like this:
for (int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
} catch (NumberFormatException ex) {
return null;
}
myFloats[i] = myNum;
}
Is there any reason, performance or otherwise, to prefer one over the other?
Edit: The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?
A: Performance: as Jeffrey said in his reply, in Java it doesn't make much difference.
Generally, for readability of the code, your choice of where to catch the exception depends upon whether you want the loop to keep processing or not.
In your example you returned upon catching an exception. In that case, I'd put the try/catch around the loop. If you simply want to catch a bad value but carry on processing, put it inside.
The third way: You could always write your own static ParseFloat method and have the exception handling dealt with in that method rather than your loop. Making the exception handling isolated to the loop itself!
class Parsing
{
public static Float MyParseFloat(string inputValue)
{
try
{
return Float.parseFloat(inputValue);
}
catch ( NumberFormatException e )
{
return null;
}
}
// .... your code
for(int i = 0; i < max; i++)
{
String myString = ...;
Float myNum = Parsing.MyParseFloat(myString);
if ( myNum == null ) return;
myFloats[i] = (float) myNum;
}
}
A: As already mentioned, the performance is the same. However, user experience isn't necessarily identical. In the first case, you'll fail fast (i.e. after the first error), however if you put the try/catch block inside the loop, you can capture all the errors that would be created for a given call to the method. When parsing an array of values from strings where you expect some formatting errors, there are definitely cases where you'd like to be able to present all the errors to the user so that they don't need to try and fix them one by one.
A: All right, after Jeffrey L Whitledge said that there was no performance difference (as of 1997), I went and tested it. I ran this small benchmark:
public class Main {
private static final int NUM_TESTS = 100;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, Jeffrey is correct; there is absolutely no performance difference on Java 6, Sun client VM (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or Ray Hayes's way.
A: If its an all-or-nothing fail, then the first format makes sense. If you want to be able to process/return all the non-failing elements, you need to use the second form. Those would be my basic criteria for choosing between the methods. Personally, if it is all-or-nothing, I wouldn't use the second form.
A: As long as you are aware of what you need to accomplish in the loop you could put the try catch outside the loop. But it is important to understand that the loop will then end as soon as the exception occurs and that may not always be what you want. This is actually a very common error in Java based software. People need to process a number of items, such as emptying a queue, and falsely rely on an outer try/catch statement handling all possible exceptions. They could also be handling only a specific exception inside the loop and not expect any other exception to occur.
Then if an exception occurs that is not handled inside the loop then the loop will be "preemted", it ends possibly prematurely and the outer catch statement handles the exception.
If the loop had as its role in life to empty a queue then that loop very likely could end before that queue was really emptied. Very common fault.
A: My perspective would be try/catch blocks are necessary to insure proper exception handling, but creating such blocks has performance implications. Since, Loops contain intensive repetitive computations, it is not recommended to put try/catch blocks inside loops. Additionally, it seems where this condition occurs, it is often "Exception" or "RuntimeException" which is caught. RuntimeException being caught in code should be avoided. Again, if if you work in a big company it's essential to log that exception properly, or stop runtime exception to happen. Whole point of this description is PLEASE AVOID USING TRY-CATCH BLOCKS IN LOOPS
A: In your examples there is no functional difference. I find your first example more readable.
A: You should prefer the outer version over the inner version. This is just a specific version of the rule, move anything outside the loop that you can move outside the loop. Depending on the IL compiler and JIT compiler your two versions may or may not end up with different performance characteristics.
On another note you should probably look at float.TryParse or Convert.ToFloat.
A: If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.
A: I's like to add my own 0.02c about two competing considerations when looking at the general problem of where to position exception handling:
*
*The "wider" the responsibility of the try-catch block (i.e. outside the loop in your case) means that when changing the code at some later point, you may mistakenly add a line which is handled by your existing catch block; possibly unintentionally. In your case, this is less likely because you are explicitly catching a NumberFormatException
*The "narrower" the responsibility of the try-catch block, the more difficult refactoring becomes. Particularly when (as in your case) you are executing a "non-local" instruction from within the catch block (the return null statement).
A: If you want to catch Exception for each iteration, or check at what iteration Exception is thrown and catch every Exceptions in an iteration, place try...catch inside the loop. This will not break the loop if Exception occurs and you can catch every Exception in each iteration throughout the loop.
If you want to break the loop and examine the Exception whenever thrown, use try...catch out of the loop. This will break the loop and execute statements after catch (if any).
It all depends on your need. I prefer using try...catch inside the loop while deploying as, if Exception occurs, the results aren't ambiguous and loop will not break and execute completely.
A: While performance might be the same and what "looks" better is very subjective, there is still a pretty big difference in functionality. Take the following example:
Integer j = 0;
try {
while (true) {
++j;
if (j == 20) { throw new Exception(); }
if (j%4 == 0) { System.out.println(j); }
if (j == 40) { break; }
}
} catch (Exception e) {
System.out.println("in catch block");
}
The while loop is inside the try catch block, the variable 'j' is incremented until it hits 40, printed out when j mod 4 is zero and an exception is thrown when j hits 20.
Before any details, here the other example:
Integer i = 0;
while (true) {
try {
++i;
if (i == 20) { throw new Exception(); }
if (i%4 == 0) { System.out.println(i); }
if (i == 40) { break; }
} catch (Exception e) { System.out.println("in catch block"); }
}
Same logic as above, only difference is that the try/catch block is now inside the while loop.
Here comes the output (while in try/catch):
4
8
12
16
in catch block
And the other output (try/catch in while):
4
8
12
16
in catch block
24
28
32
36
40
There you have quite a significant difference:
while in try/catch breaks out of the loop
try/catch in while keeps the loop active
A: PERFORMANCE:
There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.
Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html
The table is described about half-way down.
A: I agree with all the performance and readability posts. However, there are cases where it really does matter. A couple other people mentioned this, but it might be easier to see with examples.
Consider this slightly modified example:
public static void main(String[] args) {
String[] myNumberStrings = new String[] {"1.2345", "asdf", "2.3456"};
ArrayList asNumbers = parseAll(myNumberStrings);
}
public static ArrayList parseAll(String[] numberStrings){
ArrayList myFloats = new ArrayList();
for(int i = 0; i < numberStrings.length; i++){
myFloats.add(new Float(numberStrings[i]));
}
return myFloats;
}
If you want the parseAll() method to return null if there are any errors (like the original example), you'd put the try/catch on the outside like this:
public static ArrayList parseAll1(String[] numberStrings){
ArrayList myFloats = new ArrayList();
try{
for(int i = 0; i < numberStrings.length; i++){
myFloats.add(new Float(numberStrings[i]));
}
} catch (NumberFormatException nfe){
//fail on any error
return null;
}
return myFloats;
}
In reality, you should probably return an error here instead of null, and generally I don't like having multiple returns, but you get the idea.
On the other hand, if you want it to just ignore the problems, and parse whatever Strings it can, you'd put the try/catch on the inside of the loop like this:
public static ArrayList parseAll2(String[] numberStrings){
ArrayList myFloats = new ArrayList();
for(int i = 0; i < numberStrings.length; i++){
try{
myFloats.add(new Float(numberStrings[i]));
} catch (NumberFormatException nfe){
//don't add just this one
}
}
return myFloats;
}
A: If it's inside, then you'll gain the overhead of the try/catch structure N times, as opposed to just the once on the outside.
Every time a Try/Catch structure is called it adds overhead to the execution of the method. Just the little bit of memory & processor ticks needed to deal with the structure. If you're running a loop 100 times, and for hypothetical sake, let's say the cost is 1 tick per try/catch call, then having the Try/Catch inside the loop costs you 100 ticks, as opposed to only 1 tick if it's outside of the loop.
A: setting up a special stack frame for the try/catch adds additional overhead, but the JVM may be able to detect the fact that you're returning and optimize this away.
depending on the number of iterations, performance difference will likely be negligible.
However i agree with the others that having it outside the loop make the loop body look cleaner.
If there's a chance that you'll ever want to continue on with the processing rather than exit if there an invalid number, then you would want the code to be inside the loop.
A: The whole point of exceptions is to encourage the first style: letting the error handling be consolidated and handled once, not immediately at every possible error site.
A: put it inside. You can keep processing (if you want) or you can throw a helpful exception that tells the client the value of myString and the index of the array containing the bad value. I think NumberFormatException will already tell you the bad value but the principle is to place all the helpful data in the exceptions that you throw. Think about what would be interesting to you in the debugger at this point in the program.
Consider:
try {
// parse
} catch (NumberFormatException nfe){
throw new RuntimeException("Could not parse as a Float: [" + myString +
"] found at index: " + i, nfe);
}
In the time of need you will really appreciate an exception like this with as much information in it as possible.
A: That depends on the failure handling. If you just want to skip the error elements, try inside:
for(int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
} catch (NumberFormatException ex) {
--i;
}
}
In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.
A: I'll put my $0.02 in. Sometimes you wind up needing to add a "finally" later on in your code (because who ever writes their code perfectly the first time?). In those cases, suddenly it makes more sense to have the try/catch outside the loop. For example:
try {
for(int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
}
} catch (NumberFormatException ex) {
return null;
} finally {
dbConnection.release(); // Always release DB connection, even if transaction fails.
}
Because if you get an error, or not, you only want to release your database connection (or pick your favorite type of other resource...) once.
A: Another aspect not mentioned in the above is the fact that every try-catch has some impact on the stack, which can have implications for recursive methods.
If method "outer()" calls method "inner()" (which may call itself recursively), try to locate the try-catch in method "outer()" if possible. A simple "stack crash" example we use in a performance class fails at about 6,400 frames when the try-catch is in the inner method, and at about 11,600 when it is in the outer method.
In the real world, this can be an issue if you're using the Composite pattern and have large, complex nested structures.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "210"
}
|
Q: SQL to find the number of distinct values in a column I can select all the distinct values in a column in the following ways:
*
*SELECT DISTINCT column_name FROM table_name;
*SELECT column_name FROM table_name GROUP BY column_name;
But how do I get the row count from that query? Is a subquery required?
A: You can use the DISTINCT keyword within the COUNT aggregate function:
SELECT COUNT(DISTINCT column_name) AS some_alias FROM table_name
This will count only the distinct values for that column.
A: An sql sum of column_name's unique values and sorted by the frequency:
SELECT column_name, COUNT(*) FROM table_name GROUP BY column_name ORDER BY 2 DESC;
A: Be aware that Count() ignores null values, so if you need to allow for null as its own distinct value you can do something tricky like:
select count(distinct my_col)
+ count(distinct Case when my_col is null then 1 else null end)
from my_table
/
A: This will give you BOTH the distinct column values and the count of each value. I usually find that I want to know both pieces of information.
SELECT [columnName], count([columnName]) AS CountOf
FROM [tableName]
GROUP BY [columnName]
A: SELECT COUNT(DISTINCT column_name) FROM table as column_name_count;
you've got to count that distinct col, then give it an alias.
A: select count(*) from
(
SELECT distinct column1,column2,column3,column4 FROM abcd
) T
This will give count of distinct group of columns.
A: select Count(distinct columnName) as columnNameCount from tableName
A: Using following SQL we can get the distinct column value count in Oracle 11g.
select count(distinct(Column_Name)) from TableName
A: After MS SQL Server 2012, you can use window function too.
SELECT column_name, COUNT(column_name) OVER (PARTITION BY column_name)
FROM table_name
GROUP BY column_name
A: To do this in Presto using OVER:
SELECT DISTINCT my_col,
count(*) OVER (PARTITION BY my_col
ORDER BY my_col) AS num_rows
FROM my_tbl
Using this OVER based approach is of course optional. In the above SQL, I found specifying DISTINCT and ORDER BY to be necessary.
Caution: As per the docs, using GROUP BY may be more efficient.
A: select count(distinct(column_name)) AS columndatacount from table_name where somecondition=true
You can use this query, to count different/distinct data.
A: Without using DISTINCT this is how we could do it-
SELECT COUNT(C)
FROM (SELECT COUNT(column_name) as C
FROM table_name
GROUP BY column_name)
A: Count(distinct({fieldname})) is redundant
Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "423"
}
|
Q: Bulk time entry into timesprite / fogbugz Is there a good way to import time data into either timesprite or fogbugz? Both seem to have very clunky interfaces for adding single items at a time. What I want is a spreadsheet-style format that I can enter a bunch of rows and suck them in. Noticed timesprite has an import on it, but it seems to only want timesprite formatted XML.
A: You can use the FogBugz API to bulk-add time records into FogBugz. I don't know of an existing spreadsheet-entry interface that uses the API to load data into FogBugz, but one could easily be written for the purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Storing Relational Data in XML I'm wondering what the best practices are for storing a relational data structure in XML. Particulary, I am wondering about best practices for enforcing node order. For example, say I have three objects: School, Course, and Student, which are defined as follows:
class School
{
List<Course> Courses;
List<Student> Students;
}
class Course
{
string Number;
string Description;
}
class Student
{
string Name;
List<Course> EnrolledIn;
}
I would store such a data structure in XML like so:
<School>
<Courses>
<Course Number="ENGL 101" Description="English I" />
<Course Number="CHEM 102" Description="General Inorganic Chemistry" />
<Course Number="MATH 103" Description="Trigonometry" />
</Courses>
<Students>
<Student Name="Jack">
<EnrolledIn>
<Course Number="CHEM 102" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
<Student Name="Jill">
<EnrolledIn>
<Course Number="ENGL 101" />
<Course Number="MATH 103" />
</EnrolledIn>
</Student>
</Students>
</School>
With the XML ordered this way, I can parse Courses first. Then, when I parse Students, I can look up each Course listed in EnrolledIn (by its Number) in the School.Courses list. This will give me an object reference to add to the EnrolledIn list in Student. If Students, however, comes before Courses, such a lookup to get a object reference is not possible. (Since School.Courses has not yet been populated.)
So what are the best practices for storing relational data in XML?
- Should I enforce that Courses must always come before Students?
- Should I tolerate any ordering and create a stub Course object whenever I encounter one I have not yet seen? (To be expanded when the definition of the Course is eventually reached later.)
- Is there some other way I should be persisting/loading my objects to/from XML? (I am currently implementing Save and Load methods on all my business objects and doing all this manually using System.Xml.XmlDocument and its associated classes.)
I am used to working with relational data out of SQL, but this is my first experience trying to store a non-trivial relational data structure in XML. Any advice you can provide as to how I should proceed would be greatly appreciated.
A: While you can specify order of child elements using a <xsd:sequence>, by requiring child objects to come in specific order you make your system less flexible (i.e., harder to update using notepad).
Best thing to do is to parse out all your data, then perform what actions you need to do. Don't act during the parse.
Obviously, the design of the XML and the data behind it precludes serializing a single POCO to XML. You need to control the serialization and deserialization logic in order to unhook and re-hook objects together.
I'd suggest creating a custom serializer that builds the xml representation of this object graph. It can thereby control not only the order of serialization, but also handle situations where nodes aren't in the expected order. You could do other things such as adding custom attributes to use for linking objects together which don't exist as public properties on the objects being serialized.
Creating the xml would be as simple as iterating over your objects a few times, building up collections of XElements with the expected representation of the objects as xml. When you're done you can stitch them together into an XDocument and grab the xml from it. You can make multiple passes over the xml on the reverse side to re-create your object graph and restore all references.
A: Don't think in SQL or relational when working with XML, because there are no order constraints.
You can however query using XPath to any portion of the XML document at any time. You want the courses first, then "//Courses/Course". You want the students enrollments next, then "//Students/Student/EnrolledIn/Course".
The bottom line being... just because XML is stored in a file, don't get caught thinking all your accesses are serial.
I posted a separate question, "Can XPath do a foreign key lookup across two subtrees of an XML?", in order to clarify my position. The solution shows how you can use XPath to make relational queries against XML data.
A: Node ordering is only important if you need to do forward-only processing of the data, e.g. using an XmlReader or a SAX parser. If you're going to read the XML into a DOM before processing it (which you are if you're using XmlDocument), node order doesn't really matter. What matters more is that the XML be structured so that you can query it with XPath efficiently, i.e. without having to use "//".
If you take a look at the schema that the DataSetGenerator produces, you'll see that there's no ordering associated with the DataTable-level elements. It may be that ADO processes elements in some sequence not represented in the schema (e.g. one DataTable at a time), or it may be that ADO does forward-only processing and doesn't enforce relational constraints until the DataSet is fully read. I don't know. But it's clear that ADO doesn't couple the processing order to the document order.
(And yes, you can specify the order of child elements in an XML schema; that's what xs:sequence does. If you don't want node order to be enforced, you use an unbounded xs:choice.)
A: From experience, XML isn't the best to store relational data. Have you investigated YAML? Do you have the option?
If you don't, a safe way would be to have a strict DTD for the XML and enforce that way. You could also, as you suggest, keep a hash of objects created. That way if a Student creates a Course you keep that Course around for future updating when the tag is hit.
Also remember you can use XPath queries to access specific nodes directly, so you can enforce parsing of courses first regardless of position in the XML document. (making a more complete answer, thanks to dacracot)
A: The order is not usually important in XML. In this case the Courses could come after Students. You parse the XML and then you make your queries on the entire data.
A: XML is definitely not a friendly place for relational data.
If you absolutely need to do this, then I'd recommend a funky inverted kind of logic.
In your example, you've got Schools, which offers many courses, taken by many students.
Your XML might follow as such:
<School>
<Students>
<Student Name="Jack">
<EnrolledIn>
<Course Number="CHEM 102" Description="General Inorganic Chemistry" />
<Course Number="MATH 103" Description="Trigonometry" />
</EnrolledIn>
</Student>
<Student Name="Jill">
<EnrolledIn>
<Course Number="ENGL 101" Description="English I" />
<Course Number="MATH 103" Description="Trigonometry" />
</EnrolledIn>
</Student>
</Students>
</School>
This obviously isn't the least repetitive way to do this (it's relational data!), but it's easily parse-able.
A: You could also use two XML files, one for courses and a second for students. Open and parse the first before you do the second.
A: I's been a while, but I seem to remember doing a base collection of 'things' in one part of an xml file, and referring to them in another using the schema features keyref and refer. I found a few examples here. My apologies if this is not what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you get a list of changes from a Subversion repository by date range? What I would like is be able to generate a simple report that is the output of svn log for a certain date range. Specifically, all the changes since 'yesterday'.
Is there an easy way to accomplish this in Subversion besides grep-ing the svn log output for the timestamp?
Example:
svn -v log -d 2008-9-23:2008-9:24 > report.txt
A: svn log -r '{2013-9-23}:{2013-9-24}'
This is might be the correct syntex.
Quotes are required to get the correct results.
A: Very first hit by google for "svn log date range": http://svn.haxx.se/users/archive-2006-08/0737.shtml
So svn log <url> -r
{2008-09-19}:{2008-09-26} will get
all changes for the past week,
including today.
And if you want to generate reports for a repo, there's a solution: Statsvn.
HTH
A: You can do this:
svn log -r{2008-9-23}:{2008-9-24} > report.txt
Add a --xml before the -r if you want ot get the output in xml format for "easier" post processing.
A: The -v is important if you want to see a list of the actual changes (over and above the log messages... if any! ;) )
A: You can use dates the same as you can use revision numbers. The syntax is {yyyy-mm-dd}. So, for all changes between 12:00am on September 23 and 12am on September 24, do:
svn log -v -r {2008-09-23}:{2008-09-24} > report.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "57"
}
|
Q: LINQ Syntext Sequence The following SQL
SELECT * FROM customers
converted to this in LINQ
var customers = from c in customers
select c;
Is their any good reasones why the from and select is swaped?
The only logical reason I can think of is for intellisens? For the intellesens to get resolved, it needs to know what it is querying (scope)?
Any other reasons why it was swaped?
A: Select is swapped because it represents the order of the method calls that the LINQ query syntax is representing.
This is equivalent to
customers.Select(c=>c);
or
customers.Select();
SQL gets away with it, by processing the entire statement before proceeding, but in order to get things like intellisense and to figure out if your select is valid it has to be the last step and not the first.
You might also want to look at FLWOR, which is a closer representation, which stands for for, let, where, orderby, and return. You'll note the for, which is equivalent to from, is first; and the return, which is equivalent to select, is last.
SQL, here, is more the abnormality. How is one supposed to know what you're operating on before you've specified your domain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I hide content in a HTML file from search engines? Say that I write an article or document about a certain topic, but the content is meant for readers with certain prior knowledge about the topic. To help people who don't have the "required" background information, I would like to add a note to the top of the page with an explanation and possibly a link to some reference material.
Here's an example:
Using The Best Product in the World to Create World Peace
Note: This article assumes you are already familiar with The Best Product in the World. To learn more about The Best Product in the World, please see the official web site.
The Best Product in the World ...
Now, I don't want the note to show up in Google search engine results, only the title and the content that follows the note. Is there any way I can achieve this?
Also, is it possible to do this without direct control over the entire HTML file and/or HTTP response, i.e. on blog hosted by a third party, like Wordpress.com?
Update
Unfortunately, both the JavaScript solution and the HTML meta tag approach does not work on hosted Wordpress.com blogs, since they don't allow JavaScript in posts and they don't provide access to edit the HTML meta tags directly.
A: You can build that portion of the content dynamically using Javascript.
For example:
<html>
<body>
<div id="dynContent">
</div>
Rest of the content here.
</body>
<script language='javascript' type='text/javascript'>
var dyn = document.getElementById('dynContent');
dyn.innerHTML = "Put the dynamic content here";
</script>
</html>
If you're really stuck, you can just go old school and reference an image that has your text as part of it. It's not particularly "accessibility-friendly" though.
A: Javascript. If you add your content to the site using javascript, it won't be picked up by the search engines. It's even appropriate, because you're enhancing the site, not providing additional content. Any other method of performing this will stick the content into the page. Even if you hide it using styling, it will still be in the text. Depending on your page structure, that might not be possible anyway.
A: If you can use an iframe, then place the content on a static html page and use the meta tag in it's head to tell the search engines to ignore it. Since it's a seperate page, google etc.. should ignore it.
meta tag:
<meta name="robots" content="noindex, nofollow">
A: You can try to improve the text that's shown on the search results page by providing a meta description tag. However, It's the search engine's prerogative to display whatever it chooses, which is not necessarily the first 'n' words on the page.
A: I just came to think of something. I guess I could render the note with JavaScript once the page is loaded?
A: Hmm... maybe you can create a <div> with position: absolute; z-index: 99 (should be greater than 1); top: 0px; -- this should put the note at the top of the page but you could place the actual code near the bottom... search engines go linearly through the source and not by position I'd assume.
Edit: And this is fail if you decide you want it located somewhere else since this is an absolute location-- it'll just break down.. :\. go with the javascript
A: Any attempt to hide content is going to have side-effects regarding accessibility and compatibility. It seems that all you are attempting to do is control the snippet that search engines display, in which case you are better off providing an appropriate meta element description.
A: I'm familiar with how WordPress.com works, but if you can put in stuff like Digg, Delicious badges on your blog as a third part added stuff.. then you might have a chance to do the same trick these badges uses, they inject dynamic content in your page , and you can figure how they are doing it and do the same with your custom content
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: iterating over Enum constants in JSP I have an Enum like this
package com.example;
public enum CoverageEnum {
COUNTRY,
REGIONAL,
COUNTY
}
I would like to iterate over these constants in JSP without using scriptlet code. I know I can do it with scriptlet code like this:
<c:forEach var="type" items="<%= com.example.CoverageEnum.values() %>">
${type}
</c:forEach>
But can I achieve the same thing without scriptlets?
Cheers,
Don
A: If you're using Spring MVC, you can accomplish your goal with the following syntactic blessing:
<form:form method="post" modelAttribute="cluster" cssClass="form" enctype="multipart/form-data">
<form:label path="clusterType">Cluster Type
<form:errors path="clusterType" cssClass="error" />
</form:label>
<form:select items="${clusterTypes}" var="type" path="clusterType"/>
</form:form>
where your model attribute (ie, bean/data entity to populate) is named cluster and you have already populated the model with an enum array of values named clusterTypes. The <form:error> part is very much optional.
In Spring MVC land, you can also auto-populate clusterTypes into your model like this
@ModelAttribute("clusterTypes")
public MyClusterType[] populateClusterTypes() {
return MyClusterType.values();
}
A: If you are using Tag Libraries you could encapsulate the code within an EL function. So the opening tag would become:
<c:forEach var="type" items="${myprefix:getValues()}">
EDIT: In response to discussion about an implementation that would work for multiple Enum types just sketched out this:
public static <T extends Enum<T>> Enum<T>[] getValues(Class<T> klass) {
try {
Method m = klass.getMethod("values", null);
Object obj = m.invoke(null, null);
return (Enum<T>[])obj;
} catch(Exception ex) {
//shouldn't happen...
return null;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Database structure to track change history I'm working on database designs for a project management system as personal project and I've hit a snag.
I want to implement a ticket system and I want the tickets to look like the tickets in Trac. What structure would I use to replicate this system? (I have not had any success installing trac on any of my systems so I really can't see what it's doing)
Note: I'm not interesting in trying to store or display the ticket at any version. I would only need a history of changes. I don't want to store extra data. Also, I have implemented a feature like this using a serialized array in a text field. I do not want to implement that as a solution ever again.
Edit: I'm looking only for database structures. Triggers/Callbacks are not really a problem.
A: Are you after a database mechanism like this?
CREATE OR REPLACE TRIGGER history$yourTable
BEFORE UPDATE ON yourTable
FOR EACH ROW
BEGIN
INSERT INTO
history
VALUES
(
:old.field1,
:old.field2,
:old.field3,
:old.field4,
:old.field5,
:old.field6
);
END;
/
SHOW ERRORS TRIGGER history$yourTable
A: I did something like this. I have a table called LoggableEntity that contains: ID (PK).
Then I have EntityLog table that contains information about changes made to a loggableentity (record): ID (PK), EntityID (FK to LoggableEntity.ID), ChangedBy (username who made a change), ChangedAt (smalldatetime when the change happened), Type (enum: Create, Delete, Update), Details (memo field containing what has changed - might be an XML with serialized details).
Now every table (entity) that I want to be tracked is "derived" from the LoggableEntity table - what it means that for example Customer has FK to LoggableEntity table.
Now my DAL code takes care of populating EntityLog table everytime there is a change made to a customer record. Everytime when it sees that entity class is a loggableentity then it adds new change record into entitylog table.
So here is my table structure:
┌──────────────────┐ ┌──────────────────┐
│ LoggableEntity │ │ EntityLog │
│ ──────────────── │ │ ──────────────── │
│ (PK) ID │ ◀──┐ │ (PK) ID │
└──────────────────┘ └───── │ (FK) LoggableID │
▲ │ ... │
│ └──────────────────┘
┌──────────────────┐
│ Customer │
│ ──────────────── │
│ (PK) ID │
│ (FK) LoggableID │
│ ... │
└──────────────────┘
A: As far as not storing a lot of extra data, I can't think of any good ways to do that. You have to store every revision in order to see changes.
Here is one solution I have seen, although I'm not sure if it's the best one. Have a primary key, say id which points to a particular revision. also have ticket_number and revision_date fields. ticket_number does not change when you revise a ticket, but id and revision_date do. Then, depending on the context, you can get a particular revision, or the latest revision of a particular ticket, using groupwise max.
A: I have implemented pure record change data using a "thin" design:
RecordID Table Column OldValue NewValue
-------- ----- ------ -------- --------
You may not want to use "Table" and "Column", but rather "Object" and "Property", and so forth, depending on your design.
This has the advantage of flexibility and simplicity, at the cost of query speed -- clustered indexes on the "Table" and "Column" columns can speed up queries and filters. But if you are going to be viewing the change log online frequently at a Table or object level, you may want to design something flatter.
EDIT: several people have rightly pointed out that with this solution you could not pull together a change set. I forgot this in the table above -- the implementation I worked with also had a "Transaction" table with a datetime, user and other info, and a "TransactionID" column, so the design would look like this:
CHANGE LOG TABLE:
RecordID Table Column OldValue NewValue TransactionID
-------- ----- ------ -------- -------- -------------
TRANSACTION LOG TABLE:
TransactionID UserID TransactionDate
------------- ------ ---------------
A: I'd say create some kind of event listening class that you ping every time something happens within your system & places a description of the event in a database.
It should store basic who/what/where/when/what info.
sorting through that project-events table should get you the info you want.
A: One possible solution is storing a copy of the ticket in a history table with the user that made the change.
However, this will store alot of extra data and require alot of processing to create the view that Trac shows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: RoR: Accessing models from with application.rb i am working on a simple web app which has a user model and role model (among others), and an admin section that contains many controllers. i would like to use a before_filter to check that the user of the user in the session has a 'can_access_admin' flag.
i have this code in the application.rb:
def check_role
@user = session[:user]
if @user.role.can_access_admin.nil? || !@user.role.can_access_admin
render :text => "your current role does not allow access to the administration area."
return
end
end
and then i have this code inside one of the admin controllers:
class Admin::BlogsController < ApplicationController
before_filter :check_role
def list
@blogList = Blog.find(:all)
end
end
and when i try to view the list action i get this error:
undefined method 'role' for user...
anyone know what i have to do to get the role association to be recognized in the application.rb? (note that the associations are configured correctly and the @user.role is working fine everywhere else i've tried to use it)
A: just a guess but it seems that your session[:user] is just storing the id, you need to do:
@user = User.find(session[:user])
or something along those lines to fetch the user from the database (along with its associations).
It's good to do the above in a before filter too.
A: Is session[:user] holding the user? or the user_id? You may need a lookup before you call .role.
A: Also, if you're using ActsAsAuthenticated or RestfulAuthentication or their brethren you can also use the current_user method they supply.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I access PostData from WebBrowser.Navigating event handler? I've got a windows form in Visual Studio 2008 using .NET 3.5 which has a WebBrowser control on it. I need to analyse the form's PostData in the Navigating event handler before the request is sent. Is there a way to get to it?
The old win32 browser control had a Before_Navigate event which had PostData as one of its arguments. Not so with the new .NET WebBrowser control.
A: C# version
/// <summary>
/// Fires before navigation occurs in the given object (on either a window or frameset element).
/// </summary>
/// <param name="pDisp">Object that evaluates to the top level or frame WebBrowser object corresponding to the navigation.</param>
/// <param name="url">String expression that evaluates to the URL to which the browser is navigating.</param>
/// <param name="Flags">Reserved. Set to zero.</param>
/// <param name="TargetFrameName">String expression that evaluates to the name of the frame in which the resource will be displayed, or Null if no named frame is targeted for the resource.</param>
/// <param name="PostData">Data to send to the server if the HTTP POST transaction is being used.</param>
/// <param name="Headers">Value that specifies the additional HTTP headers to send to the server (HTTP URLs only). The headers can specify such things as the action required of the server, the type of data being passed to the server, or a status code.</param>
/// <param name="Cancel">Boolean value that the container can set to True to cancel the navigation operation, or to False to allow it to proceed.</param>
private delegate void BeforeNavigate2(object pDisp, ref dynamic url, ref dynamic Flags, ref dynamic TargetFrameName, ref dynamic PostData, ref dynamic Headers, ref bool Cancel);
private void Form1_Load(object sender, EventArgs e)
{
dynamic d = webBrowser1.ActiveXInstance;
d.BeforeNavigate2 += new BeforeNavigate2((object pDisp,
ref dynamic url,
ref dynamic Flags,
ref dynamic TargetFrameName,
ref dynamic PostData,
ref dynamic Headers,
ref bool Cancel) => {
// Do something with PostData
});
}
C# WPF version
Keep the above, but replace:
dynamic d = webBrowser1.ActiveXInstance;
with:
using System.Reflection;
...
PropertyInfo prop = typeof(System.Windows.Controls.WebBrowser).GetProperty("ActiveXInstance", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo getter = prop.GetGetMethod(true);
dynamic d = getter.Invoke(webBrowser1, null);
A: That functionality isn't exposed by the .NET WebBrowser control. Fortunately, that control is mostly a wrapper around the 'old' control. This means you can subscribe to the BeforeNavigate2 event you know and love(?) using something like the following (after adding a reference to SHDocVw to your project):
Dim ie = DirectCast(WebBrowser1.ActiveXInstance, SHDocVw.InternetExplorer)
AddHandler ie.BeforeNavigate2, AddressOf WebBrowser_BeforeNavigate2
...and do whatever you want to the PostData inside that event:
Private Sub WebBrowser_BeforeNavigate2(ByVal pDisp As Object, ByRef URL As Object, _
ByRef Flags As Object, ByRef TargetFrameName As Object, _
ByRef PostData As Object, ByRef Headers As Object, ByRef Cancel As Boolean)
Dim PostDataText = System.Text.Encoding.ASCII.GetString(PostData)
End Sub
One important caveat: the documentation for the WebBrowser.ActiveXInstance property states that "This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.". In other words: your use of the property may break your app at any point in the future, for example when the Framework people decide to implement their own browser component, instead of wrapping the existing SHDocVw COM one.
So, you'll not want to put this code in anything you ship to a lot of people and/or anything that should remain working for many Framework versions to come...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can I read raw (CF_HTML) clipboard data in a webpage or C#? If I drag and drop a selection of a webpage from Firefox to HTML-Kit, HTML-Kit asks me whether I want to paste as text or HTML. If I select "text," I get this:
Version:0.9
StartHTML:00000147
EndHTML:00000516
StartFragment:00000181
EndFragment:00000480
SourceURL:http://en.wikipedia.org/wiki/Herodotus
<html><body>
<!--StartFragment-->Additional details have been garnered from the <i><a href="http://en.wikipedia.org/wiki/Suda" title="Suda">Suda</a></i>, an 11th-century encyclopaedia of the <a href="http://en.wikipedia.org/wiki/Byzantium" title="Byzantium">Byzantium</a> which likely took its information from traditional accounts.<!--EndFragment-->
</body>
</html>
According to MSDN, this is "CF_HTML" formatted clipboard data. Is it the same on OS X and Linux systems?
Is there any way to access this kind of detailed information (as opposed to just the plain clip fragment) in a webpage-to-webpage drag and drop operation? What about to a C# WinForms desktop application?
A: For completeness, here is the P/Invoke Win32 API code to get RAW clipboard data
using System;
using System.Runtime.InteropServices;
using System.Text;
//--------------------------------------------------------------------------------
http://metadataconsulting.blogspot.com/2019/06/How-to-get-HTML-from-the-Windows-system-clipboard-directly-using-PInvoke-Win32-Native-methods-avoiding-bad-funny-characters.html
//--------------------------------------------------------------------------------
public class ClipboardHelper
{
#region Win32 Native PInvoke
[DllImport("User32.dll", SetLastError = true)]
private static extern uint RegisterClipboardFormat(string lpszFormat);
//or specifically - private static extern uint RegisterClipboardFormatA(string lpszFormat);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsClipboardFormatAvailable(uint format);
[DllImport("User32.dll", SetLastError = true)]
private static extern IntPtr GetClipboardData(uint uFormat);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenClipboard(IntPtr hWndNewOwner);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseClipboard();
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern IntPtr GlobalLock(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GlobalUnlock(IntPtr hMem);
[DllImport("Kernel32.dll", SetLastError = true)]
private static extern int GlobalSize(IntPtr hMem);
#endregion
public static string GetHTMLWin32Native()
{
string strHTMLUTF8 = string.Empty;
uint CF_HTML = RegisterClipboardFormatA("HTML Format");
if (CF_HTML != null || CF_HTML == 0)
return null;
if (!IsClipboardFormatAvailable(CF_HTML))
return null;
try
{
if (!OpenClipboard(IntPtr.Zero))
return null;
IntPtr handle = GetClipboardData(CF_HTML);
if (handle == IntPtr.Zero)
return null;
IntPtr pointer = IntPtr.Zero;
try
{
pointer = GlobalLock(handle);
if (pointer == IntPtr.Zero)
return null;
uint size = GlobalSize(handle);
byte[] buff = new byte[size];
Marshal.Copy(pointer, buff, 0, (int)size);
strHTMLUTF8 = System.Text.Encoding.UTF8.GetString(buff);
}
finally
{
if (pointer != IntPtr.Zero)
GlobalUnlock(handle);
}
}
finally
{
CloseClipboard();
}
return strHTMLUTF8;
}
}
A: It is Microsoft specific, don't expect to see the same information in other OSes.
Note that you get the same format when you copy a fragment from IE.
I am not sure what you mean by "webpage-to-webpage drag and drop operation". To drop where? A textarea?
I don't know C#, but in C/C++ applications, you have to use OpenClipboard and related Win32 APIs to get this info. In particular, GetClipboardData(CF_HTML) allows you to get this info (can be obtained in plain text too, for example, or Unicode data, etc.).
A: A WinForms app can use Clipboard.GetText to get it. I don't think there is a way to do it in a webpage, however.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Another JPA Question I have this code:
@PersistenceContext(name="persistence/monkey", unitName="deltaflow-pu")
...
@Stateless
public class GahBean implements GahRemote {
But when I use this:
try{
InitialContext ic = new InitialContext();
System.out.println("Pissing me off * " + ic.lookup("java:comp/env/persistent/monkey"));
Iterator e = ic.getEnvironment().values().iterator();
while ( e.hasNext() )
System.out.println("rem - " + e.next());
}catch(Exception a){ a.printStackTrace();}
I get this exception:
javax.naming.NameNotFoundException: No object bound to name java:comp/env/persistent/monkey
If I remove the lookup the iterator doesn't have anything close to it either. What could be the problem?
A: This could be my ignorance about JPA showing, but you appear to have "persistence" in some places and "persistent" in others. I'd start by making sure the names match.
A: If I inject it by the way it works fine, but everywhere I read about that they say it isn't threadsafe to do it that way.
A: Check whether you have configured the data source on the server with the name persistence/monkey and check whether the name is matched in persistance.xml
The name is case sensitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What constitutes effective Perl training for non-Perl developers? I've been working with Perl long enough that many of its idiosyncracies have become second nature to me. When new programmers join our group, they frequently have little to no experience with Perl, and it's usually my task to train them (to the extent necessary). I'd like to know what to focus on when training a programmer who is new to Perl but has experience with other languages (this question is meant to be language-agnostic, but most developers I've worked with have come from Java).
A few things occur to me:
*
*The proper use of sigils
*Referencing/Dereferencing
*Use of list functions like map,
grep, sort
Is there anything in particular that you've found it useful to focus on when helping a programmer to transition to Perl? Do you stress the similarities or the differences, or both in equal measure?
A: I'd start by telling them to always use the magical mantra:
use strict;
use warnings;
They don't need to know why (yet).
Next, I'd introduce them to perldoc and show them the basics of using it (the -f and -q flags, perldoc perl and perldoc perltoc, etc.) They need to know where to look when they have questions.
I'd talk about scalar vs. list context.
I'd introduce them to the basic data types (scalars, arrays, and hashes) and how the sigils follow the context, not the data type!
Introduce $_ and @_. It's critical to understand $_ because it's used in so many places, often implicitly. @_ is essential to writing subroutines. The other punctuation variables are used far less often and can wait.
Introduce them to regular expressions and get them used to the idea of regexes being first-class objects in Perl.
I'd briefly show them Perl's "diagonal" syntax. Idioms like next unless /foo/ are wonderful once you get use them but seem very alien when coming from other languages, particularly "orthogonal" ones.
You don't need to talk about references right away. Let that wait until they're ready to do things that require data structures. Functions like map and grep can wait, too.
Build a solid foundation on the fundamentals. Let them take baby steps for a while, then mix in more advanced features and idioms.
A: The most important thing you can show them is how to access the documentation, and how to find it (perldoc perltoc, perldoc -q $keyword, perldoc -f $function etc).
Perl comes with great documentation, including reference and tutorial-style material. Making that accessible to the newcomer is the most effective thing you can do for them.
A: Another surprising aspect is context. The fact that functions or even variables behave differently depending on whether they're referenced in list or scalar (or void) context has been an important detail for Perl trainees.
I usually insist on "higher-level" built in functions (map, grep, splice, split). Because of TMTOWTDI, many programmers only remember the more familiar aspects of Perl (like the C-style loops, substr and index) and use exclusively those.
After they are familiar with the language, Intermediate Perl and Advanced Perl Programming can give them further insights into the world of Perl
A: Probably not exactly what you are looking for. Apologies in advance.
I would not point to similarities unless it is really necessary.
Perl works in its own world. You could program Perl in Java style if you like, but what's the point?
The most important lesson I've learned from Perl (and my Perl tutors) is "There Is More Than One Way To Do It". So I think the best way of learning Perl is embracing its attitude to programming and supporting each programmer as he or she finds his or her way.
The examples you are making, list functions etc., are things that come naturally with use -- you can only understand their power once you get the Perl "way of things".
Just my two cents.
A: Frankly, I'd just give them the Camel. It's such a readable and entertaining book, they'll be up and running in no time. I'm still laughing about 'Perl holds truth to be self-evident' and it must be ten years since I first read it.
A: I'm a java programmer who recently had to pick up Perl. The part I found hardest to get used to were all the special built in variables like $_ $~ $' and so on. Until you get used to them it's hard to keep track of which one does what.
And, of course, the use of regular expressions.
For example, I have to maintain code and when I saw the line below for the first time it was a little confusing. As a java programmer it looks like gibberish.
next unless "$_" !~ /^#/;
A: I can only add, that somebody coming from a less expressive languages might not understand hash expressions or hash and array slice expressions. Seems like every language has a PCRE library these days.
Oh, and to add to moritz idea, I tutored my co-workers on just that.
Plus, I included some instruction on Data::Dumper, Scalar::Util, List::Util and some very useful modules like that.
And why not for that matter, check out Damian's Perl Best Practices and snag a few of the more powerful suggestions.
A: I'd go for the variety of quoting operators (from perlop):
Customary Generic Meaning Interpolates
'' q{} Literal no
"" qq{} Literal yes
`` qx{} Command yes*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)
<<EOF here-doc yes*
* unless the delimiter is ''.
The list can be overwhelming (especially when you add in alternate delimiters), but extremely useful. It also helps when reading code since few (if any!) languages have the variety of quotes that Perl has.
A: Check out the tables of contents for my books. Both Learning Perl and Intermediate Perl are designed to teach programmers the Perl language. We cover the 80% of Perl that most people use all of the time and developed that from years and years of teaching people Perl. Each book is designed as a tutorial, and there are exercises at the end of each chapter. I've also written the Learning Perl Student Workbook to provide additional exercises. Programming Perl is a good reference, too.
There are actually very few rules that you need to know to "get" Perl, and most people don't get these rules right just by looking at code. Some things to teach new Perlers who are coming from another language:
*
*strict and warnings
*Scalar versus list context
*dynamic versus lexical scope
*The sigil is not the variable type
*List creation and manipulation (map, grep, sort)
*How to use CPAN effectively
*Closures and subroutines as data
*Recursion in Perl sucks
Good luck :)
A: This is a single detail, not a full answer to your question, but for me, the mark of someone who's truly become oriented to Perl is someone who replaces this idiom:
for (my $i = 0; $i < @a; $i++)
{
&do_something_with($array[$i]);
}
with this idiom:
foreach my $a (@array)
{
&do_something_with($a);
}
Teach them lists as lists, not just as arrays. Teach the awesome data structures. Teach lists, hashes, lists of hashes, hashes of lists, hashes of hashes. That's where the biggest step up in power comes in over most conventional strongly-typed languages. (Ironically in the Java shop I joined this year, we sling around tons of arbitarily deep nested HashMap structures. Too many, in fact; I'm the one arguing for doing a bit less of it! But in Perl, this sort of thing is vital.)
A: Just joking, but whatever you do, show things like this LAST! ;)
use integer;@A=split//,<>;sub R{for$i(0..80){next if$A[$i];my%t=map{$_/9
==$i/9||$_%9==$i%9||$_/27==$i/27&&$_%9/3==$i%9/3?$A[$_]:0=>1}0..80;R($A[
$i]=$_)for grep{!$t{$_}}1..9;return$A[$i]=0}die@A}R
A: as others said:
use strict;
use warnings;
maybe
use diagnostics;
for Java programmers:
use autodie; #or Fatal
English.pm
Moose/Mouse
Perl::Critic
perltidy
A: I think that the "killer app" of Perl is CPAN…
Typical quotes after browsing CPAN for the first time:
"You have a library for WHAT?"
"Extirpate HTML has to be the best function name ever!"
"You can summarize text in Perl?"
Once the programmers see how easy is to do hard things, they are sold.
Then you can show them perldoc and the Camel.
A: I own and manage Perl Training Australia. I've been teaching Perl for about eight years, and computer science for over a decade. I have strong opinions on not only Perl, but also on teaching, and presenting in general. I've written hundreds of pages of text about Perl -- which I won't be repeating here -- so what I'm going to give you isn't advice on teaching Perl; it's meta-advice instead.
Firstly, if your time and budget allows, consider sending your staff member on a professional Perl training course. Dedicated courses have the advantage that they don't come with work interruptions, they don't come with workplace politics, and they do come with someone who's very familiar with the difficulties people have when learning Perl. Please make sure you have a trainer who knows their stuff and is an active member of the Perl community; it means they should be able to answer any question thrown at them, or direct the questioner to an appropriate reference where they can learn more. Yes, I run a Perl training business, so I'm heavily opinionated here.
If for whatever reason you can't go with a dedicated course, then get a book that's specifically designed to teach people how to program in Perl, and walk through that. It's easy to miss things, or to try and introduce things in the wrong order, or (heaven forbid) teach bad habits, and all of those can make your life difficult. Often the people writing books designed to teach Perl are the same people who have successful Perl training businesses. If you want to buy a book, I'd recommend the latest version of Learning Perl. If you want to download a book, I'd recommend grabbing the Programming Perl course notes from the Perl Training Australia website.
Both of these books come with exercises, and this brings me to my last piece of meta-advice. Make sure anyone who is learning Perl does the exercises. It's very easy when learning any new skill to think you know what's going on, but discover that when putting things into practice it's harder than it looks. This is particularly the case with Perl, where programming concepts like "context" can apply, which are rare in other languages. Usually the exercises are specifically designed to teach a certain skill, or to highlight a certain pitfall; figuring these things out during learning is much easier than figuring them out on the eve of a project deadline.
A: I was just hired into this exact scenario. I am a C++ and Java developer and had never touched Perl until my current job. The things that took some time to get used too were the idiosyncratic Perl syntax choices [$_], $this = that unless ... , and seeing the forest for the trees (anything containing /^#+\d/ elements). Other things were just a result of the programming house I work in [confusing OO statements, $self, and putting 1; at the end of module files].
Now that I have been here a while, I see the elements of style that Perl has given me even in my non-work projects. You approach tasks, especially data massaging, differently and it feels like a real solid tool in my toolbox.
All that being said, I was handed a codebase of around 35,000 lines, the camel book and told I could not use CPAN. It has been a productive six months. ^^
A: Programming Perl (coauthored by #22483 - good work Randal, i've had mine for near on 10 years) was a great intro to Perl. Starting with regex, slicing and dicing arrays, associative arrays etc. Plus the whys and hows of reporting in Perl and a function reference.
I'm not sure how much it's changed in it's third edition but i would base a course on it and use it as the text book. It's reasonably terse and to the point. Plus then your course matches your documentation.
A: Based on my experience in the workplace I'd recommend beginning with Perl's documentation (already covered here) and spend some time showing the student how to test code on the command line. It's really surprising how quickly someone can pick up a language when they can try something on the fly and make corrections until they get it right.
A: For C++/Java/C# coders two differences I stress very strongly up-front are that:
No 1: In Perl almost everything has a meaning, just not always what you want. Good examples include:
*
*Variable names without sigils don't stop execution - they are interpreted as barewords
*Try to store an array in a scalar and you get the length
*Try to store a hash in a scalar and you get 'a/b' (buckets in use vs total buckets?)
No 2: In Perl you can make it up as you go along. In other works you can say "in the hash 'w' the key 'x' indexes an anonymous array where box 'y' holds 'z'" and the interpreter will create and size all the variables for you as you go.
A: Ok. Sure you need to use strict at some point. And sure you want to use libraries at some point. But strict is just the basic start-the-file-magic for Perl, and each language has libraries. I don't think those are the things which are very important to learn when starting out.
When you start out in Perl, but already know other languages, you need to know crazy idiosyncracies, like $a and $b being special vars, being able to index using -1, etc.
In retrospect, I really like how I learned Perl: By playing Perl Golf.
By using a language to such an extreme, you force yourself to find out all the crazy bits of it, and you really need to understand the different constructs. Especially if you are doing this with a group of friend/colleagues/... this works really well.
(of course this should not be the only training ;) but I really believe it works very well at some point)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: What limitations have closures in Python compared to language X closures? Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures.
Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more.
Seeing a code example for a concrete limitation would be great.
Related questions:
*
*Can you explain closures (as they relate to Python)?
*What is a ‘Closure’?
*How does a javascript closure work ?
A: The only difficulty I've seen people encounter with Python's in particular is when they try to mix non-functional features like variable reassignment with closures, and are surprised when this doesn't work:
def outer ():
x = 1
def inner ():
print x
x = 2
return inner
outer () ()
Usually just pointing out that a function has its own local variables is enough to deter such silliness.
A: A limitation (or "limitation") of Python closures, comparing to Javascript closures, is that it cannot be used for effective data hiding
Javascript
var mksecretmaker = function(){
var secrets = [];
var mksecret = function() {
secrets.push(Math.random())
}
return mksecret
}
var secretmaker = mksecretmaker();
secretmaker(); secretmaker()
// privately generated secret number list
// is practically inaccessible
Python
import random
def mksecretmaker():
secrets = []
def mksecret():
secrets.append(random.random())
return mksecret
secretmaker = mksecretmaker()
secretmaker(); secretmaker()
# "secrets" are easily accessible,
# it's difficult to hide something in Python:
secretmaker.__closure__[0].cell_contents # -> e.g. [0.680752847190161, 0.9068475951742101]
A: Fixed in Python 3 via the nonlocal statement:
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
A: The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only:
>>> def outer(x):
... def inner_reads():
... # Will return outer's 'x'.
... return x
... def inner_writes(y):
... # Will assign to a local 'x', not the outer 'x'
... x = y
... def inner_error(y):
... # Will produce an error: 'x' is local because of the assignment,
... # but we use it before it is assigned to.
... tmp = x
... x = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
5
>>> inner_error(10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in inner_error
UnboundLocalError: local variable 'x' referenced before assignment
A name that gets assigned to in a local scope (a function) is always local, unless declared otherwise. While there is the 'global' declaration to declare a variable global even when it is assigned to, there is no such declaration for enclosed variables -- yet. In Python 3.0, there is (will be) the 'nonlocal' declaration that does just that.
You can work around this limitation in the mean time by using a mutable container type:
>>> def outer(x):
... x = [x]
... def inner_reads():
... # Will return outer's x's first (and only) element.
... return x[0]
... def inner_writes(y):
... # Will look up outer's x, then mutate it.
... x[0] = y
... def inner_error(y):
... # Will now work, because 'x' is not assigned to, just referenced.
... tmp = x[0]
... x[0] = y
... return tmp
... return inner_reads, inner_writes, inner_error
...
>>> inner_reads, inner_writes, inner_error = outer(5)
>>> inner_reads()
5
>>> inner_writes(10)
>>> inner_reads()
10
>>> inner_error(15)
10
>>> inner_reads()
15
A: @John Millikin
def outer():
x = 1 # local to `outer()`
def inner():
x = 2 # local to `inner()`
print(x)
x = 3
return x
def inner2():
nonlocal x
print(x) # local to `outer()`
x = 4 # change `x`, it is not local to `inner2()`
return x
x = 5 # local to `outer()`
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 5 4
A: comment for @Kevin Little's answer to include the code example
nonlocal does not solve completely this problem on python3.0:
x = 0 # global x
def outer():
x = 1 # local to `outer`
def inner():
global x
x = 2 # change global
print(x)
x = 3 # change global
return x
def inner2():
## nonlocal x # can't use `nonlocal` here
print(x) # prints global
## x = 4 # can't change `x` here
return x
x = 5
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 3 3
On the other hand:
x = 0
def outer():
x = 1 # local to `outer`
def inner():
## global x
x = 2
print(x) # local to `inner`
x = 3
return x
def inner2():
nonlocal x
print(x)
x = 4 # local to `outer`
return x
x = 5
return (inner, inner2)
for inner in outer():
print(inner())
# -> 2 3 5 4
it works on python3.1-3.3
A: The better workaround until 3.0 is to include the variable as a defaulted parameter in the enclosed function definition:
def f()
x = 5
def g(y, z, x=x):
x = x + 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "48"
}
|
Q: Socket programming for mobile phones in Python I've written code for communication between my phone and comp thru TCP sockets. When I type out the code line by line in the interactive console it works fine. However, when i try running the script directly through filebrowser.py it just wont work. I'm using Nokia N95. Is there anyway I can run this script directly without using filebrowser.py?
A: Have you read Hack a Mobile Phone with Linux and Python? It is rather old, but maybe you find it helpful.
A: If the code is working in the interactive interpreter when typed, but not when run directly then I would suggest seeing if your code has reached a deadlock on the socket, for example both ends are waiting for data from the other. When typing into the interactive interpreter there is a longer delay between the execution of each line on code.
A: Well, it doesn't appear to be a deadlock situation. It throws an error saying remote server refused connection. However, like I said before, if i type the very same code into the interactive interpreter it works just fine. I'm wondering if the error is because the script is run through filebrowser.py?
A: Don't you have the "Run script" menu in your interactive Python shell?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do you make a generic memoize function in Haskell? I've seen the other post about this, but is there a clean way of doing this in Haskell?
As a 2nd part, can it also be done without making the function monadic?
A: This largely follows http://www.haskell.org/haskellwiki/Memoization.
You want a function of type (a -> b). If it doesn't call itself, then
you can just write a simple wrapper that caches the return values. The
best way to store this mapping depends on what properties of a you can
exploit. Ordering is pretty much a minimum. With integers
you can construct an infinite lazy list or tree holding the values.
type Cacher a b = (a -> b) -> a -> b
positive_list_cacher :: Cacher Int b
positive_list_cacher f n = (map f [0..]) !! n
or
integer_list_cacher :: Cacher Int b
integer_list_cacher f n = (map f (interleave [0..] [-1, -2, ..]) !!
index n where
index n | n < 0 = 2*abs(n) - 1
index n | n >= 0 = 2 * n
So, suppose it is recursive. Then you need it to call not itself, but
the memoized version, so you pass that in instead:
f_with_memo :: (a -> b) -> a -> b
f_with_memo memoed base = base_answer
f_with_memo memoed arg = calc (memoed (simpler arg))
The memoized version is, of course, what we're trying to define.
But we can start by creating a function that caches its inputs:
We could construct one level by passing in a function that creates a
structure that caches values. Except we need to create the version of f
that already has the cached function passed in.
Thanks to laziness, this is no problem:
memoize cacher f = cached where
cached = cacher (f cached)
then all we need is to use it:
exposed_f = memoize cacher_for_f f
The article gives hints as to how to use a type class selecting on the
input to the function to do the above, rather than choosing an explicit
caching function. This can be really nice -- rather than explicitly
constructing a cache for each combination of input types, we can implicitly
combine caches for types a and b into a cache for a function taking a and b.
One final caveat: using this lazy technique means the cache never shrinks,
it only grows. If you instead use the IO monad, you can manage this, but
doing it wisely depends on usage patterns.
A: Doing a direct translation from the more imperative languages, I came up with this.
memoize :: Ord a => (a -> IO b) -> IO (a -> IO b)
memoize f =
do r <- newIORef Map.empty
return $ \x -> do m <- readIORef r
case Map.lookup x m of
Just y -> return y
Nothing -> do y <- f x
writeIORef r (Map.insert x y m)
return y
But this is somehow unsatisfactory. Also, Data.Map constrains the parameter to be an instance of Ord.
A: The package data-memocombinators on hackage provides lots of reusable memoization routines. The basic idea is:
type Memo a = forall r. (a -> r) -> (a -> r)
I.e. it can memoize any function from a. The module then provides some primitives (like unit :: Memo () and integral :: Memo Int), and combinators for building more complex memo tables (like pair :: Memo a -> Memo b -> Memo (a,b) and list :: Memo a -> Memo [a]).
A: You can modify Jonathan´s solution with unsafePerformIO to create a "pure" memoizing version of your function.
import qualified Data.Map as Map
import Data.IORef
import System.IO.Unsafe
memoize :: Ord a => (a -> b) -> (a -> b)
memoize f = unsafePerformIO $ do
r <- newIORef Map.empty
return $ \ x -> unsafePerformIO $ do
m <- readIORef r
case Map.lookup x m of
Just y -> return y
Nothing -> do
let y = f x
writeIORef r (Map.insert x y m)
return y
This will work with recursive functions:
fib :: Int -> Integer
fib 0 = 1
fib 1 = 1
fib n = fib_memo (n-1) + fib_memo (n-2)
fib_memo :: Int -> Integer
fib_memo = memoize fib
Altough this example is a function with one integer parameter, the type of memoize tells us that it can be used with any function that takes a comparable type. If you have a function with more than one parameter just group them in a tuple before applying memoize. F.i.:
f :: String -> [Int] -> Float
f ...
f_memo = curry (memoize (uncurry f))
A: If your arguments are going to be natural numbers, you can do simply:
memo f = let values = map f [0..]
in \n -> values !! n
However, that doesn't really help you with the stack overflowing, and it doesn't work with recursive calls. You can see some fancier solutions at http://www.haskell.org/haskellwiki/Memoization.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Viewing the Visual SourceSafe log inside Visual Studio Is there any way to view the activity log for the integrate SourceSafe inside Visual Studio 2005 Pro? I'd like to be able to quickly see the results of any Get Latest Version, Check In and Checkout actions, and I can't find a way to get that information without having to open the VSS client.
A: The output window (View - Output) echoes a lot. If it isn't verbose enough though I don't know how one would configure that.
A: That's what I was missing - I never saw the [Source Control] option for the "Show output from:" setting in the Output window. Great, thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Polyglot Programming: Is building applications with multiple languages a good practice? I am considering building an application that is a blend of a dynamic language (python or ruby) and compiled language and need some help getting convincing myself that this is a good idea.
My thought are that I can use a dynamic language to get a lot of code written quickly, and then dropping down to a compiled language like c/c++ to implement performance critical code.
I can see a lot of benefits of this approach:
*
*Increased Productivity by primarily coding in the dynamic language
*Availability of libraries from both languages
But there are also some downsides:
*
*Maintaining a bridge between the two languages
*Dependency on two languages and language/library bugs instead of one
What are the other pros/cons of this approach? Does anybody know about any resources and/or best practices around this?
A: I just re-read your question - your proposal to use C for performance critical code. Any dynamic language worth its salt has tools to let you access native code efficiently. So start by writing the whole thing in the dynamic language. You may find you don't need C after all.
But if you do, break out a profiler, carefully choose something to optimise, and go for it.
A: Ja, bien sur, mein freund. It is un'idea meravigliosa indeed. Boa sorte.
I'm joking of course. A web developer does that everyday without even noticing: Java, JSP, EL/OGNL, HTML, CSS, Javascript, ant, XML, XSLT...
I think polyglot programming is natural, powerful, efficient and more than else cool. It has to be used in the right way of course, to tap the maximum power of every language, and to not confuse the other people in your team.
A: Yes. Many programs are a mixture of a high-level language, like Python or Ruby, and a low-level language like C. You get the benefits of coding logic in a garbage-collected OO language and can still manually manage registers within tight inner loops.
A: You may find that you do not need to implement any performance critical stuff until a later time. So, I would fight hard against the entrance of one of these performance critical major changes until you are really sure you need to do it.
Otherwise just pick a root language, perl and ruby use c, so their incorporation is pretty simple. You could also run python (jython) or ruby (jrunby) on a Java VM, which would give you java as a backend. Though it might provide some other problems, as I am not familiar with developing against those versions of the respective languages.
not all performance problems will require you to drop down to a low level language though, so try and tackle it first in one langugae, before you quickly jump to another.
Good luck,
A: I'm in favor of using the best tool for the job. In the case of software engineering that means being polyglot. You would never expect a carpenter to use only a hammer, no matter what he/she were building. Why should it be different for us?
A: @Zorkerman
I have experience with both Jython and JRuby... a lot more with JRuby.
I must say they are great platforms, and you get the huge benefit of dynamic languages, PLUS the rich 3rd and 1st party library support of Java, PLUS a highly platform independent base compiled language, PLUS garbage collection in both languages (it's important to understand memory management, but I'm of the camp that you are better off avoiding it unless you REALLY need it, such as if you are doing drivers or kernel level stuff, or stuff that need every ounce of performance you can muster).
I just want to give a quick anecdote. I recently was building a ruby script to index a Solr instance, and I needed to access a DB2 database (the source of our data to be indexed). Straight Ruby failed miserably... it has horrible DB2 support, which requires a full install of DB2 express edition... which still didn't work as advertised (I couldn't compile the Ruby drivers after I had finished installation). The solution was to just switch to JRuby and use JDBC from the Ruby side, using a couple easy to install jars (and much much MUCH smaller files than the DB2 install).
I would definitely highly advise considering JRuby or Jython instead of using C as your back end... I've found that algorithm and resource performance usually have a much much bigger impact on application performance than the language you pick, and the Java platform has so much to offer (and it has come a long way since the early days when people were decrying it as vastly slower than C/C++). Unless you are doing very heavy calculation intensive things that can't be refactored algorithmically, you most likely won't need to drop down to the compiled language, regardless of your pick.
PS The integration with Java in JRuby is very seamless (from the JRuby to Java side anyways), so maintaining a bridge is not an issue. Jython I think is the same, but again my experience with it is a lot less.
A: It's worth noting that Gambit Scheme and Chicken (and a few other implementations for that matter) run in an interpreted mode, and can then be compiled down to C.
A: I think your approach is very sensible. The way to address the downsides is to find out ahead of time how easy it is to interface the dynamic language with C or C++ before deciding whether or not to use it for your project.
Also, you need to think about whether or not you want your application to be cross-platform. A dynamic language is likely to be much less platform dependent, than a compiled one. That may be a factor in deciding which parts of the app should be done in C or C++.
A: I think this is a good idea.
Since most (nearly all?) OSes are written in C or C++, every dynamic or interpreted language is at some level falling back to a compiled, optimized language for low level stuff.
A: Some folks argue that we programmers must master too many languages. They argue that adding a language is A Bad Thing.
The whole data access in SQL, presentation in HTML/CSS seems to be irreversible.
The XML thing is a bit tiresome: some people try to do everything in XML, as if XML has magical powers to make software better.
Also, there's a fair amount of redundancy because of the multiple languages. All of the inter-language bindings means that things get written twice, once in each language.
A: It's quite common, but make sure you know why you're architecting it the way you do.
One example is in games programming. In many games, the performance-critical game engine is written in C, while things like level scripting are done in Python, Scheme, a home-grown language or whatever.
This means the performance geeks are working in a language they like and which gives them the low level control they need, while the level designers can work in a higher level language where they don't need to worry about managing memory and so forth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How do I find a default constraint using INFORMATION_SCHEMA? I'm trying to test if a given default constraint exists. I don't want to use the sysobjects table, but the more standard INFORMATION_SCHEMA.
I've used this to check for tables and primary key constraints before, but I don't see default constraints anywhere.
Are they not there? (I'm using MS SQL Server 2000).
EDIT: I'm looking to get by the name of the constraint.
A: You can use the following to narrow the results even more by specifying the Table Name and Column Name that the Default Constraint correlates to:
select * from sysobjects o
inner join syscolumns c
on o.id = c.cdefault
inner join sysobjects t
on c.id = t.id
where o.xtype = 'D'
and c.name = 'Column_Name'
and t.name = 'Table_Name'
A: There seems to be no Default Constraint names in the Information_Schema views.
use SELECT * FROM sysobjects WHERE xtype = 'D' AND name = @name
to find a default constraint by name
A: select c.name, col.name from sys.default_constraints c
inner join sys.columns col on col.default_object_id = c.object_id
inner join sys.objects o on o.object_id = c.parent_object_id
inner join sys.schemas s on s.schema_id = o.schema_id
where s.name = @SchemaName and o.name = @TableName and col.name = @ColumnName
A: Is the COLUMN_DEFAULT column of INFORMATION_SCHEMA.COLUMNS what you are looking for?
A: Necromancing.
If you only need to check if a default-constraint exists
(default-constraint(s) may have different name in poorly-managed DBs),
use INFORMATION_SCHEMA.COLUMNS (column_default):
IF NOT EXISTS(
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE (1=1)
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_VWS_PdfBibliothek'
AND COLUMN_NAME = 'PB_Text'
AND COLUMN_DEFAULT IS NOT NULL
)
BEGIN
EXECUTE('ALTER TABLE dbo.T_VWS_PdfBibliothek
ADD CONSTRAINT DF_T_VWS_PdfBibliothek_PB_Text DEFAULT (N''image'') FOR PB_Text;
');
END
If you want to check by the constraint-name only:
-- Alternative way:
IF OBJECT_ID('DF_CONSTRAINT_NAME', 'D') IS NOT NULL
BEGIN
-- constraint exists, deal with it.
END
And last but not least, you can just create a view called INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS:
CREATE VIEW INFORMATION_SCHEMA.DEFAULT_CONSTRAINTS
AS
SELECT
DB_NAME() AS CONSTRAINT_CATALOG
,csch.name AS CONSTRAINT_SCHEMA
,dc.name AS CONSTRAINT_NAME
,DB_NAME() AS TABLE_CATALOG
,sch.name AS TABLE_SCHEMA
,syst.name AS TABLE_NAME
,sysc.name AS COLUMN_NAME
,COLUMNPROPERTY(sysc.object_id, sysc.name, 'ordinal') AS ORDINAL_POSITION
,dc.type_desc AS CONSTRAINT_TYPE
,dc.definition AS COLUMN_DEFAULT
-- ,dc.create_date
-- ,dc.modify_date
FROM sys.columns AS sysc -- 46918 / 3892 with inner joins + where
-- FROM sys.all_columns AS sysc -- 55429 / 3892 with inner joins + where
INNER JOIN sys.tables AS syst
ON syst.object_id = sysc.object_id
INNER JOIN sys.schemas AS sch
ON sch.schema_id = syst.schema_id
INNER JOIN sys.default_constraints AS dc
ON sysc.default_object_id = dc.object_id
INNER JOIN sys.schemas AS csch
ON csch.schema_id = dc.schema_id
WHERE (1=1)
AND dc.is_ms_shipped = 0
/*
WHERE (1=1)
AND sch.name = 'dbo'
AND syst.name = 'tablename'
AND sysc.name = 'columnname'
*/
A: As I understand it, default value constraints aren't part of the ISO standard, so they don't appear in INFORMATION_SCHEMA. INFORMATION_SCHEMA seems like the best choice for this kind of task because it is cross-platform, but if the information isn't available one should use the object catalog views (sys.*) instead of system table views, which are deprecated in SQL Server 2005 and later.
Below is pretty much the same as @user186476's answer. It returns the name of the default value constraint for a given column. (For non-SQL Server users, you need the name of the default in order to drop it, and if you don't name the default constraint yourself, SQL Server creates some crazy name like "DF_TableN_Colum_95AFE4B5". To make it easier to change your schema in the future, always explicitly name your constraints!)
-- returns name of a column's default value constraint
SELECT
default_constraints.name
FROM
sys.all_columns
INNER JOIN
sys.tables
ON all_columns.object_id = tables.object_id
INNER JOIN
sys.schemas
ON tables.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND tables.name = 'tablename'
AND all_columns.name = 'columnname'
A: The script below lists all the default constraints and the default values for the user tables in the database in which it is being run:
SELECT
b.name AS TABLE_NAME,
d.name AS COLUMN_NAME,
a.name AS CONSTRAINT_NAME,
c.text AS DEFAULT_VALUE
FROM sys.sysobjects a INNER JOIN
(SELECT name, id
FROM sys.sysobjects
WHERE xtype = 'U') b on (a.parent_obj = b.id)
INNER JOIN sys.syscomments c ON (a.id = c.id)
INNER JOIN sys.syscolumns d ON (d.cdefault = a.id)
WHERE a.xtype = 'D'
ORDER BY b.name, a.name
A: If you want to get a constraint by the column or table names, or you want to get all the constraints in the database, look to other answers. However, if you're just looking for exactly what the question asks, namely, to "test if a given default constraint exists ... by the name of the constraint", then there's a much easier way.
Here's a future-proof answer that doesn't use the sysobjects or other sys tables at all:
IF object_id('DF_CONSTRAINT_NAME', 'D') IS NOT NULL BEGIN
-- constraint exists, work with it.
END
A: WHILE EXISTS(
SELECT * FROM sys.all_columns
INNER JOIN sys.tables ST ON all_columns.object_id = ST.object_id
INNER JOIN sys.schemas ON ST.schema_id = schemas.schema_id
INNER JOIN sys.default_constraints ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND ST.name = 'MyTable'
)
BEGIN
DECLARE @SQL NVARCHAR(MAX) = N'';
SET @SQL = ( SELECT TOP 1
'ALTER TABLE ['+ schemas.name + '].[' + ST.name + '] DROP CONSTRAINT ' + default_constraints.name + ';'
FROM
sys.all_columns
INNER JOIN
sys.tables ST
ON all_columns.object_id = ST.object_id
INNER JOIN
sys.schemas
ON ST.schema_id = schemas.schema_id
INNER JOIN
sys.default_constraints
ON all_columns.default_object_id = default_constraints.object_id
WHERE
schemas.name = 'dbo'
AND ST.name = 'MyTable'
)
PRINT @SQL
EXECUTE sp_executesql @SQL
--End if Error
IF @@ERROR <> 0
BREAK
END
A: I don't think it's in the INFORMATION_SCHEMA - you'll probably have to use sysobjects or related deprecated tables/views.
You would think there would be a type for this in INFORMATION_SCHEMA.TABLE_CONSTRAINTS, but I don't see one.
A: Probably because on some of the other SQL DBMSs the "default constraint" is not really a constraint, you'll not find its name in "INFORMATION_SCHEMA.TABLE_CONSTRAINTS", so your best bet is "INFORMATION_SCHEMA.COLUMNS" as others have mentioned already.
(SQLServer-ignoramus here)
The only a reason I can think of when you have to know the "default constraint"'s name is if SQLServer doesn't support "ALTER TABLE xxx ALTER COLUMN yyy SET DEFAULT..." command. But then you are already in a non-standard zone and you have to use the product-specific ways to get what you need.
A: How about using a combination of CHECK_CONSTRAINTS and CONSTRAINT_COLUMN_USAGE:
select columns.table_name,columns.column_name,columns.column_default,checks.constraint_name
from information_schema.columns columns
inner join information_schema.constraint_column_usage usage on
columns.column_name = usage.column_name and columns.table_name = usage.table_name
inner join information_schema.check_constraints checks on usage.constraint_name = checks.constraint_name
where columns.column_default is not null
A: I am using folllowing script to retreive all defaults (sp_binddefaults) and all default constraint with following scripts:
SELECT
t.name AS TableName, c.name AS ColumnName, SC.COLUMN_DEFAULT AS DefaultValue, dc.name AS DefaultConstraintName
FROM
sys.all_columns c
JOIN sys.tables t ON c.object_id = t.object_id
JOIN sys.schemas s ON t.schema_id = s.schema_id
LEFT JOIN sys.default_constraints dc ON c.default_object_id = dc.object_id
LEFT JOIN INFORMATION_SCHEMA.COLUMNS SC ON (SC.TABLE_NAME = t.name AND SC.COLUMN_NAME = c.name)
WHERE
SC.COLUMN_DEFAULT IS NOT NULL
--WHERE t.name = '' and c.name = ''
A: Object Catalog View : sys.default_constraints
The information schema views INFORMATION_SCHEMA are ANSI-compliant, but the default constraints aren't a part of ISO standard. Microsoft SQL Server provides system catalog views for getting information about SQL Server object metadata.
sys.default_constraints system catalog view used to getting the information about default constraints.
SELECT so.object_id TableName,
ss.name AS TableSchema,
cc.name AS Name,
cc.object_id AS ObjectID,
sc.name AS ColumnName,
cc.parent_column_id AS ColumnID,
cc.definition AS Defination,
CONVERT(BIT,
CASE cc.is_system_named
WHEN 1
THEN 1
ELSE 0
END) AS IsSystemNamed,
cc.create_date AS CreationDate,
cc.modify_date AS LastModifiednDate
FROM sys.default_constraints cc WITH (NOLOCK)
INNER JOIN sys.objects so WITH (NOLOCK) ON so.object_id = cc.parent_object_id
LEFT JOIN sys.schemas ss WITH (NOLOCK) ON ss.schema_id = so.schema_id
LEFT JOIN sys.columns sc WITH (NOLOCK) ON sc.column_id = cc.parent_column_id
AND sc.object_id = cc.parent_object_id
ORDER BY so.name,
cc.name;
A: A bit of a cleaner way to do this:
SELECT DC.[name]
FROM [sys].[default_constraints] AS DC
WHERE DC.[parent_object_id] = OBJECT_ID('[Schema].[TableName]')
A: If the target database has, say, over 1M objects, using sys.default_constraints can hit you with 90%+ taken on scanning sys.syscolpars followed by a Key Lookup for the dflt you likely don't care about. On my DB, it takes 1.129s to assemble just 4 rows from the 158 read of the residual I/O impaired 1.12MM rows actually scanned.
Changing to using the current sys.% tables/views, using @Tim's query, the same 4 constraints are acquired in 2ms. Hope someone finds this as useful as I found Tim's:
SELECT ConstraintName = sdc.name
, SchemaName = ssch.name
, TableName = stab.name
, ColumnName = scol.name
FROM sys.objects sdc
INNER JOIN sys.columns scol
ON scol.default_object_id = sdc.object_id
INNER JOIN sys.objects stab
ON stab.object_id = scol.object_id
INNER JOIN sys.schemas ssch
ON ssch.schema_id = stab.schema_id;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "134"
}
|
Q: Adding a flash after authentication with merb-auth What's the best way to add a flash message, for successful or unsuccessful login when using the merb-auth slice (Other than overriding sessions create)?
A: Hey deimos. If you want to add an message without overwriting the create action you can always use an after filter. Something like
...........
after :set_login_flash, :only => [:create]
private
def set_login_flash
flash[:error] = "You're not logged in" unless logged_in?
end
..........
You'll need to tune it to use the appropriate flash system that you're using in your application but something like that should work for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java Web Deployment: build code, or deploy .war? Two main ways to deploy a J2EE/Java Web app (in a very simplistic sense):
Deploy assembled artifacts to production box
Here, we create the .war (or whatever) elsewhere, configure it for production (possibly creating numerous artifacts for numerous boxes) and place the resulting artifacts on the production servers.
*
*Pros: No dev tools on production boxes, can re-use artifacts from testing directly, staff doing deployment doesn't need knowledge of build process
*Cons: two processes for creating and deploying artifacts; potentially complex configuration of pre-built artifacts could make process hard to script/automate; have to version binary artifacts
Build the artifacts on the production box
Here, the same process used day-to-day to build and deploy locally on developer boxes is used to deploy to production.
*
*Pros: One process to maintain; and it's heavily tested/validated by frequent use. Potentially easier to customize configuration at artifact creation time rather than customize pre-built artifact afterword; no versioning of binary artifacts needed.
*Cons: Potentially complex development tools needed on all production boxes; deployment staff needs to understand build process; you aren't deploying what you tested
I've mostly used the second process, admittedly out of necessity (no time/priority for another deployment process). Personally I don't buy arguments like "the production box has to be clean of all compilers, etc.", but I can see the logic in deploying what you've tested (as opposed to building another artifact).
However, Java Enterprise applications are so sensitive to configuration, it feels like asking for trouble having two processes for configuring artifacts.
Thoughts?
Update
Here's a concrete example:
We use OSCache, and enable the disk cache. The configuration file must be inside the .war file and it references a file path. This path is different on every environment. The build process detects the user's configured location and ensures that the properties file placed in the war is correct for his environment.
If we were to use the build process for deployment, it would be a matter of creating the right configuration for the production environment (e.g. production.build.properties).
If we were to follow the "deploy assembled artifacts to the production box", we would need an additional process to extract the (incorrect) OSCache properties and replace it with one appropriate to the production environment.
This creates two processes to accomplish the same thing.
So, the questions are:
*
*Is this avoidable without "compiling on production"?
*If not, is this worth it? It the value of "no compiling on production" greater than "Don't Repeat Yourself"?
A: I'm firmly against building on the production box, because it means you're using a different build than you tested with. It also means every deployment machine has a different JAR/WAR file. If nothing else, do a unified build just so that when bug tracking you won't have to worry about inconsistencies between servers.
Also, you don't need to put the builds into version control if you can easily map between a build and the source that created it.
Where I work, our deployment process is as follows. (This is on Linux, with Tomcat.)
*
*Test changes and check into Subversion. (Not necessarily in that order; we don't require that committed code is tested. I'm the only full-time developer, so the SVN tree is essentially my development branch. Your mileage may vary.)
*Copy the JAR/WAR files to a production server in a shared directory named after the Subversion revision number. The web servers only have read access.
*The deployment directory contains relative symlinks to the files in the revision-named directories. That way, a directory listing will always show you what version of the source code produced the running version. When deploying, we update a log file which is little more than a directory listing. That makes roll-backs easy. (One gotcha, though; Tomcat checks for new WAR files by the modify date of the real file, not the symlink, so we have to touch the old file when rolling back.)
Our web servers unpack the WAR files onto a local directory. The approach is scalable, since the WAR files are on a single file server; we could have an unlimited number of web servers and only do a single deployment.
A: Most of the places I've worked have used the first method with environment specific configuration information deployed separately (and updated much more rarely) outside of the war/ear.
A: There exist configuration services, like heavy weight ZooKeeper, and most containers enable you to use JNDI to do some configuration. These will separate the configuration from the build, but can be overkill. However, they do exist. Much depends on your needs.
I've also used a process whereby the artifacts are built with placeholders for config values. When the WAR is deployed, it is exploded and the placeholders replaced with the appropriate values.
A: I highly recommend "Deploy assembled artifacts to production box" such as a war file. This is why our developers use the same build script (Ant in our case) to construct the war on their development sandbox, as is used to create the finally artifact. This way it is debugged as well as the code itself, not to mention completely repeatable.
A: I would champion the use of a continuous integration solution that supports distributed builds. Code checked into your SCM can trigger builds (for immediate testing) and you can schedule builds to create artifacts for QA. You can then promote these artifacts to production and have them deployed.
This is currently what I am working on setting up, using AnthillPro.
EDIT: We are now using Hudson. Highly recommend!
A: If you are asking this question relative to configuration management, then your answer needs to be based on what you consider to be a managed artifact. From a CM perspective, it is an unacceptable situation to have some collection of source files work in one environment and not in another. CM is sensitive to environment variables, optimization settings, compiler and runtime versions, etc. and you have to account for these things.
If you are asking this question relative to repeatable process creation, then the answer needs to be based on the location and quantity of pain you are willing to tolerate. Using a .war file may involve more up-front pain in order to save effort in test and deployment cycles. Using source files and build tools may save up-front cost, but you will have to endure additional pain in dealing with issues late in the deployment process.
Update for concrete example
Two things to consider relative to your example.
*
*A .war file is just a .zip file with an alternate extension. You could replace the configuration file in place using standard zip utilities.
*Potentially reconsider the need to put the configuration file within the .war file. Would it be enough to have it on the classpath or have properties specified in the execution command line at server startup.
Generally, I attempt to keep deployment configuration requirements specific to the deployment location.
A: Using 1 packaged war files for deploys is a good practice.
we use ant to replace the values that are different between environments. We check the file in with a @@@ variable that will get replaced by our ant script. The ant script replaces the correct item in the file and then updates the war file before the deploy to each
<replace file="${BUILDS.ROOT}/DefaultWebApp/WEB-INF/classes/log4j.xml" token="@@@" value="${LOG4J.WEBSPHERE.LOGS}"/>
<!-- update the war file We don't want the source files in the war file.-->
<war basedir="${BUILDS.ROOT}/DefaultWebApp" destfile="${BUILDS.ROOT}/myThomson.war" excludes="WEB-INF/src/**" update="true"/>
To summarize- ant does it all and we use anthill to manage ant.
ant builds the war file, replaces the file paths, updates the war file, then deploys to the target environement. One process, in fact one click of a button in anthill.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How do I use a shell command to tar a list of files and folders with exclusions How do I tar a list of files and folders (all in the same directory) with the exclusion of a single directory (which contains a huge amount of data)
A: tar --exclude=PATTERN xvzf nameof.tar.gz ./*
PATTERN can be the directory name. GNU tar.
A: I think it may depend on your version of tar. You can use 'man tar' or 'tar --help' to check for details on your version. But the options I found are:
tar -X filename: excludes anything listed in the given text file
tar --exclude=pattern: excludes anything matching the pattern
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to set CPU load on a Red Hat Linux box? I have a RHEL box that I need to put under a moderate and variable amount of CPU load (50%-75%).
What is the best way to go about this? Is there a program that can do this that I am not aware of? I am happy to write some C code to make this happen, I just don't know what system calls will help.
A: Find a simple prime number search program that has source code. Modify the source code to add a nanosleep call to the main loop with whichever delay gives you the desired CPU load.
A: This is exactly what you need (internet archive link):
https://web.archive.org/web/20120512025754/http://weather.ou.edu/~apw/projects/stress/stress-1.0.4.tar.gz
From the homepage:
"stress is a simple workload generator for POSIX systems. It imposes a configurable amount of CPU, memory, I/O, and disk stress on the system. It is written in C, and is free software licensed under the GPL."
A: One common way to get some load on a system is to compile a large software package over and over again. Something like the Linux kernel.
Get a copy of the source code, extract the tar.bz2, go into the top level source directory, copy your kernel config from /boot to .config or zcat /proc/config.gz > .config, the do make oldconfig, then while true; do make clean && make bzImage; done
If you have an SMP system, then make -j bzImage is fun, it will spawn make tasks in parallel.
One problem with this is adjusting the CPU load. It will be a maximum CPU load except for when waiting on disk I/O.
A: It really depends what you're trying to test. If you're just testing CPU load, simple scripts to eat empty CPU cycles will work fine. I personally had to test the performance of a RAID array recently and I relied on Bonnie++ and IOZone. IOZone will put a decent load on the box, particularly if you set the file size higher than the RAM.
You may also be interested in this Article.
A: You could possibly do this using a Bash script. Use " ps -o pcpu | grep -v CPU" to get the CPU Usage of all the processes. Add all those values together to get the current usage. Then have a busy while loop that basically keeps on checking those values, figuring out the current CPU usage, and waiting a calculated amount of time to keep the processor at a certain threshhold. More detail is need, but hopefully this will give you a good starting point.
Take a look at this CPU Monitor script I found and try to get some other ideas on how you can accomplish this.
A: Lookbusy enables set value of CPU load.
Project site
lookbusy -c util[-high_util], --cpu-util util[-high_util]
i.e. 60% load
lookbusy -c 60
A: You can probably use some load-generating tool to accomplish this, or run a script to take all the CPU cycles and then use nice and renice on the process to vary the percentage of cycles that the process gets.
Here is a sample bash script that will occupy all the free CPU cycles:
#!/bin/bash
while true ; do
true
done
A: Use the "nice" command.
a) Highest priority:
$ nice -n -20 my_command
or
b) Lowest priority:
$ nice -n 20 my_command
A: A Simple script to load & hammer the CPU using awk. The script does mathematical calculations and thus CPU load peaks up on higher values passwd to loadserver.sh .
checkout the script @ http://unixfoo.blogspot.com/2008/11/linux-cpu-hammer-script.html
A: Not sure what your goal is here. I believe glxgears will use 100% CPU.
So find any process that you know will max out the CPU to 100%.
If you have four CPU cores(0 1 2 3), you could use "taskset" to bind this process to say CPUs 0 and 1. That should load your box 50%. To load it 75% bind the process to 0 1 2 CPUs.
Disclaimer: Haven't tested this. Please let us know your results. Even if this works, I'm not sure what you will achieve out of this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: .NET Compact Framework 3.5 on Windows Mobile 2003 SE Does .NET Compact Framework 3.5 work on Windows Mobile 2003 SE without limitations?
A: Yes, it works fine. The documentation for the download shows this as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server Temp Tables and Connection Pooling I have a multi-user ASP.NET app running against SQL Server and want to have StoredProcA create a #temptable temp table - not a table variable - to insert some data, then branch to StoredProcB, StoredProcC, and StoredProcD to manipulate the data in #temptable per business rules.
The web app uses connection pooling when talking to SQL. Will I get a new #temptable scratch area for each call of StoredProcA? Or will the connection pooling share the #temptable between users?
A: A ## table will be shared by all users. I assume this is not your intention.
A single-# temp table is visible to all stored procedures down the call stack, but not visible outside that scope. If you can have Proc A call B, C, and D, you should be OK.
Edit: The reporting procedure I should be working on right now is a lot like that. :) I create a temp table (#results) in the root proc that's called by the application, then do some complicated data mangling in a series of child procedures, to 1) abstract repeated code, and 2) keep the root procedure from running to 500+ lines.
A: Connection pooling (with any modern version of SQL Server) will call sp_reset_connection when reusing a connection. This stored proc, among other things, drops any temporary tables that the connection owns.
A: #temptable doesn't survive past the end of the procedure in which it was declared, so it won't ever be seen by other users.
Edit: Heh, it turns out that the "nesting visibility" of temp tables has worked since SQL Server 7.0, but I never updated any of my code to take advantage of this. I guess I'm dating myself -- a lot of people probably can't imagine the hell that was SQL Server in the 6.0 and 6.5 days...
A: From the MS docs:
http://msdn.microsoft.com/en-us/library/ms177399(SQL.90).aspx
Temporary Tables
Temporary tables are similar to permanent tables, except temporary tables are stored in tempdb and are deleted automatically when they are no longer used.
There are two types of temporary tables: local and global. They differ from each other in their names, their visibility, and their availability. Local temporary tables have a single number sign (#) as the first character of their names; they are visible only to the current connection for the user, and they are deleted when the user disconnects from the instance of SQL Server.
Global temporary tables have two number signs (##) as the first characters of their names; they are visible to any user after they are created, and they are deleted when all users referencing the table disconnect from the instance of SQL Server.
For example, if you create the table employees, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If a database session creates the local temporary table #employees, only the session can work with the table, and it is deleted when the session disconnects. If you create the global temporary table ##employees, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it after you disconnect and after all other sessions are no longer actively using it.
Additionally from Curt who corrected the error of my ways and just in case you miss the citation in the comment:
http://msdn.microsoft.com/en-us/library/ms191132.aspx
*
*If you create a local temporary
table inside a stored procedure, the
temporary table exists only for the
purposes of the stored procedure; it
disappears when you exit the stored
procedure.
*If you execute a stored procedure
that calls another stored procedure,
the called stored procedure can
access all objects created by the
first stored procedure, including
temporary tables.
A: To share a temp table between users use two hashes before the name ##like_this.
In this case, though make sure you take steps to avoid clashes with multiple instances of the program.
A: Temp tables get created with name mangling under the hood so there shouldn't be conflicts between different stored procedure calls.
If you need to manipulate the same temp data in subsequent stored procedure calls, it's best to just go with a real table and use some sort of unique identifier to make sure you are only dealing with relevant data. If the data is only valuable temporarily, manually delete it once you're done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: How do you compare structs for equality in C? How do you compare two instances of structs for equality in standard C?
A: Note you can use memcmp() on non static stuctures without
worrying about padding, as long as you don't initialise
all members (at once). This is defined by C90:
http://www.pixelbeat.org/programming/gcc/auto_init.html
A: It depends on whether the question you are asking is:
*
*Are these two structs the same object?
*Do they have the same value?
To find out if they are the same object, compare pointers to the two structs for equality.
If you want to find out in general if they have the same value you have to do a deep comparison. This involves comparing all the members. If the members are pointers to other structs you need to recurse into those structs too.
In the special case where the structs do not contain pointers you can do a memcmp to perform a bitwise comparison of the data contained in each without having to know what the data means.
Make sure you know what 'equals' means for each member - it is obvious for ints but more subtle when it comes to floating-point values or user-defined types.
A: If you do it a lot I would suggest writing a function that compares the two structures. That way, if you ever change the structure you only need to change the compare in one place.
As for how to do it.... You need to compare every element individually
A: C provides no language facilities to do this - you have to do it yourself and compare each structure member by member.
A: You can't use memcmp to compare structs for equality due to potential random padding characters between field in structs.
// bad
memcmp(&struct1, &struct2, sizeof(struct1));
The above would fail for a struct like this:
typedef struct Foo {
char a;
/* padding */
double d;
/* padding */
char e;
/* padding */
int f;
} Foo ;
You have to use member-wise comparison to be safe.
A: memcmp does not compare structure, memcmp compares the binary, and there is always garbage in the struct, therefore it always comes out False in comparison.
Compare element by element its safe and doesn't fail.
A: You may be tempted to use memcmp(&a, &b, sizeof(struct foo)), but it may not work in all situations. The compiler may add alignment buffer space to a structure, and the values found at memory locations lying in the buffer space are not guaranteed to be any particular value.
But, if you use calloc or memset the full size of the structures before using them, you can do a shallow comparison with memcmp (if your structure contains pointers, it will match only if the address the pointers are pointing to are the same).
A: @Greg is correct that one must write explicit comparison functions in the general case.
It is possible to use memcmp if:
*
*the structs contain no floating-point fields that are possibly NaN.
*the structs contain no padding (use -Wpadded with clang to check this) OR the structs are explicitly initialized with memset at initialization.
*there are no member types (such as Windows BOOL) that have distinct but equivalent values.
Unless you are programming for embedded systems (or writing a library that might be used on them), I would not worry about some of the corner cases in the C standard. The near vs. far pointer distinction does not exist on any 32- or 64- bit device. No non-embedded system that I know of has multiple NULL pointers.
Another option is to auto-generate the equality functions. If you lay your struct definitions out in a simple way, it is possible to use simple text processing to handle simple struct definitions. You can use libclang for the general case – since it uses the same frontend as Clang, it handles all corner cases correctly (barring bugs).
I have not seen such a code generation library. However, it appears relatively simple.
However, it is also the case that such generated equality functions would often do the wrong thing at application level. For example, should two UNICODE_STRING structs in Windows be compared shallowly or deeply?
A: If the structs only contain primitives or if you are interested in strict equality then you can do something like this:
int my_struct_cmp(const struct my_struct * lhs, const struct my_struct * rhs)
{
return memcmp(lhs, rsh, sizeof(struct my_struct));
}
However, if your structs contain pointers to other structs or unions then you will need to write a function that compares the primitives properly and make comparison calls against the other structures as appropriate.
Be aware, however, that you should have used memset(&a, sizeof(struct my_struct), 1) to zero out the memory range of the structures as part of your ADT initialization.
A: This compliant example uses the #pragma pack compiler extension from Microsoft Visual Studio to ensure the structure members are packed as tightly as possible:
#include <string.h>
#pragma pack(push, 1)
struct s {
char c;
int i;
char buffer[13];
};
#pragma pack(pop)
void compare(const struct s *left, const struct s *right) {
if (0 == memcmp(left, right, sizeof(struct s))) {
/* ... */
}
}
A: if the 2 structures variable are initialied with calloc or they are set with 0 by memset so you can compare your 2 structures with memcmp and there is no worry about structure garbage and this will allow you to earn time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "249"
}
|
Q: OC4J 10.1.3.4 problem with deploying multiple 2.1 EJBs I am having troubles migrating from OC4J 10.1.2.3 to 10.1.3.1.4. The problem is for applications that have multiple EJBs (all are 2.1, no EJB 3.0). Jdeveloper will take the default ejb-jar.xml (the one required for Jdeveloper to run it on its stand-alone OC4J instance) and package it into each EJB JAR module NO MATTER what. This results in the app server drilling into each EJB JAR module when deploying, and find the same ejb-jar.xml file N times (where N = number of EJB Modules). This results in duplicate EJB references and will break any JNDI lookups such as: "java:comp/env/ejb/EJBName". Thus deploying an app that has 3 EJBs, EJB1, EJB2 and EJB3 causes the app server to register 9 EJBs instead of 3. I need a best practices way, but in between the way 10.1.3.4 and JDeveloper are acting the situation is rather dire...
Side note: They will work if the web app's JNDI look-up code is refractored to just "ejb/EJBName". This is not desirable though.
A: You should check the Oracle documentation to see which is your case.
The Oracle® Containers for J2EE Enterprise JavaBeans Developer's Guide is a good start
According to the Oracle® Containers for J2EE Services Guide, chapter 2: Using JNDI
when you use the form "ejb/EJBName" you perform "local" lookup. If you want to use the full form you must check the "Enabling Global JNDI Lookups" section of the "Using JNDI" chapter.
A: The problem was multiple reference in our deployment profiles. We were create a deployment profile for EACH EJB. This meant that each EJB had it's own ejb-jar.xml (this file contained a description of all EJBS in the project). Therefore, every time JDeveloper created an EJB, it placed a descriptor of all EJBS in each EJB it generated, causing an NxN amount of references. Therefore Nx(N-1) extra references.
Now, the key point is that Oracle Application Server 10.1.2.3.0 and bellow did not care about these duplicate references. However as we can see, 10.1.3.1.4 is a much different version and this did break.
Our fix: to have only 1 EJB Deployment profile that contains all of the EJB classes and the POJO's that they use. Remember, before there was 1 EJB Profile for each EJB... All this did was allow for Jdeveloper (which is crap IMHO) to correctly generate a valid EAR. A combination of Jdeveloper and Oracle's Application Server's crap is what caused this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the default session timeout for a Java EE website? If I do not specify the following in my web.xml file:
<session-config>
<session-timeout>10</session-timeout>
</session-config>
What will be my default session timeout? (I am running Tomcat 6.0)
A: You can also set this in code, for a specific session using the HttpSession setMaxInactiveInterval API:
Specifies the time, in seconds,
between client requests before the
servlet container will invalidate this
session. A negative time indicates the
session should never timeout.
I mention this in case you see timeouts that are not 30 minutes, but you didn't specify another value (e.g. another developer on the project used this API).
Another item to note is this timeout may not trigger on the exact second the session is eligible to expire. The Java EE server may have a polling thread that checks for expired sessions every minute. I don't have a reference for this, but have seen this behavior in the WebSphere 5.1 era.
A: I'm sure it depends on your container. Tomcat is 30 minutes.
A: If you're using Tomcat, it's 30 minutes. You can read more about it here.
A: Session Time out we can specify for that particular context in web.xml file as mentined below entry
60
Default Session time out is 30 mins
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: Float values behaving differently across the release and debug builds My application is generating different floating point values when I compile it in release mode and in debug mode. The only reason that I found out is I save a binary trace log and the one from the release build is ever so slightly off from the debug build, it looks like the bottom two bits of the 32 bit float values are different about 1/2 of the cases.
Would you consider this "difference" to be a bug or would this type of difference be expected. Would this be a compiler bug or an internal library bug.
For example:
LEFTPOS and SPACING are defined floating point values.
float def_x;
int xpos;
def_x = LEFTPOS + (xpos * (SPACING / 2));
The issue is in regards to the X360 compiler.
A: I know that on PC, floating point registers are 80 bits wide. So if a calculation is done entirely within the FPU, you get the benefit of 80 bits of precision. On the other hand, if an intermediate result is moved out into a normal register and back, it gets truncated to 32 bits, which gives different results.
Now consider that a release build will have optimisations which keep intermediate results in FPU registers, whereas a debug build will probably naively copy intermediate results back and forward between memory and registers - and there you have your difference in behaviour.
I don't know whether this happens on X360 too or not.
A: It's not a bug. Any floating point uperation has a certain imprecision. In Release mode, optimization will change the order of the operations and you'll get a slightly different result. The difference should be small, though. If it's big you might have other problems.
A: I helped a co-worker find a compiler switch that was different in release vs. debug builds that was causing his differences.
Take a look at /fp (Specify Floating-Point Behavior).
A: In addition to the different floating-point modes others have pointed out, SSE or similiar vector optimizations may be turned on for release. Converting floating-point arithmetic from standard registers to vector registers can have an effect on the lower bits of your results, as the vector registers will generally be more narrow (fewer bits) than the standard floating-point registers.
A: Release mode may have a different FP strategy set. There are different floating point arithmetic modes depending on the level of optimization you'd like. MSVC, for example, has strict, fast, and precise modes.
A: Not a bug. This type of difference is to be expected.
For example, some platforms have float registers that use more bits than are stored in memory, so keeping a value in the register can yield a slightly different result compared to storing to memory and re-loading from memory.
A: This discrepancy may very well be caused by the compiler optimization, which is typically done in the release mode, but not in debug mode. For example, the compiler may reorder some of the operations to speed up execution, which can conceivably cause a slight difference in the floating point result.
So, I would say most likely it is not a bug. If you are really worried about this, try turning on optimization in the Debug mode.
A: Like others mentioned, floating point registers have higher precision than floats, so the accuracy of the final result depends on the register allocation.
If you need consistent results, you can make the variables volatile, which will result in slower, less precise, but consistent results.
A: If you set a compiler switch that allowed the compiler to reorder floating-point operations, -- e.g. /fp:fast -- then obviously it's not a bug.
If you didn't set any such switch, then it's a bug -- the C and C++ standards don't allow the compilers to reorder operations without your permission.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: GDI has been accelerated. Does anyone know when this happened? To sketch the background of this question : at work we use Dell Precision workstations. My current one has got an NVidia Quadro FX1700.
My team is developing the graphics components for a real time data acquisition system.
So we are always looking out to see if the graphics operations don't use up too much CPU time. For quick checks, we have a couple of test programs that we run, which draw scenes at a specified rate ( e.g. 10 fps ) and we use plain old Task Manager to see where CPU usage is at.
One of these programs is heavy on GDI DrawRectangle calls ( which are filled ). This program always used to consume about 40% CPU user-time, but since about a year or so ( just guessing here ) it only uses about 2-3 % kernel-time. So clearly some hardware acceleration is going on here. And indeed, if I turn HW-accell off, we're back to the original 40% user-time.
All of this is of course good news, because we were already thinking about going to OpenGL. Year after year GDI never got the benefit of hardware acceleration. Until some time ago that is.
Does anyone know anything more about this? Did Microsoft do this? Or is it gfx-card vendor specific?
Edit
Thnx for the answers already ( Ferrucio, Torlack and Rob Walker ) but my question has not been answered yet. We are talking about a filled rectangle here. Probably the most trivial function to optimize : just send a couple of coordinates to the GPU and let it rip. Yet it was always implemented on the CPU side.
So far the answers lead me to believe that NVidia finally saw the light ( after more than 10 years ) and accelerated GDI. And no announcement about this? There's no information to be found on this at all.
My internal customers ask me about the speedup of the graphics, and all I can say is "well, we got lucky".
Edit2
It does seem like it is driver related according to the different answers. So, then NVidia has made crappy GDI drivers for its workstation cards for years. It really was an accepted fact within this company that GDI was not accelerated and all the tests confirmed this.
A: GDI works by calling various functions in the graphics device driver. There are a core set of functions that every driver must implement. Other functions may be implemented by the driver. If they are not, GDI will perform those functions itself.
If a particular function is not implemented in hardware then there is no point in the driver doing a software implementation of that function since GDI can probably do a better job. GDI is extremely well optimized for performance.
As more functions are implemented in hardware, not only do those functions perform much better, but there is also less work for GDI to do, resulting in less CPU time spent on graphics.
It may also be the case that the graphics card vendor, in an effort to get a card out to market quickly, may not have implemented all possible hardware functions that the card could perform. Later versions of that driver may then implement that functionality, resulting in improved performance.
A: GDI was accelerated for quite awhile. Far as I recall it did depend on your hardware and drivers to some extent. Why you've seen such a jump in performance only recently seems odd.
However, don't get too happy - GDI hardware acceleration is no longer supported in Vista. The new desktop composition engine doesn't support it. However, in Vista you do gain fast moving of windows since content doesn't always have to be re-drawn by the application (and no tearing I think?).
A: To some extent, GDI has always been accelerated. Even back in the old Win31 days I remember buys cards (Number9) who's main selling point was hardware acceleration of GDI.
A: Vista has a new display driver architecture which would provide an opportunity for a dramatic increase in performance. Are you comparing like hardware/OS combinations?
A: A lot of the 2D stuff has been accelerated for some time, each new major version of windows has changed the way display drivers have worked. I believe it was with XP that windows revamped it's window manager layer. Hard to compare, really, since XP is more similar to windows 2000/NT than any earlier versions.
Some more info on wikipedia, Development of Windows XP.
Windows 2000, certainly, was the first NT-kernel-based windows to include DirectX, and had some graphical improvements as well. Windows 2000 (wikipedia)
I don't believe there have been major changes to the display driver model/2D subsystem between releases. So if you noticed a change like that, it's likely due to something nVidia did.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Is there an alternative to conditional display:none I inherited an application where display:none was used to control conditional display of input elements based the values of other input elements.
The way this was handled is by running some pretty ugly code to evaluate field values and reset the display property in the during page load. Every time.
Isn't there a better way?
A: Using display: none in conjunction with JavaScript and CSS is the easiest way of simply showing or hiding DOM elements on the fly. That said, you could manipulate the DOM itself by adding or removing elements rather than simply showing / hiding them (with jQuery, for example).
A: Maybe your should just redesign the form that uses all the display: none fields or rewrite/refactor the script that does this checking? If the form is too large split it into several pieces - this will help the user too. I personally don't like if the form changes often whenever I am trying to fill in everything.
A: If you are not showing and hiding elements dynamically as the user interacts with the form, then there's no need to use CSS/Javascript. Just use your server-side language (PHP/JSP/whatever) to not output the hidden fields. You'll use less bandwidth, and the form will work even with Javascript disabled.
A: Is the idea to reshape the form on every POST or reorder fields before submitting. If the first then the fields shown should be removed on the server-side before page get to the user. If you are talking about changing on the client side before a post (e.g. removing fields which are not relevant based on the input in some fields as the user types), you can use javascript to remove fields from the DOM.
The two things your solution needs are:
*
*The forms must be functional without javascript (even if they feel less slick)
*Don't submit fields the user cannot see unless they are input tags with type="hidden". You will only confuse yourself on the backend if you don't know whether a user left a field blank or could not see it because it dynamically had its styling changed by a client-side script.
A: there is an partial alternate to display:none i.e
use this style in css
opacity:0;
but problem with this is it doesn't appears on canvas but it is still there.
using display:none; completely delete element and creates when u apply attribute display:block;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Solving the NP-complete problem in XKCD The problem/comic in question: http://xkcd.com/287/
I'm not sure this is the best way to do it, but here's what I've come up with so far. I'm using CFML, but it should be readable by anyone.
<cffunction name="testCombo" returntype="boolean">
<cfargument name="currentCombo" type="string" required="true" />
<cfargument name="currentTotal" type="numeric" required="true" />
<cfargument name="apps" type="array" required="true" />
<cfset var a = 0 />
<cfset var found = false />
<cfloop from="1" to="#arrayLen(arguments.apps)#" index="a">
<cfset arguments.currentCombo = listAppend(arguments.currentCombo, arguments.apps[a].name) />
<cfset arguments.currentTotal = arguments.currentTotal + arguments.apps[a].cost />
<cfif arguments.currentTotal eq 15.05>
<!--- print current combo --->
<cfoutput><strong>#arguments.currentCombo# = 15.05</strong></cfoutput><br />
<cfreturn true />
<cfelseif arguments.currentTotal gt 15.05>
<cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br />
<cfreturn false />
<cfelse>
<!--- less than 15.05 --->
<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />
<cfset found = testCombo(arguments.currentCombo, arguments.currentTotal, arguments.apps) />
</cfif>
</cfloop>
</cffunction>
<cfset mf = {name="Mixed Fruit", cost=2.15} />
<cfset ff = {name="French Fries", cost=2.75} />
<cfset ss = {name="side salad", cost=3.35} />
<cfset hw = {name="hot wings", cost=3.55} />
<cfset ms = {name="moz sticks", cost=4.20} />
<cfset sp = {name="sampler plate", cost=5.80} />
<cfset apps = [ mf, ff, ss, hw, ms, sp ] />
<cfloop from="1" to="6" index="b">
<cfoutput>#testCombo(apps[b].name, apps[b].cost, apps)#</cfoutput>
</cfloop>
The above code tells me that the only combination that adds up to $15.05 is 7 orders of Mixed Fruit, and it takes 232 executions of my testCombo function to complete.
Is there a better algorithm to come to the correct solution? Did I come to the correct solution?
A: Even though knapsack is NP Complete, it is a very special problem: the usual dynamic program for it is in fact excellent (http://en.wikipedia.org/wiki/Knapsack_problem)
And if you do the correct analysis, it turns out that it is O(nW), n being the # of items, and W being the target number. The problem is when you have to DP over a large W, that's when we get the NP behaviour. But for the most part, knapsack is reasonably well behaved and you can solve really large instances of it with no problems. As far as NP complete problems go, knapsack is one of the easiest.
A: Here is the solution using constraint.py
>>> from constraint import *
>>> problem = Problem()
>>> menu = {'mixed-fruit': 2.15,
... 'french-fries': 2.75,
... 'side-salad': 3.35,
... 'hot-wings': 3.55,
... 'mozarella-sticks': 4.20,
... 'sampler-plate': 5.80}
>>> for appetizer in menu:
... problem.addVariable( appetizer, [ menu[appetizer] * i for i in range( 8 )] )
>>> problem.addConstraint(ExactSumConstraint(15.05))
>>> problem.getSolutions()
[{'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 5.7999999999999998, 'mixed-fruit': 2.1499999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 7.0999999999999996},
{'side-salad': 0.0, 'french-fries': 0.0, 'sampler-plate': 0.0, 'mixed-fruit': 15.049999999999999, 'mozarella-sticks': 0.0, 'hot-wings': 0.0}]
So the solution is to order a sampler plate, a mixed fruit, and 2 orders of hot wings, or order 7 mixed-fruits.
A: It gives all the permutations of the solutions, but I think I'm beating everyone else for code size.
item(X) :- member(X,[215, 275, 335, 355, 420, 580]).
solution([X|Y], Z) :- item(X), plus(S, X, Z), Z >= 0, solution(Y, S).
solution([], 0).
Solution with swiprolog:
?- solution(X, 1505).
X = [215, 215, 215, 215, 215, 215, 215] ;
X = [215, 355, 355, 580] ;
X = [215, 355, 580, 355] ;
X = [215, 580, 355, 355] ;
X = [355, 215, 355, 580] ;
X = [355, 215, 580, 355] ;
X = [355, 355, 215, 580] ;
X = [355, 355, 580, 215] ;
X = [355, 580, 215, 355] ;
X = [355, 580, 355, 215] ;
X = [580, 215, 355, 355] ;
X = [580, 355, 215, 355] ;
X = [580, 355, 355, 215] ;
No
A: Here's a solution with F#:
#light
type Appetizer = { name : string; cost : int }
let menu = [
{name="fruit"; cost=215}
{name="fries"; cost=275}
{name="salad"; cost=335}
{name="wings"; cost=355}
{name="moz sticks"; cost=420}
{name="sampler"; cost=580}
]
// Choose: list<Appetizer> -> list<Appetizer> -> int -> list<list<Appetizer>>
let rec Choose allowedMenu pickedSoFar remainingMoney =
if remainingMoney = 0 then
// solved it, return this solution
[ pickedSoFar ]
else
// there's more to spend
[match allowedMenu with
| [] -> yield! [] // no more items to choose, no solutions this branch
| item :: rest ->
if item.cost <= remainingMoney then
// if first allowed is within budget, pick it and recurse
yield! Choose allowedMenu (item :: pickedSoFar) (remainingMoney - item.cost)
// regardless, also skip ever picking more of that first item and recurse
yield! Choose rest pickedSoFar remainingMoney]
let solutions = Choose menu [] 1505
printfn "%d solutions:" solutions.Length
solutions |> List.iter (fun solution ->
solution |> List.iter (fun item -> printf "%s, " item.name)
printfn ""
)
(*
2 solutions:
fruit, fruit, fruit, fruit, fruit, fruit, fruit,
sampler, wings, wings, fruit,
*)
A: The point about an NP-complete problem is not that it's tricky on a small data set, but that the amount of work to solve it grows at a rate greater than polynomial, i.e. there is no O(n^x) algorithm.
If the time complexity is O(n!), as in (I believe) the two problems mentioned above, that is in NP.
A: Read up on the Knapsack Problem.
A: You've got all the correct combinations now, but you're still checking many more than you need to (as evidenced by the many permutations your result shows). Also, you're omitting the last item that hits the 15.05 mark.
I have a PHP version that does 209 iterations of the recursive call (it does 2012 if I get all permutations). You can reduce your count if right before the end of your loop, you pull out the item you just checked.
I don't know CF syntax, but it will be something like this:
<cfelse>
<!--- less than 15.50 --->
<!--<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />-->
<cfset found = testCombo(CC, CT, arguments.apps) />
------- remove the item from the apps array that was just checked here ------
</cfif>
</cfloop>
EDIT: For reference, here's my PHP version:
<?
function rc($total, $string, $m) {
global $c;
$m2 = $m;
$c++;
foreach($m as $i=>$p) {
if ($total-$p == 0) {
print "$string $i\n";
return;
}
if ($total-$p > 0) {
rc($total-$p, $string . " " . $i, $m2);
}
unset($m2[$i]);
}
}
$c = 0;
$m = array("mf"=>215, "ff"=>275, "ss"=>335, "hw"=>355, "ms"=>420, "sp"=>580);
rc(1505, "", $m);
print $c;
?>
Output
mf mf mf mf mf mf mf
mf hw hw sp
209
EDIT 2:
Since explaining why you can remove the elements will take a little more than I could fit in a comment, I'm adding it here.
Basically, each recursion will find all combinations that include the currently search element (e.g., the first step will find everything including at least one mixed fruit). The easiest way to understand it is to trace the execution, but since that will take a lot of space, I'll do it as if the target was 6.45.
MF (2.15)
MF (4.30)
MF (6.45) *
FF (7.05) X
SS (7.65) X
...
[MF removed for depth 2]
FF (4.90)
[checking MF now would be redundant since we checked MF/MF/FF previously]
FF (7.65) X
...
[FF removed for depth 2]
SS (5.50)
...
[MF removed for depth 1]
At this point, we've checked every combination that includes any mixed fruit, so there's no need to check for mixed fruit again. You can use the same logic to prune the array at each of the deeper recursions as well.
Tracing through it like this actually suggested another slight time saver -- knowing the prices are sorted from low to high means that we don't need to keep checking items once we go over the target.
A: I would make one suggestion about the design of the algorithm itself (which is how I interpreted the intent of your original question). Here is a fragment of the solution I wrote:
....
private void findAndReportSolutions(
int target, // goal to be achieved
int balance, // amount of goal remaining
int index // menu item to try next
) {
++calls;
if (balance == 0) {
reportSolution(target);
return; // no addition to perfect order is possible
}
if (index == items.length) {
++falls;
return; // ran out of menu items without finding solution
}
final int price = items[index].price;
if (balance < price) {
return; // all remaining items cost too much
}
int maxCount = balance / price; // max uses for this item
for (int n = maxCount; 0 <= n; --n) { // loop for this item, recur for others
++loops;
counts[index] = n;
findAndReportSolutions(
target, balance - n * price, index + 1
);
}
}
public void reportSolutionsFor(int target) {
counts = new int[items.length];
calls = loops = falls = 0;
findAndReportSolutions(target, target, 0);
ps.printf("%d calls, %d loops, %d falls%n", calls, loops, falls);
}
public static void main(String[] args) {
MenuItem[] items = {
new MenuItem("mixed fruit", 215),
new MenuItem("french fries", 275),
new MenuItem("side salad", 335),
new MenuItem("hot wings", 355),
new MenuItem("mozzarella sticks", 420),
new MenuItem("sampler plate", 580),
};
Solver solver = new Solver(items);
solver.reportSolutionsFor(1505);
}
...
(Note that the constructor does sort the menu items by increasing price, to enable the constant-time early termination when the remaining balance is smaller than any remaining menu item.)
The output for a sample run is:
7 mixed fruit (1505) = 1505
1 mixed fruit (215) + 2 hot wings (710) + 1 sampler plate (580) = 1505
348 calls, 347 loops, 79 falls
The design suggestion I want to highlight is that in the above code, each nested (recursive) call of findAndReportSolution(...) deals with the quantity of exactly one menu item, identified by the index argument. In other words, the recursive nesting parallels the behavior of an in-line set of nested loops; the outermost counts possible uses of the first menu item, the next in counts the uses of the second menu item, etc. (Except, of course, the use of recursion liberates the code from dependence on a specific number of menu items!)
I suggest that this makes it easier to design the code, and easier to understand what each invocation is doing (accounting for all possible uses of a specific item, delegating the remainder of the menu to subordinate calls). It also avoids the combinatorial explosion of producing all arrangements of a multiple-item solution (as in the second line of the above output, which only occurs once, instead of repeatedly with different orderings of the items).
I try to maximize the "obviousness" of the code, rather than trying to minimize the number of calls of some specific method. For example, the above design lets a delegated call determine if a solution has been reached, rather than wrapping that check around the point of the call, which would reduce the number of calls at the expense of cluttering up the code.
A: Isn't it more elegant with recursion (in Perl)?
#!/usr/bin/perl
use strict;
use warnings;
my @weights = (2.15, 2.75, 3.35, 3.55, 4.20, 5.80);
my $total = 0;
my @order = ();
iterate($total, @order);
sub iterate
{
my ($total, @order) = @_;
foreach my $w (@weights)
{
if ($total+$w == 15.05)
{
print join (', ', (@order, $w)), "\n";
}
if ($total+$w < 15.05)
{
iterate($total+$w, (@order, $w));
}
}
}
Output
marco@unimatrix-01:~$ ./xkcd-knapsack.pl
2.15, 2.15, 2.15, 2.15, 2.15, 2.15, 2.15
2.15, 3.55, 3.55, 5.8
2.15, 3.55, 5.8, 3.55
2.15, 5.8, 3.55, 3.55
3.55, 2.15, 3.55, 5.8
3.55, 2.15, 5.8, 3.55
3.55, 3.55, 2.15, 5.8
3.55, 5.8, 2.15, 3.55
5.8, 2.15, 3.55, 3.55
5.8, 3.55, 2.15, 3.55
A: Hmm, you know what's weird. The solution is seven of the first item on the menu.
Since this was obviously meant to be solved by paper and pencil in a short time frame, why not divide the order total by the price of each item to see if by some chance they ordered multiples of one item?
For example,
15.05/2.15 = 7 mixed fruits
15.05/2.75 = 5.5 french fries.
And then move on to simple combinations...
15 / (2.15 + 2.75) = 3.06122449 mixed fruits with french fries.
In other words, assume that the solution is supposed to be simple and solvable by a human without access to a computer. Then test if the simplest, most obvious (and therefore hidden in plain sight) solution(s) work(s).
I swear I'm pulling this at the local coney this weekend when I order $4.77 worth of appetizers (including tax) at 4:30 AM after the club closes.
A: In python.
I had some problems with "global vars" so I put the function as method of an object. It is recursive and it calls itself 29 times for the question in the comic, stopping at the first successful match
class Solver(object):
def __init__(self):
self.solved = False
self.total = 0
def solve(s, p, pl, curList = []):
poss = [i for i in sorted(pl, reverse = True) if i <= p]
if len(poss) == 0 or s.solved:
s.total += 1
return curList
if abs(poss[0]-p) < 0.00001:
s.solved = True # Solved it!!!
s.total += 1
return curList + [poss[0]]
ml,md = [], 10**8
for j in [s.solve(p-i, pl, [i]) for i in poss]:
if abs(sum(j)-p)<md: ml,md = j, abs(sum(j)-p)
s.total += 1
return ml + curList
priceList = [5.8, 4.2, 3.55, 3.35, 2.75, 2.15]
appetizers = ['Sampler Plate', 'Mozzarella Sticks', \
'Hot wings', 'Side salad', 'French Fries', 'Mixed Fruit']
menu = zip(priceList, appetizers)
sol = Solver()
q = sol.solve(15.05, priceList)
print 'Total time it runned: ', sol.total
print '-'*30
order = [(m, q.count(m[0])) for m in menu if m[0] in q]
for o in order:
print '%d x %s \t\t\t (%.2f)' % (o[1],o[0][1],o[0][0])
print '-'*30
ts = 'Total: %.2f' % sum(q)
print ' '*(30-len(ts)-1),ts
Output:
Total time it runned: 29
------------------------------
1 x Sampler Plate (5.80)
2 x Hot wings (3.55)
1 x Mixed Fruit (2.15)
------------------------------
Total: 15.05
A: Actually, I've refactored my algorithm some more. There were several correct combinations I was missing, and it was due to the fact that I was returning as soon as the cost went over 15.05 -- I wasn't bothering to check other (cheaper) items that I could add. Here's my new algorithm:
<cffunction name="testCombo" returntype="numeric">
<cfargument name="currentCombo" type="string" required="true" />
<cfargument name="currentTotal" type="numeric" required="true" />
<cfargument name="apps" type="array" required="true" />
<cfset var a = 0 />
<cfset var found = false />
<cfset var CC = "" />
<cfset var CT = 0 />
<cfset tries = tries + 1 />
<cfloop from="1" to="#arrayLen(arguments.apps)#" index="a">
<cfset combos = combos + 1 />
<cfset CC = listAppend(arguments.currentCombo, arguments.apps[a].name) />
<cfset CT = arguments.currentTotal + arguments.apps[a].cost />
<cfif CT eq 15.05>
<!--- print current combo --->
<cfoutput><strong>#CC# = 15.05</strong></cfoutput><br />
<cfreturn true />
<cfelseif CT gt 15.05>
<!--<cfoutput>#arguments.currentCombo# > 15.05 (aborting)</cfoutput><br />-->
<cfelse>
<!--- less than 15.50 --->
<!--<cfoutput>#arguments.currentCombo# < 15.05 (traversing)</cfoutput><br />-->
<cfset found = testCombo(CC, CT, arguments.apps) />
</cfif>
</cfloop>
<cfreturn found />
</cffunction>
<cfset mf = {name="Mixed Fruit", cost=2.15} />
<cfset ff = {name="French Fries", cost=2.75} />
<cfset ss = {name="side salad", cost=3.35} />
<cfset hw = {name="hot wings", cost=3.55} />
<cfset ms = {name="moz sticks", cost=4.20} />
<cfset sp = {name="sampler plate", cost=5.80} />
<cfset apps = [ mf, ff, ss, hw, ms, sp ] />
<cfset tries = 0 />
<cfset combos = 0 />
<cfoutput>
<cfloop from="1" to="6" index="b">
#testCombo(apps[b].name, apps[b].cost, apps)#
</cfloop>
<br />
tries: #tries#<br />
combos: #combos#
</cfoutput>
Output:
Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit,Mixed Fruit = 15.05
Mixed Fruit,hot wings,hot wings,sampler plate = 15.05
Mixed Fruit,hot wings,sampler plate,hot wings = 15.05
Mixed Fruit,sampler plate,hot wings,hot wings = 15.05
false false false hot wings,Mixed Fruit,hot wings,sampler plate = 15.05
hot wings,Mixed Fruit,sampler plate,hot wings = 15.05
hot wings,hot wings,Mixed Fruit,sampler plate = 15.05
hot wings,sampler plate,Mixed Fruit,hot wings = 15.05
false false sampler plate,Mixed Fruit,hot wings,hot wings = 15.05
sampler plate,hot wings,Mixed Fruit,hot wings = 15.05
false
tries: 2014
combos: 12067
I think this may have all of the correct combinations, but my question still stands: Is there a better algorithm?
A: Learning from @rcar's answer, and another refactoring later, I've got the following.
As with so many things I code, I've refactored from CFML to CFScript, but the code is basically the same.
I added in his suggestion of a dynamic start point in the array (instead of passing the array by value and changing its value for future recursions), which brought me to the same stats he gets (209 recursions, 571 combination price checks (loop iterations)), and then improved on that by assuming that the array will be sorted by cost -- because it is -- and breaking as soon as we go over the target price. With the break, we're down to 209 recursions and 376 loop iterations.
What other improvements could be made to the algorithm?
function testCombo(minIndex, currentCombo, currentTotal){
var a = 0;
var CC = "";
var CT = 0;
var found = false;
tries += 1;
for (a=arguments.minIndex; a <= arrayLen(apps); a++){
combos += 1;
CC = listAppend(arguments.currentCombo, apps[a].name);
CT = arguments.currentTotal + apps[a].cost;
if (CT eq 15.05){
//print current combo
WriteOutput("<strong>#CC# = 15.05</strong><br />");
return(true);
}else if (CT gt 15.05){
//since we know the array is sorted by cost (asc),
//and we've already gone over the price limit,
//we can ignore anything else in the array
break;
}else{
//less than 15.50, try adding something else
found = testCombo(a, CC, CT);
}
}
return(found);
}
mf = {name="mixed fruit", cost=2.15};
ff = {name="french fries", cost=2.75};
ss = {name="side salad", cost=3.35};
hw = {name="hot wings", cost=3.55};
ms = {name="mozarella sticks", cost=4.20};
sp = {name="sampler plate", cost=5.80};
apps = [ mf, ff, ss, hw, ms, sp ];
tries = 0;
combos = 0;
testCombo(1, "", 0);
WriteOutput("<br />tries: #tries#<br />combos: #combos#");
A: Here's concurrent implementation in Clojure. To calculate (items-with-price 15.05) takes about 14 combination-generation recursions, and about 10 possibility-checks. Took me about 6 minutes to calculate (items-with-price 100) on my Intel Q9300.
This only gives the first found answer, or nil if there is none, as that's all the problem calls for. Why do more work that you've been told to do ;) ?
;; np-complete.clj
;; A Clojure solution to XKCD #287 "NP-Complete"
;; By Sam Fredrickson
;;
;; The function "items-with-price" returns a sequence of items whose sum price
;; is equal to the given price, or nil.
(defstruct item :name :price)
(def *items* #{(struct item "Mixed Fruit" 2.15)
(struct item "French Fries" 2.75)
(struct item "Side Salad" 3.35)
(struct item "Hot Wings" 3.55)
(struct item "Mozzarella Sticks" 4.20)
(struct item "Sampler Plate" 5.80)})
(defn items-with-price [price]
(let [check-count (atom 0)
recur-count (atom 0)
result (atom nil)
checker (agent nil)
; gets the total price of a seq of items.
items-price (fn [items] (apply + (map #(:price %) items)))
; checks if the price of the seq of items matches the sought price.
; if so, it changes the result atom. if the result atom is already
; non-nil, nothing is done.
check-items (fn [unused items]
(swap! check-count inc)
(if (and (nil? @result)
(= (items-price items) price))
(reset! result items)))
; lazily generates a list of combinations of the given seq s.
; haven't tested well...
combinations (fn combinations [cur s]
(swap! recur-count inc)
(if (or (empty? s)
(> (items-price cur) price))
'()
(cons cur
(lazy-cat (combinations (cons (first s) cur) s)
(combinations (cons (first s) cur) (rest s))
(combinations cur (rest s))))))]
; loops through the combinations of items, checking each one in a thread
; pool until there are no more combinations or the result atom is non-nil.
(loop [items-comb (combinations '() (seq *items*))]
(if (and (nil? @result)
(not-empty items-comb))
(do (send checker check-items (first items-comb))
(recur (rest items-comb)))))
(await checker)
(println "No. of recursions:" @recur-count)
(println "No. of checks:" @check-count)
@result))
A: If you want an optimized algorithm, it's best to try the prices in descending order. That lets you use up as much of the remaining amount first and then see how the rest can be filled in.
Also, you can use math to figure out the maximum quantity of each food item to start each time so you don't try combinations that would go over the $15.05 goal.
This algorithm only needs to try 88 combinations to get a complete answer and that looks like the lowest that's been posted so far:
public class NPComplete {
private static final int[] FOOD = { 580, 420, 355, 335, 275, 215 };
private static int tries;
public static void main(String[] ignore) {
tries = 0;
addFood(1505, "", 0);
System.out.println("Combinations tried: " + tries);
}
private static void addFood(int goal, String result, int index) {
// If no more food to add, see if this is a solution
if (index >= FOOD.length) {
tries++;
if (goal == 0)
System.out.println(tries + " tries: " + result.substring(3));
return;
}
// Try all possible quantities of this food
// If this is the last food item, only try the max quantity
int qty = goal / FOOD[index];
do {
addFood(goal - qty * FOOD[index],
result + " + " + qty + " * " + FOOD[index], index + 1);
} while (index < FOOD.length - 1 && --qty >= 0);
}
}
Here's the output showing the two solutions:
9 tries: 1 * 580 + 0 * 420 + 2 * 355 + 0 * 335 + 0 * 275 + 1 * 215
88 tries: 0 * 580 + 0 * 420 + 0 * 355 + 0 * 335 + 0 * 275 + 7 * 215
Combinations tried: 88
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: KornShell (ksh) wraparound Okay, I am sure this is simple but it is driving me nuts. I recently went to work on a program where I have had to step back in time a bit and use Redhat 9. When I'm typing on the command line from a standard xterm running KornShell (ksh), and I reach the end of the line the screen slides to the right (cutting off the left side of my command) instead of wrapping the text around to a new line. This makes things difficult for me because I can't easily copy and paste from the previous command straight from the command line. I have to look at the history and paste the command from there. In case you are wondering, I do a lot of command-line awk scripts that cause the line to get quite long.
Is there a way to force the command line to wrap instead of shifting visibility to the right side of the command I am typing?
I have poured through man page options with no luck.
I'm running:
*
*XFree86 4.2.99.903(174)
*KSH 5.2.14.
Thanks.
A: Did you do man ksh?
You want to do a set -o multiline.
Excerpt from man ksh:
multiline:
The built-in editors will use multiple lines on the screen for
lines that are longer than the width of the screen. This may not
work for all terminals.
A: eval $(resize) should do it.
A: If possible, try to break the command down to multiple lines by adding \
ie:
$ mycommand -a foo \
-f bar \
-c dif
A: The simple answer is:
$ set -o multiline
ksh earlier than 5.12, like the ksh shipped with NetBSD 6.1, doesn't have this option. You will have to turn off current Interactive Input Line Editing mode, which is usually emacs:
$ set +o emacs
This turns off a lot of featuers altogether, like tab-completion or the use of 'Up-arrow' key to roll back the previous command.
If you decide to get used to emacs mode somehow, remember ^a goes to the begining of the line ("Home" key won't workk) and ^e goes to the end.
A: I don't know of a way of forcing the shell to wrap, but I would ask why you'd be writing lines that long. With awk scripts, I simply wrap the script in single quotes, and then break the lines where I want. It only gets tricky if you need single quotes in the script -- and diabolical if you need both single and double quotes. Actually, the rule is simple enough: use single quotes to wrap the whole script, and when you want a single quote in the script, write '\''. The first quote terminates the previous single-quoted string; the backslash-single quote yields a single quote; and the last single quote starts a new single quoted string. It really gets hairy if you need to escape those characters for an eval or something similar.
The other question is - why not launch into an editor. Since I'm a die-hard vim nutcase (ok - I've been using vi for over 20 years, so it is easier for me than the alternatives), I have Korn shell set to vi mode (set -o vi), and can do escape-v to launch the editor on whatever I've typed.
A: This is kind of a pragmatic answer, but when that's an issue for me I usually do something like:
strings ~/.history | grep COMMAND
or
strings ~/.history | tail
(The history file has a little bit of binary data in it, hence 'strings')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: .Net Web Service Logging My ideal situation for logging in our web service would be to log all the method calls (authentication as well as data access) with the parameters passed to them as well as errors that may have occured, and have them linked with a single ID that associates them with the same call. In addition, I'd ideally like to be able to control whether all parameters are logged, or if just the method call is logged. I'd like to be able to control if all logins are logged or just the failed ones. Again, all information retrieved in a single request would be linked together via an id (guid or otherwise).
This is my ideal logging situation. If anyone knows how to implement all of this and would be willing to move to the Manchester, NH area... ;)
But seriously, does anyone know how I would go about tying a webservice request received to an error, or method call? My initial attempts involve messing around in a Soap Extension, trying to add a header (soap or html) and what not to pass an arbitrary value from the extension into the service itself. All my attempts have not succeeded.
Our current logging situation has the authentication logging to one table, the method/business calls to another table, and exceptions logging to another table, with no interconnection between them. Timestamps are helpful, sometimes, but not reliable enough to effectively debug. We're currently on .Net 2.0 with the potential to be using 3.5 by the end of the year, so it would be more helpful if replies were kept to 2.0 functionality.
Anyone got any ideas?
A: Use wcf if possible and implement message logging see http://msdn.microsoft.com/en-us/library/ms730064.aspx
<system.diagnostics>
<sources>
<source name="System.ServiceModel.MessageLogging">
<listeners>
<add name="messages"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData="c:\logs\messages.svclog" />
</listeners>
</source>
</sources>
</system.diagnostics>
<system.serviceModel>
<diagnostics>
<messageLogging
logEntireMessage="true"
logMalformedMessages="false"
logMessagesAtServiceLevel="true"
logMessagesAtTransportLevel="false"
maxMessagesToLog="3000"
maxSizeOfMessageToLog="2000"/>
</diagnostics>
</system.serviceModel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How do I dump an entire Python process for later debugging inspection? I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb.
(This is a variation on my question about debugging memleaks in a production system.)
A: There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it.
As for handling the corefile of a Python process, the Python source has a gdbinit file that contains useful macros. It's still a lot more painful than somehow getting into the process itself (with pdb or the interactive interpreter) but it makes life a little easier.
A: If you only care about storing the traceback object (which is all you need to start a debugging session), you can use debuglater (a fork of pydump). It works with recent versions of Python and has a IPython/Jupyter integration.
If you want to store the entire session, look at dill. It has a dump_session, and load_session functions.
Here are two other relevant projects:
*
*python-checkpointing2
*pycrunch-trace
If you're looking for a language agnostic solution, you want to create a core dump file. Here's an example with Python.
A: Someone above said that there is no builtin way to perform this, but that's not entirely true. For an example, you could take a look at the pylons debugging tools. Whene there is an exception, the exception handler saves the stack trace and prints a URL on the console that can be used to retrieve the debugging session over HTTP.
While they're probably keeping these sessions in memory, they're just python objects, so there's nothing to stop you from pickling a stack dump and restoring it later for inspection. It would mean some changes to the app, but it should be possible...
After some research, it turns out the relevant code is actually coming from Paste's EvalException module. You should be able to look there to figure out what you need.
A: It's also possible to write something that would dump all the data from the process, e.g.
*
*Pickler that ignores the objects it can't pickle (replacing them with something else) (e.g. Python: Pickling a dict with some unpicklable items)
*Method that recursively converts everything into serializable stuff (e.g. this, except it needs a check for infinitely recursing objects and do something with those; also it could try dir() and getattr() to process some of the unknown objects, e.g. extension classes).
But leaving a running process with manhole or pylons or something like that certainly seems more convenient when possible.
(also, I wonder if something more convenient was written since this question was first asked)
A: This answer suggests making your program core dump and then continuing execution on another sufficiently similar box.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: How do I rename an entire project in VC++ 2005 I've got a really large project I made for myself and rece3ntly a client asked for their own version of it with some modifications. The project name was rather silly and my client wants the source so I figured it'd be best if I renamed all my files from
sillyname.h
sillyname.cpp
sillyname.dsp
etc..
Unfortunatly after I added everything back together I can't see any way to change the project name itself. Plus now I'm getting this error on compilation.
main.obj : error LNK2001: unresolved external symbol __imp__InitCommonControls@0
Debug/New_Name_Thats_not_so_silly.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
There has to be an easier way to change all this, right?
A: Here is a Step by Step on Steve Andrews' blog (he works on Visual Studio at Microsoft)
A: I haven't verified this, but I've done this a number of times and if my memory serves me right, you can actually use the search-and-replace functionality in VS2005 to rename all instances of the string "X" to "Y" in any type of file.
Then you need to close the solution and change the project (and any other file with the same name regardless of extension) file name(s).
You will obviously need to do a full rebuild afterwards.
A: I find it always annoying too, to do this manually.
So I tried some tools available by googling- two didn't work (VS C++ here), dunno, if they are more useful for C#.
The following tool worked good for me: I have used the trial version, but I will pay 39,- bucks for it. For me it is worth it. It has also a VS add-in. VS 2013 was not supported directly, at least not mentioned, yet, when I looked:
http://www.kinook.com/CopyWiz
In-place rename didn't work (access error), but "rename-while-copying" worked fine.
But I really wonder, if it is so difficult as some programmers claim. For most parts file renaming and a search&replace of all occurences in all text files in the project dir should be a quite easy and working approach. Maybe someone can contibute what shall be so difficult.
The rational part of my brain forbids the dreaming part to program an own tool- I am lucky ! :-)
A: You can simply rename the .vcproj or .dsp file and then either create a new workspace (sln dsw) and include the renamed project or simply chnage the name inside the sln file (it's just xml) I can't remember the format of the old workspace but it's still text.
You can either manually rename and reinclude all the .cpp of edit the project file and rename them in there.
sorry don't know of refactoring tool that will do all this but there probably is one.
A: I assume that in addition to the renamed set of files, you also still maintain a complete "parallel" set of the original files in some other directory, am I right?
Assuming you have both versions, what I would do is:
Get a file comparison tool like Beyond Compare or DiffMerge and compare the old SLN file and the new SLN file side-by-side. Also do this for each "proj" file and any other "config" type files.
It is possible to edit these files by hand. Usually looking at what is different between two copies will help illuminate what you should do to get the second one working.
You might as well start tinkering with the renamed project by hand, anyway, given that it already isn't working. You can't make it much worse. And: you might learn some handy tricks about the XML structure of these files.
Even if you do make small mistakes when hand-tweaking this files, I have repeatedly been very impressed by how Visual Studio handles things. Visual Studio will usually tell you exactly where you got it wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to ignore accents in highlight function I have a micro-mini-search engine that highlights the search terms in my rails app. The search ignores accents and the highlight is case insensitive. Almost perfect.
But, for instance if I have a record with the text "pão de queijo" and searches for "pao de queijo" the record is returned but the iext is not highlighted. Similarly, if I search for "pÃo de queijo" the record is returned but not highlighted properly.
My code is as simple as:
<%= highlight(result_pessoa.observacoes, search_string, '<span style="background-color: yellow;">\1</span>') %>
A: Maybe you're searching UTF-8 strings directly against a MySQL database?
A properly configured MySQL server (and likely any other mainstream database server) will perform correctly with case-insensitive and accent-insensitive comparisons.
That's not the case of Ruby, though. As of version 1.8 Ruby does not support Unicode strings. So you are getting correct results from your database server but the Rails' highlight function, which uses gsub, fails to find your search string. You need to reimplement highlight using an Unicode-aware string library, like ICU4R.
A: I've just submitted a patch to Rails thats solves this.
http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3593-patch-support-for-highlighting-with-ignoring-special-chars
# Highlights one or more +phrases+ everywhere in +text+ by inserting it into
# a <tt>:highlighter</tt> string. The highlighter can be specialized by passing <tt>:highlighter</tt>
# as a single-quoted string with \1 where the phrase is to be inserted (defaults to
# '<strong class="highlight">\1</strong>')
#
# ==== Examples
# highlight('You searched for: rails', 'rails')
# # => You searched for: <strong class="highlight">rails</strong>
#
# highlight('You searched for: ruby, rails, dhh', 'actionpack')
# # => You searched for: ruby, rails, dhh
#
# highlight('You searched for: rails', ['for', 'rails'], :highlighter => '<em>\1</em>')
# # => You searched <em>for</em>: <em>rails</em>
#
# highlight('You searched for: rails', 'rails', :highlighter => '<a href="search?q=\1">\1</a>')
# # => You searched for: <a href="search?q=rails">rails</a>
#
# highlight('Šumné dievčatá', ['šumňe', 'dievca'], :ignore_special_chars => true)
# # => <strong class="highlight">Šumné</strong> <strong class="highlight">dievča</strong>tá
#
# You can still use <tt>highlight</tt> with the old API that accepts the
# +highlighter+ as its optional third parameter:
# highlight('You searched for: rails', 'rails', '<a href="search?q=\1">\1</a>') # => You searched for: <a href="search?q=rails">rails</a>
def highlight(text, phrases, *args)
options = args.extract_options!
unless args.empty?
options[:highlighter] = args[0] || '<strong class="highlight">\1</strong>'
end
options.reverse_merge!(:highlighter => '<strong class="highlight">\1</strong>')
if text.blank? || phrases.blank?
text
else
haystack = text.clone
match = Array(phrases).map { |p| Regexp.escape(p) }.join('|')
if options[:ignore_special_chars]
haystack = haystack.mb_chars.normalize(:kd)
match = match.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]+/n, '').gsub(/\w/, '\0[^\x00-\x7F]*')
end
highlighted = haystack.gsub(/(#{match})(?!(?:[^<]*?)(?:["'])[^<>]*>)/i, options[:highlighter])
highlighted = highlighted.mb_chars.normalize(:kc) if options[:ignore_special_chars]
highlighted
end
end
A: it sounds like you are using two different methods for deciding whether a match has occured or not: one for your search, and one for the hilight. Use the same method as your search for your highlighting and it should pick it up, no?
A: Here's my article that explains elegant solution where you don't need Rails or ActiveSupport.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I programmatically repair (not merely compact) an Access .mdb file? I have a corrupt database. If I open it in MS Access, MS Access offers to repair it, and it succeeds.
How can I do that with code? On a machine where MS Access is not installed.
I know from trying it that JRO.JetEngine.CompactDatabase does NOT work.
In other words, I want to do what Access or JETCOMP.exe is doing, not what JRO.JetEngine.CompactDatabase is doing.
A: You need to go to http://support.microsoft.com and search for the JetComp.exe utility, which will attempt to repair and compact your MDB without opening the file. The reason none of the suggestions above work is because they have to open the MDB to do their work, whereas JetComp doesn't open the file, but operates on it structurally.
If it can't recover your file (which does happen), then you'll have to go to a data recovery service. I recommend Peter Miller of PKSolutions.com.
A: Command-line switch for opening a .mdb file:
/compact
It repairs and compacts the database file.
If you leave out a target file name following the /compact switch, the file is compacted to the original name and folder. To compact to a different name, specify a target file.
A: Have you tried DBEngine.RepairDatabase [my.mdb]? (which doesn't seem to work any more even when you reference an earlier version)
However, if is happening so often that you need to code it, you probably have a bigger problem you should be solving first.
If you are willing to use separate utility, how about the Jetcomp.exe utility (http://support.microsoft.com/kb/295334 ). It is supposed to "be able to recover some databases that the Microsoft Access compact utility and the CompactDatabase method cannot." In which case, all you need to do is execute the external application.
e.g.,
Call Shell("Jetcomp.exe <arguments>")
A: I'm not a MS Acccess guru, but it appears as though this utility contains the DLLs you'd need to compact and repair a corrupt database file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which Haskell package contains given module I know a Haskell module name, but I can't figure out in what package it is defined. This is bad because I can't compile without a package exposing this module.
Specificaly it is Text.Regex that I can't locate, but I would like to know how to solve that problem in general.
A: If you're using Cabal and you have the package installed, you can just try to compile it with cabal build, and Cabal will inform you of which package you forgot to add to your dependencies:
Main.hs:1:8:
Could not find module `Text.Regex':
It is a member of the hidden package `regex-compat-0.93.1'.
Perhaps you need to add `regex-compat' to the build-depends in your .cabal file.
Use -v to see a list of the files searched for.
A: http://www.haskell.org/ghc/docs/latest/html/users_guide/packages.html
ghc-pkg find-module Text.Regex
But that only works for (a) recent GHCs, and (b) packages installed on your system.
You can also grep through the package file (e.g. /usr/lib/ghc-6.8.2/package.conf) to see what's installed.
You can also use either the haskell API search engines hoogle or the hackage search engine hayoo.
Text.Regex is in the package regex-base, and a few others built on top of it.
A: The best tools are:
*
*hoogle; or
*hayoo.
Both are search engines for Haskell modules and functions.
A: If you are using Debian and the Debian-provided packages, there is a global documentation index at /usr/share/doc/ghc-doc/html/libraries/index.html which lists the package in the last column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: sql 2005 rollback transaction I just did a delete from table
How do I roll back or undelete the rows??
A: if you called begin transaction before you did it, and have not yet called commit, then you can call rollback, otherwise... you're gonna have to restore
A: Assuming you have a recent full backup of your database, backup your transaction log now, and restore it to a point in time prior to your delete. If there's live data that's been changed since then, you'll probably want to restore it to a different DB, and manually insert the deleted records.
From memory, so syntax may be a bit off - but you get the idea:
BACKUP LOG DBName
TO DISK='C:\DBName.TRN'
GO
RESTORE DATABASE DBName2
FROM DISK='C:\DBName.BAK'
WITH
MOVE 'DBName.MDF' TO 'C:\DBName2.MDF',
MOVE 'DBName.LDF' TO 'C:\DBName2.LDF',
NORECOVERY
GO
RESTORE LOG DBName2
FROM DISK='C:\DBName.TRN'
WITH
RECOVERY,
STOPAT = '09/26/2008 17:00'
GO
A: restore from a backup.
A: This will do the trick, assuming you have the money: http://www.lumigent.com/products/log_explorer.html
Apart from that, backups, like everyone else said
A: if you prefaced the delete with a begin tran you just use rollback tran
if not, start looking for your backups.
A: rollback;
But only if you were in a transaction..
A: I did this once on a database with no backups and was able to recover the data using a utility that replayed all the transaction log entries. Fortunately in my situation I had never truncated the transaction log.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Programmatically Lighten a Color Motivation
I'd like to find a way to take an arbitrary color and lighten it a few shades, so that I can programatically create a nice gradient from the one color to a lighter version. The gradient will be used as a background in a UI.
Possibility 1
Obviously I can just split out the RGB values and increase them individually by a certain amount. Is this actually what I want?
Possibility 2
My second thought was to convert the RGB to HSV/HSB/HSL (Hue, Saturation, Value/Brightness/Lightness), increase the brightness a bit, decrease the saturation a bit, and then convert it back to RGB. Will this have the desired effect in general?
A: Convert it to RGB and linearly interpolate between the original color and the target color (often white). So, if you want 16 shades between two colors, you do:
for(i = 0; i < 16; i++)
{
colors[i].R = start.R + (i * (end.R - start.R)) / 15;
colors[i].G = start.G + (i * (end.G - start.G)) / 15;
colors[i].B = start.B + (i * (end.B - start.B)) / 15;
}
A: In order to get a lighter or a darker version of a given color you should modify its brightness. You can do this easily even without converting your color to HSL or HSB color. For example to make a color lighter you can use the following code:
float correctionFactor = 0.5f;
float red = (255 - color.R) * correctionFactor + color.R;
float green = (255 - color.G) * correctionFactor + color.G;
float blue = (255 - color.B) * correctionFactor + color.B;
Color lighterColor = Color.FromArgb(color.A, (int)red, (int)green, (int)blue);
If you need more details, read the full story on my blog.
A: As Wedge said, you want to multiply to make things brighter, but that only works until one of the colors becomes saturated (i.e. hits 255 or greater). At that point, you can just clamp the values to 255, but you'll be subtly changing the hue as you get lighter. To keep the hue, you want to maintain the ratio of (middle-lowest)/(highest-lowest).
Here are two functions in Python. The first implements the naive approach which just clamps the RGB values to 255 if they go over. The second redistributes the excess values to keep the hue intact.
def clamp_rgb(r, g, b):
return min(255, int(r)), min(255, int(g)), min(255, int(b))
def redistribute_rgb(r, g, b):
threshold = 255.999
m = max(r, g, b)
if m <= threshold:
return int(r), int(g), int(b)
total = r + g + b
if total >= 3 * threshold:
return int(threshold), int(threshold), int(threshold)
x = (3 * threshold - total) / (3 * m - total)
gray = threshold - x * m
return int(gray + x * r), int(gray + x * g), int(gray + x * b)
I created a gradient starting with the RGB value (224,128,0) and multiplying it by 1.0, 1.1, 1.2, etc. up to 2.0. The upper half is the result using clamp_rgb and the bottom half is the result with redistribute_rgb. I think it's easy to see that redistributing the overflows gives a much better result, without having to leave the RGB color space.
For comparison, here's the same gradient in the HLS and HSV color spaces, as implemented by Python's colorsys module. Only the L component was modified, and clamping was performed on the resulting RGB values. The results are similar, but require color space conversions for every pixel.
A: Converting to HS(LVB), increasing the brightness and then converting back to RGB is the only way to reliably lighten the colour without effecting the hue and saturation values (ie to only lighten the colour without changing it in any other way).
A: I would go for the second option. Generally speaking the RGB space is not really good for doing color manipulation (creating transition from one color to an other, lightening / darkening a color, etc). Below are two sites I've found with a quick search to convert from/to RGB to/from HSL:
*
*from the "Fundamentals of Computer Graphics"
*some sourcecode in C# - should be easy to adapt to other programming languages.
A: A very similar question, with useful answers, was asked previously:
How do I determine darker or lighter color variant of a given color?
Short answer: multiply the RGB values by a constant if you just need "good enough", translate to HSV if you require accuracy.
A: I used Andrew's answer and Mark's answer to make this (as of 1/2013 no range input for ff).
function calcLightness(l, r, g, b) {
var tmp_r = r;
var tmp_g = g;
var tmp_b = b;
tmp_r = (255 - r) * l + r;
tmp_g = (255 - g) * l + g;
tmp_b = (255 - b) * l + b;
if (tmp_r > 255 || tmp_g > 255 || tmp_b > 255)
return { r: r, g: g, b: b };
else
return { r:parseInt(tmp_r), g:parseInt(tmp_g), b:parseInt(tmp_b) }
}
A: In C#:
public static Color Lighten(Color inColor, double inAmount)
{
return Color.FromArgb(
inColor.A,
(int) Math.Min(255, inColor.R + 255 * inAmount),
(int) Math.Min(255, inColor.G + 255 * inAmount),
(int) Math.Min(255, inColor.B + 255 * inAmount) );
}
I've used this all over the place.
A: I've done this both ways -- you get much better results with Possibility 2.
Any simple algorithm you construct for Possibility 1 will probably work well only for a limited range of starting saturations.
You would want to look into Poss 1 if (1) you can restrict the colors and brightnesses used, and (2) you are performing the calculation a lot in a rendering.
Generating the background for a UI won't need very many shading calculations, so I suggest Poss 2.
-Al.
A: ControlPaint class in System.Windows.Forms namespace has static methods Light and Dark:
public static Color Dark(Color baseColor, float percOfDarkDark);
These methods use private implementation of HLSColor. I wish this struct was public and in System.Drawing.
Alternatively, you can use GetHue, GetSaturation, GetBrightness on Color struct to get HSB components. Unfortunately, I didn't find the reverse conversion.
A: IF you want to produce a gradient fade-out, I would suggest the following optimization: Rather than doing RGB->HSB->RGB for each individual color you should only calculate the target color. Once you know the target RGB, you can simply calculate the intermediate values in RGB space without having to convert back and forth. Whether you calculate a linear transition of use some sort of curve is up to you.
A: Method 1: Convert RGB to HSL, adjust HSL, convert back to RGB.
Method 2: Lerp the RGB colour values - http://en.wikipedia.org/wiki/Lerp_(computing)
See my answer to this similar question for a C# implementation of method 2.
A: Pretend that you alpha blended to white:
oneMinus = 1.0 - amount
r = amount + oneMinus * r
g = amount + oneMinus * g
b = amount + oneMinus * b
where amount is from 0 to 1, with 0 returning the original color and 1 returning white.
You might want to blend with whatever the background color is if you are lightening to display something disabled:
oneMinus = 1.0 - amount
r = amount * dest_r + oneMinus * r
g = amount * dest_g + oneMinus * g
b = amount * dest_b + oneMinus * b
where (dest_r, dest_g, dest_b) is the color being blended to and amount is from 0 to 1, with zero returning (r, g, b) and 1 returning (dest.r, dest.g, dest.b)
A: I didn't find this question until after it became a related question to my original question.
However, using insight from these great answers. I pieced together a nice two-liner function for this:
Programmatically Lighten or Darken a hex color (or rgb, and blend colors)
Its a version of method 1. But with over saturation taken into account. Like Keith said in his answer above; use Lerp to seemly solve the same problem Mark mentioned, but without redistribution. The results of shadeColor2 should be much closer to doing it the right way with HSL, but without the overhead.
A: A bit late to the party, but if you use javascript or nodejs, you can use tinycolor library, and manipulate the color the way you want:
tinycolor("red").lighten().desaturate().toHexString() // "#f53d3d"
A: I would have tried number #1 first, but #2 sounds pretty good. Try doing it yourself and see if you're satisfied with the results, it sounds like it'll take you maybe 10 minutes to whip up a test.
A: Technically, I don't think either is correct, but I believe you want a variant of option #2. The problem being that taken RGB 990000 and "lightening" it would really just add onto the Red channel (Value, Brightness, Lightness) until you got to FF. After that (solid red), it would be taking down the saturation to go all the way to solid white.
The conversions get annoying, especially since you can't go direct to and from RGB and Lab, but I think you really want to separate the chrominance and luminence values, and just modify the luminence to really achieve what you want.
A: Here's an example of lightening an RGB colour in Python:
def lighten(hex, amount):
""" Lighten an RGB color by an amount (between 0 and 1),
e.g. lighten('#4290e5', .5) = #C1FFFF
"""
hex = hex.replace('#','')
red = min(255, int(hex[0:2], 16) + 255 * amount)
green = min(255, int(hex[2:4], 16) + 255 * amount)
blue = min(255, int(hex[4:6], 16) + 255 * amount)
return "#%X%X%X" % (int(red), int(green), int(blue))
A: This is based on Mark Ransom's answer.
Where the clampRGB function tries to maintain the hue, it however miscalculates the scaling to keep the same luminance. This is because the calculation directly uses sRGB values which are not linear.
Here's a Java version that does the same as clampRGB (although with values ranging from 0 to 1) that maintains luminance as well:
private static Color convertToDesiredLuminance(Color input, double desiredLuminance) {
if(desiredLuminance > 1.0) {
return Color.WHITE;
}
if(desiredLuminance < 0.0) {
return Color.BLACK;
}
double ratio = desiredLuminance / luminance(input);
double r = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getRed()) * ratio;
double g = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getGreen()) * ratio;
double b = Double.isInfinite(ratio) ? desiredLuminance : toLinear(input.getBlue()) * ratio;
if(r > 1.0 || g > 1.0 || b > 1.0) { // anything outside range?
double br = Math.min(r, 1.0); // base values
double bg = Math.min(g, 1.0);
double bb = Math.min(b, 1.0);
double rr = 1.0 - br; // ratios between RGB components to maintain
double rg = 1.0 - bg;
double rb = 1.0 - bb;
double x = (desiredLuminance - luminance(br, bg, bb)) / luminance(rr, rg, rb);
r = 0.0001 * Math.round(10000.0 * (br + rr * x));
g = 0.0001 * Math.round(10000.0 * (bg + rg * x));
b = 0.0001 * Math.round(10000.0 * (bb + rb * x));
}
return Color.color(toGamma(r), toGamma(g), toGamma(b));
}
And supporting functions:
private static double toLinear(double v) { // inverse is #toGamma
return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
}
private static double toGamma(double v) { // inverse is #toLinear
return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1.0 / 2.4) - 0.055;
}
private static double luminance(Color c) {
return luminance(toLinear(c.getRed()), toLinear(c.getGreen()), toLinear(c.getBlue()));
}
private static double luminance(double r, double g, double b) {
return r * 0.2126 + g * 0.7152 + b * 0.0722;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
}
|
Q: Java, unicode and fonts I've looked at the java documentation and scoured the net for information on java's support for international characters with specific fonts (such as Monospace), but haven't been able to get a clear concrete answer.
There has been a change between java 1.4 and java 1.5/1.6. For example, in java 1.4 if you set the font on a JTextArea to Monospace, it won't be able to handle foreign characters (get rectangles instead), but in java 1.5/1.6 it seems to work fine.
Are these differences/improved support clearly documented anywhere?
Thanks
A: From Internationalization Enhancements:
Multilingual Text Rendering
To render multilingual text, using logical fonts, 2D now takes advantage of installed host OS fonts for all supported writing systems. For example, if you run in a Thai locale environment, but have Korean fonts installed, both Thai and Korean are rendered. The JRE now also automatically detects physical fonts that are installed into its lib/fonts/fallback directory and adds these physical fonts to all logical fonts for 2D rendering.
Use of Unicode APIs on Windows
AWT now uses the Unicode APIs on Windows 2000/XP. As a result, some of its components can handle text without being restricted by Windows locale settings. For example, AWT text components can accept and display text in the Devanagari writing system regardless of the Windows locale settings. (emphasis mine)
A: How "foreign" are these characters? Most Latin-based fonts can handle at least the accented letters and other characters in the upper half of ISO-8859-1, but I don't think you can reasonably count on support for anything beyond that.
Your best bet is usually to let the user choose from a list of supported fonts, which you retrieve from the underlying OS. If can't do that, or don't want to, you can take the CSS approach: iterate through a list of acceptable fonts and use the first one you find installed.
To populate the list, just Google for "programmer fonts" or "monospaced fonts". I never liked any of Java's logical fonts, especially Monospace, which is either Courier or Courier New on a Windows box. I quit using it years ago.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there an issue sending XML via WCF? Suppose you have an XElement or an XmlElment or even a string containing xml that you want to send via WCF. Are there any special precautions you have to take? The question just came up, what happens when, within the xml message, you transmit an xml document declaration (<?xml version=’1.0’ ?>), which may happen if serializing an XmlDocument...
A: Just thought I'd add that in most cases these will be configuration changes, unless you're doing all your binding setup through code.
Specifically, you'll probably need to adjust the MaxReceivedMessageSize property of the binding and the reader quotas on the receiving side.
This is not related specifically to sending XML, by the way, it just comes up whenever you're sending largish messages because the default quotas are very conservative (64kb max message size, for example).
A: I hade no problem sending XML as a string with WCF. If your XML exceed a few Kb, you must make changes in client&server to allow larger data amounts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Operator overloading for C++ maps I need help understanding some C++ operator overload statements. The class is declared like this:
template <class key_t, class ipdc_t>
class ipdc_map_template_t : public ipdc_lockable_t
{
...
typedef map<key_t,
ipdc_t*,
less<key_t>> map_t;
...
The creator of the class has created an iterator for the internal map structure:
struct iterator : public map_t::iterator
{
iterator() {}
iterator(const map_t::iterator & it)
: map_t::iterator(it) {}
iterator(const iterator & it)
: map_t::iterator(
*static_cast<const map_t::iterator *>(&it)) {}
operator key_t() {return ((this->operator*()).first);} // I don't understand this.
operator ipdc_t*() const {return ((this->operator*()).second);} // or this.
};
And begin() and end() return the begin() and end() of the map:
iterator begin() {IT_ASSERT(is_owner()); return map.begin();}
iterator end() {return map.end();}
My question is, if I have an iterator, how do I use those overloads to get the key and the value?
ipdc_map_template_t::iterator iter;
for( iter = my_instance.begin();
iter != my_instance.end();
++iter )
{
key_t my_key = ??????;
ipdc_t *my_value = ??????;
}
A: These are typecast operators, so you can do this:
{
key_t key = iter;
ipdc_t *val = iter;
}
Or, since ipdc_map_template::iterator is a subclass of std::map::iterator, you can still use the original accessors (which I find more readable):
{
key_t key = (*iter).first;
ipdc_t *val = (*iter).second;
// or, equivalently
key_t key = iter->first;
ipdc_t *val = iter->second;
}
A: The creator of the class has overridden the cast operators.
So by just assigning the iter to an object of the correct type it should auto cast itself via the methods into the correct values.
N.B.: The value type is being stored as a pointer. So when you extract the value you need to specify the pointer to the value type that you specified in the map interface.
typedef ipdc_map_template_t<int,std::string> MyMap;
MyMap mymap;
for(MyMap::iterator iter = mymap.begin();
iter != mymap.end();
++iter )
{
int my_key = iter;
std::string* my_value = iter;
}
Not sure I agree with the direction taken here.
Does this make the code more readable? I would stick with the old fashioned map iterator sounds more usable. Is this container being defined in some specialized library that you need, or would it be beneficial to look at the boost pointer containers?
A: operator key_t() and operator ipdc_t*() are both cast definitions. So, given an iterator as defined in the class, you should be able to simply assign your variables:
ipdc_map_template_t::iterator iter;
for( iter = my_instance.begin();
iter != my_instance.end();
++iter )
{
key_t my_key = iter;
ipdc_t my_value = iter;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Best place for log files in an in-house IT environment All of my users are a short walk down the hall, and all of my programs run on workstations on the same LAN. Some years ago, I had the staff write the log files for all of their programs to a shared folder hierarchy, naming each log file after the machine name in a sub-directory named after the app.
But this arrangement wasn't that great, since if the file server went down then none of the programs anywhere could write logs. Yet keeping logs local to each workstation would make it a pain in the ass to read them whenever we had to debug a problem.
We tried making a DNS alias for the logging fileserver so we could point it to a backup machine when necessary, but DNS aliases don't work with Windows file shares.
Putting the path to the shared log folder in each program isn't great--even if it's field configurable--because we have dozens of programs on dozens of machines.
We've also looked into using Microsoft's distributed file system, but the price is ridiculous.
I'd like a way to gather the logging for many programs on the local network into one place so I can tail and analyze them without paying a visit to the remote machine. We use .Net for all our programs.
Edit: I'd like to avoid setting up a file-share on each user's workstation, or solutions that trawl for logs each night, since I want to be able to read fresh logs on demand, or moments after a problem is reported.
A: In an IT environment which I worked in a few years back, we had each machine write it's log files locally and wipe them every five days. The server would log in every night to grab the latest logs from each machine. If the server went down, it would just grab two days worth of logs from everyone. If a client went down, it's log could be grabbed the next day as well.
A: You can use MSMQ. Write your logs to a MSMQ queue, and then have a service that picks these logs up and puts them in a database or out to a file in a central location if you want. It wouldn't be instantaneous, but you could tell it to run whenever you want to get new log entries. Plus it would be reliable since it uses MSMQ.
A: Our shop has had good experience with storing logs in a database table. You can schedule cleanup as a database job whenever you feel like it, to prevent it from getting too large.
A: We use the approach of logging to a known location locally which is shared. Then it's easy to have a second process pull these logs for later processing (dump to database, collect and archive etc). If the collection process dies, then nothing is really is affected.
Make sure you don't have a central point of failure. I've seen examples of this that used a central logging database that all apps depended on and when it went down everything else did too. Not clever.
A: Can you have the log files writtin to peoples local machine and then have a script that pulls them to a common file server as a nightly batch job?
A: What about having your application's logger as a subscriber service (using remoting). Then implement LogServers which subscribe to the application. When the app has something to log, it sends it to the subscribers. If there is a problem, such as the subscriber not responding/dead and you have no working subscribers, write locally but sound an alarm. E.g. a multi-machine version of the TraceListener and Debug classes.
You'd almost certainly want the application to send log messages from a different thread to the rest of your application.
A: We wrote a single application that hosts other applications (plug-in architecture). When an exception occurs, the necessary information is written to an XML file on the user's machine (which is named <USERNAME>.xml). Either upon our request or when the application exits, it sends the XML to a web service where it writes the files to a location where we can go and check them.
If the web service is down, it's no big deal since the XML file is still on the user's machine and will get uploaded the next time they run the application.
A: DFS is included with Windows Server, and you can regedit to enable NetBIOS with a CNAME.
I've also tried Splunk for pulling and analyzing log files, but it's a bit of a CPU hog and I couldn't spare the horsepower. Otherwise, though, it was a pretty nice product.
A: write to a database also (like CALM) so you only have to troll the log files when the database was down
A: I agree with craigb's comment. Creating additional single points of failure should be avoided in a LAN environment.
My preference is to have the clients log locally, and then copy these log files to a central location. In this case if your log server falls over then there won't be any serious outage. Additionally, sometimes writing a log file to a network can be performance bottleneck.
Another issue with the central log server is if one application misbehaves, it can take down all the apps. I've seen countless bugs, which when encountered cause the program to enter an infinite loop and spew logs messages until the device fills up.
If you really, want the central logging, for compliance reasons or something else, I would either write to a network drive, or write to the socket in the fashion of syslogd. Since syslogd is quite standard, you shouldn't have any trouble setting one up on a server, and there's plenty of example code and libraries to write to it. One can even configure a hardware load balance to sit in front of two or more syslogd servers, providing higher availability of the service.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Antlr: Simplest way to recognize dates and numbers? What is the simplest (shortest, fewest rules, and no warnings) way to parse both valid dates and numbers in the same grammar? My problem is that a lexer rule to match a valid month (1-12) will match any occurrence of 1-12. So if I just want to match a number, I need a parse rule like:
number: (MONTH|INT);
It only gets more complex when I add lexer rules for day and year. I want a parse rule for date like this:
date: month '/' day ( '/' year )? -> ^('DATE' year month day);
I don't care if month,day & year are parse or lexer rules, just so long as I end up with the same tree structure. I also need to be able to recognize numbers elsewhere, e.g.:
foo: STRING OP number -> ^(OP STRING number);
STRING: ('a'..'z')+;
OP: ('<'|'>');
A: The problem is that you seem to want to perform both syntactical and semantical checking in your lexer and/or your parser. It's a common mistake, and something that is only possible in very simple languages.
What you really need to do is accept more broadly in the lexer and parser, and then perform semantic checks. How strict you are in your lexing is up to you, but you have two basic options, depending on whether or not you need to accept zeroes preceding your days of the month: 1) Be really accepting for your INTs, 2) define DATENUM to only accept those tokens that are valid days, yet not valid INTs. I recommend the second because there will be less semantic checks necessary later in the code (since INTs will then be verifiable at the syntax level and you'll only need to perform semantic checks on your dates. The first approach:
INT: '0'..'9'+;
The second approach:
DATENUM: '0' '1'..'9';
INT: '0' | SIGN? '1'..'9' '0'..'9'*;
After accepting using these rules in the lexer, your date field would be either:
date: INT '/' INT ( '/' INT )?
or:
date: (INT | DATENUM) '/' (INT | DATENUM) ('/' (INT | DATENUM) )?
After that, you would perform a semantic run over your AST to make sure that your dates are valid.
If you're dead set on performing semantic checks in your grammar, however, ANTLR allows semantic predicates in the parser, so you could make a date field that checks the values like this:
date: month=INT '/' day=INT ( year='/' INT )? { year==null ? (/* First check /*) : (/* Second check */)}
When you do this, however, you are embedding language specific code in your grammar, and it won't be portable across targets.
A: Using ANTLR4, here is a simple combined grammar that I used. It makes use of the lexer to match simple tokens only, leaving the parser rules to interpret dates vs numbers.
// parser rules
date
: INT SEPARATOR month SEPARATOR INT
| INT SEPARATOR month SEPARATOR INT4
| INT SEPARATOR INT SEPARATOR INT4;
month : JAN | FEB | MAR | APR | MAY | JUN | JUL | AUG | SEP | OCT | NOV | DEC ;
number : FLOAT | INT | INT4 ;
// lexer rules
FLOAT : DIGIT+ '.' DIGIT+ ;
INT4 : DIGIT DIGIT DIGIT DIGIT;
INT : DIGIT+;
JAN : [Jj][Aa][Nn] ;
FEB : [Ff][Ee][Bb] ;
MAR : [Mm][Aa][Rr] ;
APR : [Aa][Pp][Rr] ;
MAY : [Mm][Aa][Yy] ;
JUN : [Jj][Uu][Nn] ;
JUL : [Jj][Uu][Ll] ;
AUG : [Aa][Uu][Gg] ;
SEP : [Ss][Ee][Pp] ;
OCT : [Oo][Cc][Tt] ;
NOV : [Nn][Oo][Vv] ;
DEC : [Dd][Ee][Cc] ;
SEPARATOR : [/\\\-] ;
fragment DIGIT : [0-9];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Application Title Cut Off In VB6 Platform: Windows XP
Development Platform: VB6
When trying to set an application title via the Project Properties dialog on the Make tab, it seems to silently cut off the title at a set number of characters. Also tried this via the App.Title property and it seems to suffer from the same problem. I wouldn't care about this but the QA Dept. insists that we need to get the entire title displayed.
Does anyone have a workaround or fix for this?
Edit: To those who responded about a 40 character limit, that's what I sort of suspected--hence my question about a possible workaround :-) .
Actually I posted this question to try to help a fellow developer so when I see her on Monday, I'll point her to all of your excellent suggestions and see if any of them help her get this straightened out. I do know that for some reason some of the dialogs displayed by the app seem to pick up the string from the App.Title setting which is why she had asked me about the limitation on the length of the string.
I just wish I could find something definitive from Microsoft (like some sort of KB note) so she could show it to our QA department so they'd realize this is simply a limitation of VB.
A: The MsgBox-Function takes a parameter for the title. If you dont want to change every single call to the MsgBox-Function, you could "override" the default behavior:
Function MsgBox(Prompt, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title, Optional HelpFile, Optional Context) As VbMsgBoxResult
If IsMissing(Title) Then Title = String(40, "x") & "abc"
MsgBox = Interaction.MsgBox(Prompt, Buttons, Title, HelpFile, Context)
End Function
Edit: As Mike Spross notes: This only hides the normal MsgBox-Function. If you wanted to access your custom MsgBox from another project, you would have to qualify it.
A: I just created a Standard EXE project in the IDE and typed text into the application title field under the Project Properties Make tab until I filled the field. From this quick test, it appears that App.Title is limited to 40 characters. Next I tried it in code by putting the following code in the default form (Form1) created for the project:
Private Sub Form_Load()
App.Title = String(41, "X")
MsgBox Len(App.Title)
End Sub
This quick test confirms the 40-characater limit, because the MsgBox displays 40, even though the code attempts to set App.Title to a 41-character string.
If it's really important to get the full string to display in the titlebar of a Form, then only way I can think of to ensure that the entire title is displayed would be to get the width of the titlebar text and use that to increase the width of your Form so that it can accommodate the complete title string. I may come back and post code for this if I can find the right API incantations, but it might look something like this in the Form_Load event:
Dim nTitleBarTextWidth As Long
Dim nNewWidth As Long
Me.Caption = "My really really really really really long app title here"
' Get titlebar text width (somehow) '
nTitleBarTextWidth = GetTitleBarTextWidth()
' Compute the new width for the Form such that the title will fit within it '
' (May have to add a constant to this to make sure the title fits correctly) '
nNewWidth = Me.ScaleX(nTitleBarTextWidth, vbPixels, Me.ScaleMode)
' If the new width is bigger than the forms current size, use the new width '
If nNewWidth > Me.Width Then
Form.Width = nNewWidth
End If
A: One solution using the Windows API
Disclaimer: IMHO this seems like overkill just to meet the requirement stated in the question, but in the spirit of giving a (hopefully) complete answer to the problem, here goes nothing...
Here is a working version I came up with after looking around in MSDN for awhile, until I finally came upon an article on vbAccelerator that got my wheels turning.
*
*See the vbAccelerator page for the original article (not directly related to the question, but there was enough there for me to formulate an answer)
The basic premise is to first calculate the width of the form's caption text and then to use GetSystemMetrics to get the width of various bits of the window, such as the border and window frame width, the width of the Minimize, Maximize, and Close buttons, and so on (I split these into their own functions for readibility/clarity). We need to account for these parts of the window in order to calculate an accurate new width for the form.
In order to accurately calculate the width ("extent") of the form's caption, we need to get the system caption font, hence the SystemParametersInfo and CreateFontIndirect calls and related goodness.
The end result all this effort is the GetRecommendedWidth function, which calculates all of these values and adds them together, plus a bit of extra padding so that there is some space between the last character of the caption and the control buttons. If this new width is greater than the form's current width, GetRecommendedWidth will return this (larger) width, otherwise, it will return the Form's current width.
I only tested it briefly, but it appears to work fine. Since it uses Windows API functions, however, you may want to exercise caution, especially since it's copying memory around. I didn't add robust error-handling, either.
By the way, if someone has a cleaner, less-involved way of doing this, or if I missed something in my own code, please let me know.
To try it out, paste the following code into a new module
Option Explicit
Private Type SIZE
cx As Long
cy As Long
End Type
Private Const LF_FACESIZE = 32
'NMLOGFONT: This declaration came from vbAccelerator (here is what he says about it):'
' '
' For some bizarre reason, maybe to do with byte '
' alignment, the LOGFONT structure we must apply '
' to NONCLIENTMETRICS seems to require an LF_FACESIZE '
' 4 bytes smaller than normal: '
Private Type NMLOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE - 4) As Byte
End Type
Private Type LOGFONT
lfHeight As Long
lfWidth As Long
lfEscapement As Long
lfOrientation As Long
lfWeight As Long
lfItalic As Byte
lfUnderline As Byte
lfStrikeOut As Byte
lfCharSet As Byte
lfOutPrecision As Byte
lfClipPrecision As Byte
lfQuality As Byte
lfPitchAndFamily As Byte
lfFaceName(LF_FACESIZE) As Byte
End Type
Private Type NONCLIENTMETRICS
cbSize As Long
iBorderWidth As Long
iScrollWidth As Long
iScrollHeight As Long
iCaptionWidth As Long
iCaptionHeight As Long
lfCaptionFont As NMLOGFONT
iSMCaptionWidth As Long
iSMCaptionHeight As Long
lfSMCaptionFont As NMLOGFONT
iMenuWidth As Long
iMenuHeight As Long
lfMenuFont As NMLOGFONT
lfStatusFont As NMLOGFONT
lfMessageFont As NMLOGFONT
End Type
Private Enum SystemMetrics
SM_CXBORDER = 5
SM_CXDLGFRAME = 7
SM_CXFRAME = 32
SM_CXSCREEN = 0
SM_CXICON = 11
SM_CXICONSPACING = 38
SM_CXSIZE = 30
SM_CXEDGE = 45
SM_CXSMICON = 49
SM_CXSMSIZE = 52
End Enum
Private Const SPI_GETNONCLIENTMETRICS = 41
Private Const SPI_SETNONCLIENTMETRICS = 42
Private Declare Function GetTextExtentPoint32 Lib "gdi32" Alias "GetTextExtentPoint32A" _
(ByVal hdc As Long, _
ByVal lpszString As String, _
ByVal cbString As Long, _
lpSize As SIZE) As Long
Private Declare Function GetSystemMetrics Lib "user32" (ByVal nIndex As SystemMetrics) As Long
Private Declare Function SystemParametersInfo Lib "user32" Alias "SystemParametersInfoA" ( _
ByVal uAction As Long, _
ByVal uParam As Long, _
lpvParam As Any, _
ByVal fuWinIni As Long) As Long
Private Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
Private Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
Private Declare Function CreateFontIndirect Lib "gdi32" Alias "CreateFontIndirectA" (lpLogFont As LOGFONT) As Long
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Function GetCaptionTextWidth(ByVal frm As Form) As Long
'-----------------------------------------------'
' This function does the following: '
' '
' 1. Get the font used for the forms caption '
' 2. Call GetTextExtent32 to get the width in '
' pixels of the forms caption '
' 3. Convert the width from pixels into '
' the scaling mode being used by the form '
' '
'-----------------------------------------------'
Dim sz As SIZE
Dim hOldFont As Long
Dim hCaptionFont As Long
Dim CaptionFont As LOGFONT
Dim ncm As NONCLIENTMETRICS
ncm.cbSize = LenB(ncm)
If SystemParametersInfo(SPI_GETNONCLIENTMETRICS, 0, ncm, 0) = 0 Then
' What should we do if we the call fails? Change as needed for your app,'
' but this call is unlikely to fail anyway'
Exit Function
End If
CopyMemory CaptionFont, ncm.lfCaptionFont, LenB(CaptionFont)
hCaptionFont = CreateFontIndirect(CaptionFont)
hOldFont = SelectObject(frm.hdc, hCaptionFont)
GetTextExtentPoint32 frm.hdc, frm.Caption, Len(frm.Caption), sz
GetCaptionTextWidth = frm.ScaleX(sz.cx, vbPixels, frm.ScaleMode)
'clean up, otherwise bad things will happen...'
DeleteObject (SelectObject(frm.hdc, hOldFont))
End Function
Private Function GetControlBoxWidth(ByVal frm As Form) As Long
Dim nButtonWidth As Long
Dim nButtonCount As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
nButtonCount = 1 'close button is always present'
nButtonWidth = GetSystemMetrics(SM_CXSIZE) 'get width of a single button in the titlebar'
' account for min and max buttons if they are visible'
If frm.MinButton Then nButtonCount = nButtonCount + 1
If frm.MaxButton Then nButtonCount = nButtonCount + 1
nFinalWidth = nButtonWidth * nButtonCount
End If
'convert to whatever scale the form is using'
GetControlBoxWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetIconWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog, vbSizable:
'we have an icon, gets its width'
nFinalWidth = GetSystemMetrics(SM_CXSMICON)
Case Else:
'no icon present, so report zero width'
nFinalWidth = 0
End Select
End If
'convert to whatever scale the form is using'
GetIconWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetFrameWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.BorderStyle
Case vbFixedSingle, vbFixedDialog:
nFinalWidth = GetSystemMetrics(SM_CXDLGFRAME)
Case vbSizable:
nFinalWidth = GetSystemMetrics(SM_CXFRAME)
End Select
End If
'convert to whatever scale the form is using'
GetFrameWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Private Function GetBorderWidth(ByVal frm As Form) As Long
Dim nFinalWidth As Long
If frm.ControlBox Then
Select Case frm.Appearance
Case 0 'flat'
nFinalWidth = GetSystemMetrics(SM_CXBORDER)
Case 1 '3D'
nFinalWidth = GetSystemMetrics(SM_CXEDGE)
End Select
End If
'convert to whatever scale the form is using'
GetBorderWidth = frm.ScaleX(nFinalWidth, vbPixels, frm.ScaleMode)
End Function
Public Function GetRecommendedWidth(ByVal frm As Form) As Long
Dim nNewWidth As Long
' An abitrary amount of extra padding so that the caption text '
' is not scrunched up against the min/max/close buttons '
Const PADDING_TWIPS = 120
nNewWidth = _
GetCaptionTextWidth(frm) _
+ GetControlBoxWidth(frm) _
+ GetIconWidth(frm) _
+ GetFrameWidth(frm) * 2 _
+ GetBorderWidth(frm) * 2 _
+ PADDING_TWIPS
If nNewWidth > frm.Width Then
GetRecommendedWidth = nNewWidth
Else
GetRecommendedWidth = frm.Width
End If
End Function
Then place the following in your Form_Load event
Private Sub Form_Load()
Me.Caption = String(100, "x") 'replace this with your caption'
Me.Width = GetRecommendedWidth(Me)
End Sub
A: It appears that VB6 limits the App.Title property to 40 characters. Unfortunately, I can't locate any documentation on MSDN detailing this behavior. (And unfortunately, I don't have documentation loaded onto the machine where my copy of VB6 still resides.)
I ran an experiment with long titles, and that was the observed behavior. If your title is longer than 40 characters, it simply will get truncated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to escape an underscore in a C preprocessor token? The following snippet is supposed to take the value of PROJECT (defined in the Makefile)
and create an include file name. For example, if PROJECT=classifier, then it should at the end generate classifier_ir.h for PROJECTINCSTR
I find that this code works as long as I am not trying to use an underscore in the suffix. However the use of the underscore is not optional - our code base uses them everywhere. I can work around this because there are a limited number of values for PROJECT but I would like to know how to make the following snippet actually work, with the underscore. Can it be escaped?
#define PROJECT classifier
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
#include PROJECTINCSTR
Edit: The compiler should try to include classifier_ir.h, not PROJECT_ir.h.
A: #define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define SMASH(x,y) x##y
#define MAKEINC(x) SMASH(x,_ir.h)
#define PROJECTINC MAKEINC(PROJECT)
#define PROJECTINCSTR MAKESTR(PROJECTINC)
A: This works for me:
#define QMAKESTR(x) #x
#define MAKESTR(x) QMAKESTR(x)
#define MAKEINC(x) x ## _ir.h
#define PROJECTINC(x) MAKEINC(x)
#define PROJECTINCSTR MAKESTR(PROJECTINC(PROJECT))
#include PROJECTINCSTR
A: That barebone example works with gcc (v4.1.2) and tries to include "PROJECT_ir.h"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141878",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: taglib -> dependency injection pojo/service how? Is there a nice way to dependency inject using a jsp taglib?
either using ejb 3.0, spring, or guice...
I have a lot of services/pojos that I would like to use in my taglibs
A: I think you want Seam, it enables you to refer to a component by name. However, the released version is JSF based, but that's changing.
A: just stumbled upon your question because I plan to do the same. You can actually use Spring and its @Configurable annotation (with AspectJ load-time or compile-time weaving) to inject services into your tag implementations. For a detailed explanation of all options have a look at Ramnivas' blog post here.
Hope to help in case you still need a solution...
A: Keep a reference to your injector on the servletContext and then use in each tag as you need it. See
In your Guice setup:
public class GuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(blah, blah);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.removeAttribute(Injector.class.getName());
super.contextDestroyed(servletContextEvent);
}
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
Injector injector = getInjector();
ServletContext servletContext = servletContextEvent.getServletContext();
servletContext.setAttribute(Injector.class.getName(), injector);
super.contextInitialized(servletContextEvent);
}
}
And then in your taglib:
@Singleton
@SuppressWarnings("serial")
public class MySampleTag extends TagSupport {
@Inject private MyInjectedService myService;
@Override
public int doStartTag() throws JspException {
Injector injector = (Injector) pageContext.getServletContext().getAttribute(Injector.class.getName());
injector.injectMembers(this);
String value = myService.doSomething();
etc.
etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are the methods for tokenizing strings in .Net? This must be a classic .NET question for anyone migrating from Java.
.NET does not seem to have a direct equivalent to java.io.StreamTokenizer, however the JLCA provides a SupportClass that attempts to implement it. I believe the JLCA also provides a Tokenizer SupportClass that takes a String as the source, which I thought a StreamTokenizer would be derived from, but isn't.
What is the preferred way to Tokenize both a Stream and a String? or is there one? How are streams tokenized in .Net? I'd like to have the flexibility that java.io.StreamTokenizer provides. Any thoughts?
A: There isn't anything in .NET that is completely equivalent to StreamTokenizer. For simple cases, you can use String.Split(), but for more advanced token parsing, you'll probably end up using System.Text.RegularExpressions.Regex.
A: Use System.String.Split if you need to split a string based on a collection
of specific characters.
Use System.Text.RegularExpressions.RegEx.Split to split based
on matching patterns.
A: There's a tokenizer in the Nextem library -- you can see an example here: http://trac.assembla.com/nextem/browser/trunk/Examples/Parsing.n
It's implemented as a Nemerle macro, but you can write this and then use it from C# easily.
A: I don't think so, for very simple tokenizing have a look at System.String.Split().
More complex tokenizing can be achieved by System.Text.RegularExpressions.Regex.
A: We had the same problem of finding a StreamTokenizer equivalent when porting tuProlog from Java to C#. We ended up writing what as far as I know is a straight conversion of StreamTokenizer which takes a TextReader as a "stream" for input purposes. You will find the code in the download for tuProlog.NET 2.1 (LGPL-licensed) so feel free to reuse and adapt it to your needs.
A: To tokenize a string, use string.Split(...).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Command line builds for VC 6? I have been used to working with VS2005 and 2008 - using msbuild, etc, but I have inherited a set of projects that have to remain in vc6.0 for now. I don't like opening each project in the developer studio and building. I prefer to build form command line (I am automating the builds). Is this possible?
I have tried the nmake utility, but I still need to open up the projects and save/export the make file. This is tedious if the project changes - each time I have to save the make file. nmake seems to work, but it had a problem when I changed the location of the project in my directory tree (I checked out of svn into a new clean dir to try the build). It seemed to have hard coded paths in it, but I will have to check on that - it might have been a different problem.
Any alternatives out there?
Eventually I will migrate these to 2008, but for now that is not an option.
A: I'm recording the most important part of your link here - Microsoft has a bad habit of moving stuff around and leaving dead links. Not only is this the most important bit, but it gives enough information to do a search if/when they move it.
Building a Project from the Command Line
You can build a Visual C++ project from the command line without first exporting a makefile (MAKEFILE, or filename.mak) and using the NMAKE utility.
The basic command syntax is
msdev FileName [/MAKE "ProjectName – ConfigName | ALL"] [/REBUILD /CLEAN /NORECURSE /OUT LogFile /USEENV]
where FileName is the name of your project (.dsp) or workspace (.dsw) file.
A: I think I found m answer here:
http://msdn.microsoft.com/en-us/library/aa699274.aspx
thanks all
A: We use automated builds at my work place. Essentially just a batch file i fire off from the command line. Let me make sure i am allowed to post some sample code before i go ahead and post it. But yes, it IS possible to automate the build.
Sample Code:
:::::::: CompileSolution :::::::::::::::::::::::::
call X:\BuildTools\bin\BuildVbProj.bat
%COMPONENTNAME% %SOLUTIONDIR%
%PROJFILE% %BUILDOUTPUTFILE%
%PREBUILDFILE% if %ERRORLEVEL% NEQ 0
goto BuildErrors
goto Cleanup
EDIT: The BuildVbProj.bat file ultimately calls VB6.exe in the Program Files\MS Visual Studio\VB98\ folder. Try calling it with "VB6.exe /?" or "VB6.exe -?" and it will show you a list of options. You can basically automate your process using those options.
There should be a similar exe for VC in the VC98 folder as well.
A: of course you can automate. I haven't used vc in years, but I think the compiler is called c8.exe or wow, I can't remember silly little tidbits like that anymore, but look in your vc\bin directory at all the exes and it will be obvious by name.
you can write a batch file worst case. But I also remember the UI having a "create makefile" function. So you do that once, and then just run make from the command line and voila. or maybe it's nmake. Again, been a long long time.
A: Microsoft provides a command line driver for building Visual Studio projects. In VC6 it's called "msdev" (do msdev /? for a list of options).
At some point (probably VS.NET/VS 2002) they started calling the command line build driver "devenv" for some reason. It has a somewhat different syntax, but for driving builds the options are the same or similar.
A: Another option which is less labor intensive is
Pulldown Menu (BUILD)
Select (BATCHBUILD)
Push Button (REBUILDALL)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Alternatives to the MVC What are the alternative "design methods" to the Model View Controller? MVC seems to be popular (SO was built with it, I know that much) but is it the only method used?
A: DCI - "Data, Communication and Interaction"
http://www.antonioshome.net/kitchen/nbdci/index.php#dci-introduction
http://www.artima.com/articles/dci_visionP.html
The Common Sense of Object Orientated Programming - MVC vs DCI
A: One of the best write-ups of several different Interactive Application Architecture Patterns out there, is this very detailed and well-researched blog-post. It covers Model-View-Controller, three different flavors of Model-View-Presenter, several different flavors of Presentation-Abstraction-Control, Supervising Controller, Passive View and Hierarchical MVC.
Another interesting pattern is the Presenter First pattern by Atomic Objects. It's not just a Design Pattern, it's also a Process Pattern. IOW: the name "Presenter First" is not arbitrary, it actually describes a development process, in which the Presenter gets written first, driving the design of the rest of the system.
A: There are many others:
*
*Model View Presenter (MVP)
*
*Supervising Controller
*Passive View
*Model View ViewModel (MVVM)
*
*This is common in WPF applications (though Prism uses the MVP pattern (usually))
A: MVC is part of a greater group of design patterns. I have no idea how much experience you have, so I'm not sure how to target this response. I'm a .NET programmer, but I found the Java book Head First Design Patterns extremely helpful. Design patterns are usually broken into groups with other patterns that help solve similar problems.
I also found the Data Object Factory website quite helpful as well. You should look around for some resources in your favorite language.
A: MVC is an architectural pattern. These are the other Architectural patterns you can try (from Wikipedia):
*
*Layers
*Multi-tier Architecture
*Presentation Abstraction Control (PAC)
*Model View Presenter (MVP)
*Model View ViewModel (MVVM)
*Pipeline
*Implicit Invocation
*Blackboard System
*Peer-to-Peer
*Service Oriented Architecture (SOA)
*Naked Objects
These are available here in Wikipedia.
A: We use not so much an alternative but a hybrid called MVC-ARS.
A: I know the MVCS from Joe Berkovitz.
Prof. Kowarschick used that approach to develop the VCLSD-Pattern (Wiki written in german! Maybe someone has time, to translate it - as for myself I am only a beginner in programming)
MVCS: Model View Control Service
VCLSD: View Control Logic Service Data
A: How about flux.js from Facebook? I know it's platform dependent, but it's a data flow architecture used by FB as a replacement for MVC, so I believe you can get some ideas from there too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Pulling both the text and attribute of a given node using Xpath I'm parsing XML results from an API call using PHP and xpath.
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
$xpath = new DOMXPath($dom);
$xpath->registerNamespace("a", "http://www.example.com");
$hrefs = $xpath->query('//a:Books/text()', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->data;
}
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
This works but is there a way I can access both the text and the attribute from one query? And if so how do you get to those items once query is executed?
A: After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node.
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->nodeValue;
$arrBookDewey[$i] = $hrefs->item($i)->getAttribute('DeweyDecimal');
}
A: One single XPath expression that will select both the text nodes of "a:Books" and their "DeweyDecimal" attribute, is the following
//a:Books/text() | //a:Books/@DeweyDecimal
Do note the use of the XPath's union operator in the expression above.
Another note: try to avoid using the "//" abbreviation as it may cause the whole XML document to be traversed and thus is very expensive. It is recommended to use a more specific XPath expression (such as consisting of a chain of specific location steps) always when the structure of the XML document is known.
A: If your're just retrieving values from your XML document, SimpleXML might be the leaner, faster and memory-friendlier solution:
$xml=simplexml_load_string($response->getBody());
$xml->registerXPathNamespace('a', 'http://www.example.com');
$books=$xml->xpath('//a:Books');
foreach ($books as $i => $book) {
$arrBookTitle[$i]=(string)$book;
$arrBookDewey[$i]=$book['DeweyDecimal'];
}
A: Could you query for the concatenation?
$xpath->query('concat(//a:Books/text(), //a:Books/@DeweyDecimal)', $dom);
XSLT is an expression language in itself, and you can construct whatever specific format of return value you want from within the expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Unable to link to shared library I'm building a shared library with g++ 3.3.4. I cannot link to the library because I am getting
./BcdFile.RHEL70.so: undefined symbol: _ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE13insert_uniqueERKj
Which c++filt describes as
std::_Rb_tree<unsigned int, unsigned int, std::_Identity<unsigned int>, std::less<unsigned int>, std::allocator<unsigned int> >::insert_unique(unsigned int const&)
I thought this might have come from using hash_map, but I've taken that all out and switched to regular std::map. I am using g++ to do the linking, which is including -lstdc++.
Does anyone know what class would be instantiating this template? Or even better, which library I need to be linking to?
EDIT: After further review, it appears adding the -frepo flag when compiling has caused this, unfortunately that flag is working around gcc3.3 bug.
A: std::_Rb_Tree might be a red-black tree, which would most likely be from using map. It should be part of libstdc++, unless your library is linking against a different version of libstdc++ than the application, which from what you've said so far seems unlikely.
EDIT: Just to clarify, the red-black tree is the underlying data structure in map. All that hash_map does is hash the key before using it, rather than using the raw value.
A: Try #include < map > in the source file where you are using map.
A: You seem to have 2 different incompatible versions of libstdc++.so from different versions of gcc. Check your paths.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rules for multi-user WinForms apps on Vista We have an MSI installer for a .Net WinForms app for Windows XP that installs and runs only as an admin. Users have to log in to the app when it runs. Customers want it to install and run under a user account under Vista, and to use their Windows account.
A preliminary look through the code shows lots of problems; the installer writes to the registry and installs the app in C:\Program Files. The app stores user preference in the registry, writes data to C:\Documents and Settings\All Users\, and creates temp files in C:.
I guess the first thing to do is store data files in System.Environment.CommonApplicationData and user preferences in System.Environment.LocalApplicationData. Can a user account install an app to System.Environment.ProgramFiles?
A problem is that the app must be installable and uninstallable by any user, and all users share the same data files. Each user has their own preferences.
Is there a book or web site that gives a detailed breakdown on what is required to build a WinForms app that obeys the rules for multiple users on Vista?
Edit: I checked with the client and the requirement to install only as a user account is firm, they are removing admin access from floor staff. This rules out admin-installed components and per-machine installs.
I was thinking of creating a separate data app that would run on an admin machine which the floor machines would connect to via remoting. All client data would be stored on this machine. However, this app would also have to install and run under a user account.
Is there a book or site describing all the rules which Vista user apps must follow?
A: "the app must be installable and uninstallable by any user"
"all users share the same data files"
You're going to have trouble with having to meet both of these requirements. Vista's new security features are designed to keep users from trampling on each other (and on the system).
About the only way I can think of to make this work is a way similar to how we handled a requirement like that on a Windows 2000 environment. You build two components -- the user part of the app, and a system component that manages the information that's shared between the users. An admin installs the 'shared' component (which includes a windows service to run it), and each user installs the 'user' component.
I think that might work for your scenario, but it would require re-working your code that uses the shared files to talk to the service instead of accessing those files directly.
Of course, you could also just have a tool the user runs as an admin to create your folder in a specific place and grant the needed security permissions. That might work for your purposes as well.
A: You will have problems allowing the application to be installed by any user, and at the same time access shared data files. This is because your first requirement implies a per-user install, whereas the second implies a per-machine install. Let me explain ...
Standard (MSI-based) installers can be scoped to be either per-user or per-machine:
*
*Per-user installs put the installed program files somewhere under the user's home directory. The application is installed for that user only. Other users don't even see the program in the start menu nor Add/Remove Programs. If they want the program, they have to install it themselves into their own per-user area. So there may be multiple copies of the program installed, and each one is isolated from the others. This type of installation can be performed by regular (non-admin) users, which is why they can't write to shared areas such as "Program Files" or "All Users".
*Per-machine installs can modify shared areas of the file system (ie "Program Files" or "All Users"). Each user sees the same copy of the program in the start menu and Add/Remove Programs. Only admin users can performs this type of installation.
A: Thanks guys. I checked with the client and the requirement to install only as a user account is firm, they are removing admin access from floor staff. This rules out admin-installed components and per-machine installs.
Our solution was to create a new Standard User account for our app. Staff who need to use the app must log on as this user. This actually turned out better than sharing data between users because now we can host the app for different clients on the same machine.
I also found a great reference for making multi-user apps on Windows, the Microsoft Windows 7 Client Software Logo Technical Requirements document.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: class with valueTypes fields and boxing I'm experimenting with generics and I'm trying to create structure similar to Dataset class.
I have following code
public struct Column<T>
{
T value;
T originalValue;
public bool HasChanges
{
get { return !value.Equals(originalValue); }
}
public void AcceptChanges()
{
originalValue = value;
}
}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
public bool HasChanges
{
get
{
return id.HasChanges | name.HasChanges | someDate.HasChanges | someInt.HasChanges;
}
}
public void AcceptChanges()
{
id.AcceptChanges();
name.AcceptChanges();
someDate.AcceptChanges();
someInt.AcceptChanges();
}
}
Problem I have is that when I add new column I need to add it also in HasChanges property and AcceptChanges() method. This just asks for some refactoring.
So first solution that cames to my mind was something like this:
public interface IColumn
{
bool HasChanges { get; }
void AcceptChanges();
}
public struct Column<T> : IColumn {...}
public class Record
{
Column<int> id;
Column<string> name;
Column<DateTime?> someDate;
Column<int?> someInt;
IColumn[] Columns { get { return new IColumn[] {id, name, someDate, someInt}; }}
public bool HasChanges
{
get
{
bool has = false;
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
IColumn[] columns = Columns; //clone and boxing
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges(); //Here we are changing clone
}
}
As you can see from comments we have few problems here with struct cloning. Simple solution to this is to change Column to class, but from my tests it seems that it increases memory usage by ~40% (because of each object metadata) which is not acceptable for me.
So my question is: does anyone have any other ideas how to create methods that can work on different structured objects/records? Maybe someone from F# community can suggest how such problems are solved in functional languages and how it impacts performance and memory usage.
Edit:
sfg thanks for suggestion about macros.
In Visual Studio 2008 there is built-in (but not so known) template engine called T4. Tha whole point is to add '.tt' file to my project and create a template that will search all my classes, recognize somehow the ones that are records (for example by some interface they implement) and produce partial classes with HasChanges and AcceptChanges() that will call only Columns the class contain.
Some usefull links:
T4 Editor for VS
Blog with links and tutorials about T4
Blog entry with example that uses EnvDTE to read project files
A: As you asked for examples from functional languages; in lisp you could prevent the writing of all that code upon each addition of a column by using a macro to crank the code out for you. Sadly, I do not think that is possible in C#.
In terms of performance: the macro would be evaluated at compile time (thus slowing compilation a tiny amount), but would cause no slow-down at run-time as the run-time code would be the same as what you would write manually.
I think you might have to accept your original AcceptChanges() as you need to access the structs directly by their identifiers if you want to avoid writing to cloned versions.
In other words: you need a program to write the program for you, and I do not know how to do that in C# without going to extraordinary lengths or losing more in performance than you ever would by switching the structs to classes (e.g. reflection).
A: Honestly, it sounds like you really want these Columns to be classes, but don't want to pay the runtime cost associated with classes, so you're trying to make them be structs. I don't think you're going to find an elegant way to do what you want. Structs are supposed to be value types, and you want to make them behave like reference types.
You cannot efficiently store your Columns in an array of IColumns, so no array approach is going to work well. The compiler has no way to know that the IColumn array will only hold structs, and indeed, it wouldn't help if it did, because there are still different types of structs you are trying to jam in there. Every time someone calls AcceptChanges() or HasChanges(), you're going to end up boxing and cloning your structs anyway, so I seriously doubt that making your Column a struct instead of a class is going to save you much memory.
However, you could probably store your Columns directly in an array and index them with an enum. E.g:
public class Record
{
public enum ColumnNames { ID = 0, Name, Date, Int, NumCols };
private IColumn [] columns;
public Record()
{
columns = new IColumn[ColumnNames.NumCols];
columns[ID] = ...
}
public bool HasChanges
{
get
{
bool has = false;
for (int i = 0; i < columns.Length; i++)
has |= columns[i].HasChanges;
return has;
}
}
public void AcceptChanges()
{
for (int i = 0; i < columns.Length; i++)
columns[i].AcceptChanges();
}
}
I don't have a C# compiler handy, so I can't check to see if that will work or not, but the basic idea should work, even if I didn't get all the details right. However, I'd just go ahead and make them classes. You're paying for it anyway.
A: You could use reflection to iterate over the members and invoke HasChanges and AcceptChanges. The Record class could store the reflection metadata as a static so there is no per-instance memory overhead. However, the performance cost at runtime is going to be huge -- you might also end up boxing and unboxing the column which would add even more to the cost.
A: The only way I can think of to do what you really want to do is to use Reflection. This would still box/unbox, but it would allow you to store the clone back into the field, effectively making it the real value.
public void AcceptChanges()
{
foreach (FieldInfo field in GetType().GetFields()) {
if (!typeof(IColumn).IsAssignableFrom(field.FieldType))
continue; // ignore all non-IColumn fields
IColumn col = (IColumn)field.GetValue(this); // Boxes storage -> clone
col.AcceptChanges(); // Works on clone
field.SetValue(this, col); // Unboxes clone -> storage
}
}
A: How about this:
public interface IColumn<T>
{
T Value { get; set; }
T OriginalValue { get; set; }
}
public struct Column<T> : IColumn<T>
{
public T Value { get; set; }
public T OriginalValue { get; set; }
}
public static class ColumnService
{
public static bool HasChanges<T, S>(T column) where T : IColumn<S>
{
return !(column.Value.Equals(column.OriginalValue));
}
public static void AcceptChanges<T, S>(T column) where T : IColumn<S>
{
column.Value = column.OriginalValue;
}
}
The client code is then:
Column<int> age = new Column<int>();
age.Value = 35;
age.OriginalValue = 34;
if (ColumnService.HasChanges<Column<int>, int>(age))
{
ColumnService.AcceptChanges<Column<int>, int>(age);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I get the key value of a db.ReferenceProperty without a database hit? Is there a way to get the key (or id) value of a db.ReferenceProperty, without dereferencing the actual entity it points to? I have been digging around - it looks like the key is stored as the property name preceeded with an _, but I have been unable to get any code working. Examples would be much appreciated. Thanks.
EDIT: Here is what I have unsuccessfully tried:
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return self._series
And in my template:
<a href="games/view-series.html?series={{comment.series_id}}#comm{{comment.key.id}}">more</a>
The result:
<a href="games/view-series.html?series=#comm59">more</a>
A: Actually, the way that you are advocating accessing the key for a ReferenceProperty might well not exist in the future. Attributes that begin with '_' in python are generally accepted to be "protected" in that things that are closely bound and intimate with its implementation can use them, but things that are updated with the implementation must change when it changes.
However, there is a way through the public interface that you can access the key for your reference-property so that it will be safe in the future. I'll revise the above example:
class Comment(db.Model):
series = db.ReferenceProperty(reference_class=Series);
def series_id(self):
return Comment.series.get_value_for_datastore(self)
When you access properties via the class it is associated, you get the property object itself, which has a public method that can get the underlying values.
A: You're correct - the key is stored as the property name prefixed with '_'. You should just be able to access it directly on the model object. Can you demonstrate what you're trying? I've used this technique in the past with no problems.
Edit: Have you tried calling series_id() directly, or referencing _series in your template directly? I'm not sure whether Django automatically calls methods with no arguments if you specify them in this context. You could also try putting the @property decorator on the method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PostgreSQL's and MySQL's full text search How do the full text search systems of PostgreSQL and MySQL compare? Is any clearly better than the oder? In which way are they different?
A: PostgreSQL 8.3 has built in full text search which is an integrated version of the "tsearch2"
Here is the documentation: http://www.postgresql.org/docs/8.3/static/textsearch.html
And the example from the documentation:
SELECT title
FROM pgweb
WHERE to_tsvector(body) @@ to_tsquery('friend');
Where body is a text field. You can index specifically for these types of searches and of course they can become more complex than this simple example. The functionality is very solid and worth diving into as you make your decision.
Best of luck.
A:
Update: Starting in MySQL 5.6, InnoDB supports fulltext search
I'm not well versed in PostgreSQL unfortunately, but if you use the FULL TEXT search in MySQL you're immediately tied to MyISAM. If you want to use InnoDB (and if ACID compliance means anything to you, you should be using InnoDB) you're stuck using other solutions.
Two popular alternatives that are often rolled out are Lucene (an apache project with a Zend module if you're using PHP) and Sphinx.
A: If your using Hibernate as a ORM I highly recommend using Hibernate search. Its build on top of Lucene so its super fast.
Karl
A: I've had pretty good experience with postgresql/tsearch2, especially since it was rolled into the standard distribution (before version 8.0 - I think - it was an optional contrib feature, and upgrading to tsearch2 involved a bit of work).
If I recall correctly you have to set some properties (fuzzy matching, dictionary stuff) before startup, whereas on other databases those things are flexibly exposed through the fulltext syntax itself (I'm thinking of Oracle Text, here, though I know that's not relevant to your question).
A: I think you can use Sphinx with both MySQL and Postgres.
Here is an article to explain how to use Sphinx with MySQL (you can add it as a plugin)
A: Mysql full text search is very slow. It can't handle data more than 1 million (several tens of seconds per query).
I've no experience using postgresql full text search.
I have used sphinxsearch. It is very fast and easy to use. But it is not so powerful. I mean the search functionality. For example, it doesn't support like 'abc?', where '?' stands for any character.
I also know lucene. It is powerful, but it is hard to learn.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Anyone used the ABC Metric for measuring an application's size? There are some nice things about it (like it encapsulates the concept of Cyclomatic complexity), and I was wondering if anyone has used it in "real life". If so, what are your experiences? Is it a useful measure of size (as opposed to KLOC or Function Points)?
For those wondering what I'm smoking:
Here's a link to some info on it: http://c2.com/cgi/wiki/Wiki?AbcMetric
A: The application's sheer 'size' could be safely measured in LOCs or any other metrics you could think of as long as you use the same approach across all of your application.
However the size on its own really matters only when you're talking about re-factoring and maintainance of the code base. It's almost mandatory to use the size metrics are useful in conjuction with the coverage statistics.
But most of the time Function Points or similar concepts give you much better view of how big your application really is.
I.e. as an example if it has 10 FP it's tiny, if it has 200 it's probably big.
But if it has 100 KLOCs what does it tell me on its own, aside from the fact that I'll probably spend some time reading those lines? Almost nothing, I have to take an enourmous amount of other factors into an account to be able to understand this metric.
Obviously the FPs have a significant downside of being expensive to properly calculate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Buffer a large file; BufferedInputStream limited to 2gb; Arrays limited to 2^31 bytes I am sequentially processing a large file and I'd like to keep a large chunk of it in memory, 16gb ram available on a 64 bit system.
A quick and dirty way is to do this, is simply wrap the input stream into a buffered input stream, unfortunately, this only gives me a 2gb buffer. I'd like to have more of it in memory, what alternatives do I have?
A: How about letting the OS deal with the buffering of the file? Have you checked what the performance impact of not copying the whole file into JVMs memory is?
EDIT: You could then use either RandomAccessFile or the FileChannel to efficiently read the necessary parts of the file into the JVMs memory.
A: Have you considered the MappedByteBuffer in java.nio? It's over my head but maybe it is what you are looking for.
A: I doubt that buffering more than 2gb at a time is going to be a huge win anyway. Depending on the amount of processing you're doing, you might be able to read in nearly as fast as you process. To speed it up, you might try using a two-threaded producer-consumer model (one thread reads the file and hands the data off to the other thread for processing).
A: The OS is going to cache as much of the file as it can, so trying to outsmart the cache manager probably isn't going to get you very much.
From a performance perspective, you will be much better served by keeping the bytes outside the JVM (transferring huge chunks of data between the OS and JVM is relatively slow). You can achieve this goal by using a MappedByteBuffer backed by a direct memory block.
Here's a pertinent how-to type of article: article
A: I think there are 64 bit JVMs that will support nonstandard limits.
You might try buffering chunks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why would an UpdatePanel stop working after a few minutes? What aspects of the UpdatePanel are sensitive to time?
I have an UpdatePanel that works fine. If I leave the page for a few minutes and come back, the UpdatePanel doesn't work. Looking at firebug, I see that it sends the Request and gets a Response back. However, the page itself doesn't update. I'm not seeing any script errors either. So far I haven't been able to identify any other factor than the passage of time.
A: Maybe your application domain recycled or your Session was lost. Have you tried seeing what is being called on the server? That'd be my suggestion on where to look next.
A: Turn off Firebug network monitoring if enabled.
A: Most likely the session expired, causing it to send back data that no longer matches the page.
A: If it's a session expiring, it should be reproducible without the UpdatePanel -- go back to postback and see if it also happens that way. You might even get a better idea of the error since it isn't potentially eaten by the JavaScript that the UpdatePanel runs underneath the hood.
A: I've noticed that if you have a TON of controls in your update panel, it can either timeout or refuse to work. One time I had a gridview in an update panel with three ajax calendar controls in each row.. total of 2,000 records in the gridview.. updatepanel was none too happy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best way to compare 2 XML documents in Java I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.
When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)
I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage.
So, boiled down, the question is:
Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.
A: Thanks, I extended this, try this ...
import java.io.ByteArrayInputStream;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public class XmlDiff
{
private boolean nodeTypeDiff = true;
private boolean nodeValueDiff = true;
public boolean diff( String xml1, String xml2, List<String> diffs ) throws Exception
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc1 = db.parse(new ByteArrayInputStream(xml1.getBytes()));
Document doc2 = db.parse(new ByteArrayInputStream(xml2.getBytes()));
doc1.normalizeDocument();
doc2.normalizeDocument();
return diff( doc1, doc2, diffs );
}
/**
* Diff 2 nodes and put the diffs in the list
*/
public boolean diff( Node node1, Node node2, List<String> diffs ) throws Exception
{
if( diffNodeExists( node1, node2, diffs ) )
{
return true;
}
if( nodeTypeDiff )
{
diffNodeType(node1, node2, diffs );
}
if( nodeValueDiff )
{
diffNodeValue(node1, node2, diffs );
}
System.out.println(node1.getNodeName() + "/" + node2.getNodeName());
diffAttributes( node1, node2, diffs );
diffNodes( node1, node2, diffs );
return diffs.size() > 0;
}
/**
* Diff the nodes
*/
public boolean diffNodes( Node node1, Node node2, List<String> diffs ) throws Exception
{
//Sort by Name
Map<String,Node> children1 = new LinkedHashMap<String,Node>();
for( Node child1 = node1.getFirstChild(); child1 != null; child1 = child1.getNextSibling() )
{
children1.put( child1.getNodeName(), child1 );
}
//Sort by Name
Map<String,Node> children2 = new LinkedHashMap<String,Node>();
for( Node child2 = node2.getFirstChild(); child2!= null; child2 = child2.getNextSibling() )
{
children2.put( child2.getNodeName(), child2 );
}
//Diff all the children1
for( Node child1 : children1.values() )
{
Node child2 = children2.remove( child1.getNodeName() );
diff( child1, child2, diffs );
}
//Diff all the children2 left over
for( Node child2 : children2.values() )
{
Node child1 = children1.get( child2.getNodeName() );
diff( child1, child2, diffs );
}
return diffs.size() > 0;
}
/**
* Diff the nodes
*/
public boolean diffAttributes( Node node1, Node node2, List<String> diffs ) throws Exception
{
//Sort by Name
NamedNodeMap nodeMap1 = node1.getAttributes();
Map<String,Node> attributes1 = new LinkedHashMap<String,Node>();
for( int index = 0; nodeMap1 != null && index < nodeMap1.getLength(); index++ )
{
attributes1.put( nodeMap1.item(index).getNodeName(), nodeMap1.item(index) );
}
//Sort by Name
NamedNodeMap nodeMap2 = node2.getAttributes();
Map<String,Node> attributes2 = new LinkedHashMap<String,Node>();
for( int index = 0; nodeMap2 != null && index < nodeMap2.getLength(); index++ )
{
attributes2.put( nodeMap2.item(index).getNodeName(), nodeMap2.item(index) );
}
//Diff all the attributes1
for( Node attribute1 : attributes1.values() )
{
Node attribute2 = attributes2.remove( attribute1.getNodeName() );
diff( attribute1, attribute2, diffs );
}
//Diff all the attributes2 left over
for( Node attribute2 : attributes2.values() )
{
Node attribute1 = attributes1.get( attribute2.getNodeName() );
diff( attribute1, attribute2, diffs );
}
return diffs.size() > 0;
}
/**
* Check that the nodes exist
*/
public boolean diffNodeExists( Node node1, Node node2, List<String> diffs ) throws Exception
{
if( node1 == null && node2 == null )
{
diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2 + "\n" );
return true;
}
if( node1 == null && node2 != null )
{
diffs.add( getPath(node2) + ":node " + node1 + "!=" + node2.getNodeName() );
return true;
}
if( node1 != null && node2 == null )
{
diffs.add( getPath(node1) + ":node " + node1.getNodeName() + "!=" + node2 );
return true;
}
return false;
}
/**
* Diff the Node Type
*/
public boolean diffNodeType( Node node1, Node node2, List<String> diffs ) throws Exception
{
if( node1.getNodeType() != node2.getNodeType() )
{
diffs.add( getPath(node1) + ":type " + node1.getNodeType() + "!=" + node2.getNodeType() );
return true;
}
return false;
}
/**
* Diff the Node Value
*/
public boolean diffNodeValue( Node node1, Node node2, List<String> diffs ) throws Exception
{
if( node1.getNodeValue() == null && node2.getNodeValue() == null )
{
return false;
}
if( node1.getNodeValue() == null && node2.getNodeValue() != null )
{
diffs.add( getPath(node1) + ":type " + node1 + "!=" + node2.getNodeValue() );
return true;
}
if( node1.getNodeValue() != null && node2.getNodeValue() == null )
{
diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2 );
return true;
}
if( !node1.getNodeValue().equals( node2.getNodeValue() ) )
{
diffs.add( getPath(node1) + ":type " + node1.getNodeValue() + "!=" + node2.getNodeValue() );
return true;
}
return false;
}
/**
* Get the node path
*/
public String getPath( Node node )
{
StringBuilder path = new StringBuilder();
do
{
path.insert(0, node.getNodeName() );
path.insert( 0, "/" );
}
while( ( node = node.getParentNode() ) != null );
return path.toString();
}
}
A: AssertJ 1.4+ has specific assertions to compare XML content:
String expectedXml = "<foo />";
String actualXml = "<bar />";
assertThat(actualXml).isXmlEqualTo(expectedXml);
Here is the Documentation
A: The following will check if the documents are equal using standard JDK libraries.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc1 = db.parse(new File("file1.xml"));
doc1.normalizeDocument();
Document doc2 = db.parse(new File("file2.xml"));
doc2.normalizeDocument();
Assert.assertTrue(doc1.isEqualNode(doc2));
normalize() is there to make sure there are no cycles (there technically wouldn't be any)
The above code will require the white spaces to be the same within the elements though, because it preserves and evaluates it. The standard XML parser that comes with Java does not allow you to set a feature to provide a canonical version or understand xml:space if that is going to be a problem then you may need a replacement XML parser such as xerces or use JDOM.
A: Below code works for me
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
XMLAssert.assertXMLEqual(actualxml, xmlInDb);
A: skaffman seems to be giving a good answer.
another way is probably to format the XML using a commmand line utility like xmlstarlet(http://xmlstar.sourceforge.net/) and then format both the strings and then use any diff utility(library) to diff the resulting output files. I don't know if this is a good solution when issues are with namespaces.
A: I'm using Altova DiffDog which has options to compare XML files structurally (ignoring string data).
This means that (if checking the 'ignore text' option):
<foo a="xxx" b="xxx">xxx</foo>
and
<foo b="yyy" a="yyy">yyy</foo>
are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!
A: Xom has a Canonicalizer utility which turns your DOMs into a regular form, which you can then stringify and compare. So regardless of whitespace irregularities or attribute ordering, you can get regular, predictable comparisons of your documents.
This works especially well in IDEs that have dedicated visual String comparators, like Eclipse. You get a visual representation of the semantic differences between the documents.
A: The latest version of XMLUnit can help the job of asserting two XML are equal. Also XMLUnit.setIgnoreWhitespace() and XMLUnit.setIgnoreAttributeOrder() may be necessary to the case in question.
See working code of a simple example of XML Unit use below.
import org.custommonkey.xmlunit.DetailedDiff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Assert;
public class TestXml {
public static void main(String[] args) throws Exception {
String result = "<abc attr=\"value1\" title=\"something\"> </abc>";
// will be ok
assertXMLEquals("<abc attr=\"value1\" title=\"something\"></abc>", result);
}
public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {
XMLUnit.setIgnoreWhitespace(true);
XMLUnit.setIgnoreAttributeOrder(true);
DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
List<?> allDifferences = diff.getAllDifferences();
Assert.assertEquals("Differences found: "+ diff.toString(), 0, allDifferences.size());
}
}
If using Maven, add this to your pom.xml:
<dependency>
<groupId>xmlunit</groupId>
<artifactId>xmlunit</artifactId>
<version>1.4</version>
</dependency>
A: Sounds like a job for XMLUnit
*
*http://www.xmlunit.org/
*https://github.com/xmlunit
Example:
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}
A: I required the same functionality as requested in the main question. As I was not allowed to use any 3rd party libraries, I have created my own solution basing on @Archimedes Trajano solution.
Following is my solution.
import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Assert;
import org.w3c.dom.Document;
/**
* Asserts for asserting XML strings.
*/
public final class AssertXml {
private AssertXml() {
}
private static Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(ns\\d+)=\"(.*?)\"");
/**
* Asserts that two XML are of identical content (namespace aliases are ignored).
*
* @param expectedXml expected XML
* @param actualXml actual XML
* @throws Exception thrown if XML parsing fails
*/
public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {
// Find all namespace mappings
Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();
generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);
generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);
for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {
String newAlias = entry.getValue();
String namespace = entry.getKey();
Pattern nsReplacePattern = Pattern.compile("xmlns:(ns\\d+)=\"" + namespace + "\"");
expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);
actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);
}
// nomralize namespaces accoring to given mapping
DocumentBuilder db = initDocumentParserFactory();
Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName("UTF-8"))));
expectedDocuemnt.normalizeDocument();
Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName("UTF-8"))));
actualDocument.normalizeDocument();
if (!expectedDocuemnt.isEqualNode(actualDocument)) {
Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse
}
}
private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(false);
dbf.setCoalescing(true);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setIgnoringComments(true);
DocumentBuilder db = dbf.newDocumentBuilder();
return db;
}
private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {
Matcher nsMatcherExp = namespacePattern.matcher(xml);
if (nsMatcherExp.find()) {
xml = xml.replaceAll(nsMatcherExp.group(1) + "[:]", newAlias + ":");
xml = xml.replaceAll(nsMatcherExp.group(1) + "=", newAlias + "=");
}
return xml;
}
private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {
Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);
while (nsMatcher.find()) {
if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {
fullnamespace2newAlias.put(nsMatcher.group(2), "nsTr" + (fullnamespace2newAlias.size() + 1));
}
}
}
}
It compares two XML strings and takes care of any mismatching namespace mappings by translating them to unique values in both input strings.
Can be fine tuned i.e. in case of translation of namespaces. But for my requirements just does the job.
A: Building on Tom's answer, here's an example using XMLUnit v2.
It uses these maven dependencies
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-core</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<version>2.0.0</version>
<scope>test</scope>
</dependency>
..and here's the test code
import static org.junit.Assert.assertThat;
import static org.xmlunit.matchers.CompareMatcher.isIdenticalTo;
import org.xmlunit.builder.Input;
import org.xmlunit.input.WhitespaceStrippedSource;
public class SomeTest extends XMLTestCase {
@Test
public void test() {
String result = "<root></root>";
String expected = "<root> </root>";
// ignore whitespace differences
// https://github.com/xmlunit/user-guide/wiki/Providing-Input-to-XMLUnit#whitespacestrippedsource
assertThat(result, isIdenticalTo(new WhitespaceStrippedSource(Input.from(expected).build())));
assertThat(result, isIdenticalTo(Input.from(expected).build())); // will fail due to whitespace differences
}
}
The documentation that outlines this is https://github.com/xmlunit/xmlunit#comparing-two-documents
A: This will compare full string XMLs (reformatting them on the way). It makes it easy to work with your IDE (IntelliJ, Eclipse), cos you just click and visually see the difference in the XML files.
import org.apache.xml.security.c14n.CanonicalizationException;
import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
import org.w3c.dom.Element;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSSerializer;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.IOException;
import java.io.StringReader;
import static org.apache.xml.security.Init.init;
import static org.junit.Assert.assertEquals;
public class XmlUtils {
static {
init();
}
public static String toCanonicalXml(String xml) throws InvalidCanonicalizerException, ParserConfigurationException, SAXException, CanonicalizationException, IOException {
Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
byte canonXmlBytes[] = canon.canonicalize(xml.getBytes());
return new String(canonXmlBytes);
}
public static String prettyFormat(String input) throws TransformerException, ParserConfigurationException, IOException, SAXException, InstantiationException, IllegalAccessException, ClassNotFoundException {
InputSource src = new InputSource(new StringReader(input));
Element document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(src).getDocumentElement();
Boolean keepDeclaration = input.startsWith("<?xml");
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", keepDeclaration);
return writer.writeToString(document);
}
public static void assertXMLEqual(String expected, String actual) throws ParserConfigurationException, IOException, SAXException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
String canonicalExpected = prettyFormat(toCanonicalXml(expected));
String canonicalActual = prettyFormat(toCanonicalXml(actual));
assertEquals(canonicalExpected, canonicalActual);
}
}
I prefer this to XmlUnit because the client code (test code) is cleaner.
A: Using XMLUnit 2.x
In the pom.xml
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-assertj3</artifactId>
<version>2.9.0</version>
</dependency>
Test implementation (using junit 5) :
import org.junit.jupiter.api.Test;
import org.xmlunit.assertj3.XmlAssert;
public class FooTest {
@Test
public void compareXml() {
//
String xmlContentA = "<foo></foo>";
String xmlContentB = "<foo></foo>";
//
XmlAssert.assertThat(xmlContentA).and(xmlContentB).areSimilar();
}
}
Other methods : areIdentical(), areNotIdentical(), areNotSimilar()
More details (configuration of assertThat(~).and(~) and examples) in this documentation page.
XMLUnit also has (among other features) a DifferenceEvaluator to do more precise comparisons.
XMLUnit website
A: Using JExamXML with java application
import com.a7soft.examxml.ExamXML;
import com.a7soft.examxml.Options;
.................
// Reads two XML files into two strings
String s1 = readFile("orders1.xml");
String s2 = readFile("orders.xml");
// Loads options saved in a property file
Options.loadOptions("options");
// Compares two Strings representing XML entities
System.out.println( ExamXML.compareXMLString( s1, s2 ) );
A: Since you say "semantically equivalent" I assume you mean that you want to do more than just literally verify that the xml outputs are (string) equals, and that you'd want something like
<foo> some stuff here</foo></code>
and
<foo>some stuff here</foo></code>
do read as equivalent. Ultimately it's going to matter how you're defining "semantically equivalent" on whatever object you're reconstituting the message from. Simply build that object from the messages and use a custom equals() to define what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/141993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "217"
}
|
Q: jQuery override form submit not working when submit called by javascript on a element I've got a page with a normal form with a submit button and some jQuery which binds to the form submit event and overrides it with e.preventDefault() and runs an AJAX command. This works fine when the submit button is clicked but when a link with onclick='document.formName.submit();' is clicked, the event is not caught by the AJAX form submit event handler. Any ideas why not or how to get this working without binding to all the a elements?
A: A couple of suggestions:
*
*Overwrite the submit function to do your evil bidding
var oldSubmit = form.submit;
form.submit = function() {
$(form).trigger("submit");
oldSubmit.call(form, arguments);
}
*
*Why not bind to all the <a> tags? Then you don't have to do any monkey patching, and it could be as simple as (assuming all the links are inside the form tag):
$("form a").click(function() {
$(this).parents().filter("form").trigger("submit");
});
A: If you are using jQuery, you should be attaching events via it's own event mechanism and not by using "on" properties (onclick etc.). It also has its own event triggering method, aptly named 'trigger', which you should use to activate the form submission event.
A: Thanks Eran
I am using this event binding code
this._form.bind('submit', Delegate.create(this, function(e) {
e.preventDefault();
this._searchFadeOut();
this.__onFormSubmit.invoke(this, new ZD.Core.GenericEventArgs(this._dateField.attr('value')));
});
but there is legacy onclick code on the HTML and I would prefer not to change it as there are just so many links.
A: This worked for me:
Make a dummy button, hide the real submit with the name submit,
and then:
$("#mySubmit").click(function(){
$("#submit").trigger("click"); });
set an event handler on your dummy to trigger click on the form submit button. let the browser figure out how to submit the form... This way you don't need to preventDefault on the form submit which is where the trouble starts.
This seemed to work around the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/142000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.