qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
34,506 |
<p>Is there anyway to have a sort of virtual static member in C++?</p>
<p>For example:</p>
<pre><code>class BaseClass {
public:
BaseClass(const string& name) : _name(name) {}
string GetName() const { return _name; }
virtual void UseClass() = 0;
private:
const string _name;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() : BaseClass("DerivedClass") {}
virtual void UseClass() { /* do something */ }
};
</code></pre>
<p>I know this example is trivial, but if I have a vector of complex data that is going to be always the same for all derived class but is needed to be accessed from base class methods?</p>
<pre><code>class BaseClass {
public:
BaseClass() {}
virtual string GetName() const = 0;
virtual void UseClass() = 0;
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {}
virtual string GetName() const { return _name; }
virtual void UseClass() { /* do something */ }
private:
static const string _name;
};
string DerivedClass::_name = "DerivedClass";
</code></pre>
<p>This solution does not satify me because I need reimplement the member _name and its accessor GetName() in every class. In my case I have several members that follows _name behavior and tenths of derived classes.</p>
<p>Any idea?</p>
|
[
{
"answer_id": 34591,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 2,
"selected": false,
"text": "class BaseClass {\n public:\n BaseClass(const Descriptor& desc) : _desc(desc) {}\n string GetName() const { return _desc.name; }\n int GetId() const { return _desc.Id; }\n X GetX() connst { return _desc.X; }\n virtual void UseClass() = 0;\n private:\n const Descriptor _desc;\n};\n\n\nclass DerivedClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(Descriptor(\"abc\", 1,...)) {}\n virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(\"Wowzer\", 843,...) {}\n virtual void UseClass() { /* do something */ }\n};\n enum InstanceType {\n Yellow,\n Big,\n BananaHammoc\n}\n\nclass DescriptorsMap{\n public:\n static Descriptor* GetDescriptor(InstanceType type) {\n if ( _instance.Get() == null) {\n _instance.reset(new DescriptorsMap());\n }\n return _instance.Get()-> _descriptors[type];\n }\n private:\n DescriptorsMap() {\n descriptors[Yellow] = new Descriptor(\"Yellow\", 42, ...);\n descriptors[Big] = new Descriptor(\"InJapan\", 17, ...)\n ...\n }\n\n ~DescriptorsMap() {\n /*Delete all the descriptors from the map*/\n }\n\n static autoptr<DescriptorsMap> _instance;\n map<InstanceType, Descriptor*> _descriptors;\n}\n class DerivedClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.BananaHammoc)) {}\n virtual void UseClass() { /* do something */ }\n};\n\nclass DerDerClass : public BaseClass {\n public:\n DerivedClass() : BaseClass(DescriptorsMap.GetDescriptor(InstanceType.Yellow)) {}\n virtual void UseClass() { /* do something */ }\n};\n"
},
{
"answer_id": 34701,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 1,
"selected": false,
"text": "\n#include <iostream>\n#include <string>\nusing namespace std;\n\nstruct DerivedData\n{\n DerivedData(const string & word, const int number) :\n my_word(word), my_number(number) {}\n const string my_word;\n const int my_number;\n};\n\nclass Base {\npublic:\n Base() : m_data(0) {}\n string getWord() const { return m_data->my_word; }\n int getNumber() const { return m_data->my_number; }\nprotected:\n DerivedData * m_data;\n};\n\n\nclass Derived : public Base {\npublic:\n Derived() : Base() {\n if(Derived::s_data == 0) {\n Derived::s_data = new DerivedData(\"abc\", 1);\n }\n m_data = s_data;\n }\nprivate:\n static DerivedData * s_data;\n};\n\n\nDerivedData * Derived::s_data = 0; \n\nint main()\n{\n Base * p_b = new Derived();\n cout getWord() << endl;\n}\n\n"
},
{
"answer_id": 34857,
"author": "Misha M",
"author_id": 3467,
"author_profile": "https://Stackoverflow.com/users/3467",
"pm_score": 1,
"selected": false,
"text": "\ntemplate <typename T>\nclass Object\n{\npublic:\n\n Object( const T& newObject ) : yourObject(newObject) {} ;\n T GetObject() const { return yourObject } ;\n void SetObject( const T& newObject ) { yourObject = newObject } ;\n\nprotected:\n\n const T yourObject ;\n} ;\n\nclass SomeClassOne\n{\npublic:\n\n SomeClassOne( const std::vector& someData )\n {\n yourData.SetObject( someData ) ;\n }\n\nprivate:\n\n Object<std::vector<int>> yourData ;\n} ;\n"
},
{
"answer_id": 35201,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 4,
"selected": true,
"text": "struct BaseData\n{\n const string my_word;\n const int my_number;\n};\n\nclass Base\n{\npublic:\n Base(const BaseData* apBaseData)\n {\n mpBaseData = apBaseData;\n }\n const string getMyWord()\n {\n return mpBaseData->my_word;\n }\n int getMyNumber()\n {\n return mpBaseData->my_number;\n }\nprivate:\n const BaseData* mpBaseData;\n};\n\nclass Derived : public Base\n{\npublic:\n Derived() : Base(&sBaseData)\n {\n }\nprivate:\n static BaseData sBaseData;\n}\n\nBaseData Derived::BaseData = { \"Foo\", 42 };\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
] |
34,509 |
<p>We have a large database on which we have DB side pagination. This is quick, returning a page of 50 rows from millions of records in a small fraction of a second.</p>
<p>Users can define their own sort, basically choosing what column to sort by. Columns are dynamic - some have numeric values, some dates and some text.</p>
<p>While most sort as expected text sorts in a dumb way. Well, I say dumb, it makes sense to computers, but frustrates users.</p>
<p>For instance, sorting by a string record id gives something like:</p>
<pre><code>rec1
rec10
rec14
rec2
rec20
rec3
rec4
</code></pre>
<p>...and so on.</p>
<p>I want this to take account of the number, so:</p>
<pre><code>rec1
rec2
rec3
rec4
rec10
rec14
rec20
</code></pre>
<p>I can't control the input (otherwise I'd just format in leading 000s) and I can't rely on a single format - some are things like "{alpha code}-{dept code}-{rec id}".</p>
<p>I know a few ways to do this in C#, but can't pull down all the records to sort them, as that would be to slow.</p>
<p>Does anyone know a way to quickly apply a natural sort in Sql server?</p>
<hr>
<p>We're using:</p>
<pre><code>ROW_NUMBER() over (order by {field name} asc)
</code></pre>
<p>And then we're paging by that.</p>
<p>We can add triggers, although we wouldn't. All their input is parametrised and the like, but I can't change the format - if they put in "rec2" and "rec10" they expect them to be returned just like that, and in natural order.</p>
<hr>
<p>We have valid user input that follows different formats for different clients.</p>
<p>One might go rec1, rec2, rec3, ... rec100, rec101</p>
<p>While another might go: grp1rec1, grp1rec2, ... grp20rec300, grp20rec301</p>
<p>When I say we can't control the input I mean that we can't force users to change these standards - they have a value like grp1rec1 and I can't reformat it as grp01rec001, as that would be changing something used for lookups and linking to external systems.</p>
<p>These formats vary a lot, but are often mixtures of letters and numbers.</p>
<p>Sorting these in C# is easy - just break it up into <code>{ "grp", 20, "rec", 301 }</code> and then compare sequence values in turn.</p>
<p>However there may be millions of records and the data is paged, I need the sort to be done on the SQL server.</p>
<p>SQL server sorts by value, not comparison - in C# I can split the values out to compare, but in SQL I need some logic that (very quickly) gets a single value that consistently sorts.</p>
<p>@moebius - your answer might work, but it does feel like an ugly compromise to add a sort-key for all these text values.</p>
|
[
{
"answer_id": 35382,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": -1,
"selected": false,
"text": "ROW_NUMBER() OVER (ORDER BY dbo.human_sort(field_name) ASC)\n"
},
{
"answer_id": 523012,
"author": "JazzHands",
"author_id": 63173,
"author_profile": "https://Stackoverflow.com/users/63173",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION [dbo].[fnMixSort]\n(\n @ColValue NVARCHAR(255)\n)\nRETURNS NVARCHAR(1000)\nAS\n\nBEGIN\n DECLARE @p1 NVARCHAR(255),\n @p2 NVARCHAR(255),\n @p3 NVARCHAR(255),\n @p4 NVARCHAR(255),\n @Index TINYINT\n\n IF @ColValue LIKE '[a-z]%'\n SELECT @Index = PATINDEX('%[0-9]%', @ColValue),\n @p1 = LEFT(CASE WHEN @Index = 0 THEN @ColValue ELSE LEFT(@ColValue, @Index - 1) END + REPLICATE(' ', 255), 255),\n @ColValue = CASE WHEN @Index = 0 THEN '' ELSE SUBSTRING(@ColValue, @Index, 255) END\n ELSE\n SELECT @p1 = REPLICATE(' ', 255)\n\n SELECT @Index = PATINDEX('%[^0-9]%', @ColValue)\n\n IF @Index = 0\n SELECT @p2 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255),\n @ColValue = ''\n ELSE\n SELECT @p2 = RIGHT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n SELECT @Index = PATINDEX('%[0-9,a-z]%', @ColValue)\n\n IF @Index = 0\n SELECT @p3 = REPLICATE(' ', 255)\n ELSE\n SELECT @p3 = LEFT(REPLICATE(' ', 255) + LEFT(@ColValue, @Index - 1), 255),\n @ColValue = SUBSTRING(@ColValue, @Index, 255)\n\n IF PATINDEX('%[^0-9]%', @ColValue) = 0\n SELECT @p4 = RIGHT(REPLICATE(' ', 255) + @ColValue, 255)\n ELSE\n SELECT @p4 = LEFT(@ColValue + REPLICATE(' ', 255), 255)\n\n RETURN @p1 + @p2 + @p3 + @p4\n\nEND\n select item_name from my_table order by fnMixSort(item_name)\n"
},
{
"answer_id": 579005,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "order by LEN(value), value\n"
},
{
"answer_id": 750888,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Select *, \n substring(Cote,1,len(Cote) - Len(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1)))alpha,\n CAST(RIGHT(Cote, LEN(Cote) - PATINDEX('%[0-9]%', Cote)+1) AS INT)intv \nFROM Documents \n left outer join Sites ON Sites.IDSite = Documents.IDSite \nOrder BY alpha, intv\n"
},
{
"answer_id": 2060952,
"author": "D'Arcy Rittich",
"author_id": 39430,
"author_profile": "https://Stackoverflow.com/users/39430",
"pm_score": 6,
"selected": true,
"text": "using System;\nusing System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic class UDF\n{\n [SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic=true)]\n public static SqlString Naturalize(string val)\n {\n if (String.IsNullOrEmpty(val))\n return val;\n\n while(val.Contains(\" \"))\n val = val.Replace(\" \", \" \");\n\n const int maxLength = 1000;\n const int padLength = 25;\n\n bool inNumber = false;\n bool isDecimal = false;\n int numStart = 0;\n int numLength = 0;\n int length = val.Length < maxLength ? val.Length : maxLength;\n\n //TODO: optimize this so that we exit for loop once sb.ToString() >= maxLength\n var sb = new StringBuilder();\n for (var i = 0; i < length; i++)\n {\n int charCode = (int)val[i];\n if (charCode >= 48 && charCode <= 57)\n {\n if (!inNumber)\n {\n numStart = i;\n numLength = 1;\n inNumber = true;\n continue;\n }\n numLength++;\n continue;\n }\n if (inNumber)\n {\n sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n inNumber = false;\n }\n isDecimal = (charCode == 46);\n sb.Append(val[i]);\n }\n if (inNumber)\n sb.Append(PadNumber(val.Substring(numStart, numLength), isDecimal, padLength));\n\n var ret = sb.ToString();\n if (ret.Length > maxLength)\n return ret.Substring(0, maxLength);\n\n return ret;\n }\n\n static string PadNumber(string num, bool isDecimal, int padLength)\n {\n return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');\n }\n}\n CREATE ASSEMBLY SqlServerClr FROM 'SqlServerClr.dll' --put the full path to DLL here\ngo\nCREATE FUNCTION Naturalize(@val as nvarchar(max)) RETURNS nvarchar(1000) \nEXTERNAL NAME SqlServerClr.UDF.Naturalize\ngo\n select *\nfrom MyTable\norder by dbo.Naturalize(MyTextField)\n"
},
{
"answer_id": 3887921,
"author": "Seph",
"author_id": 288747,
"author_profile": "https://Stackoverflow.com/users/288747",
"pm_score": 4,
"selected": false,
"text": "SELECT [Column] FROM [Table]\nORDER BY RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))), 1000)\n 1 1.15 1.5 {1, 1.5, 1.15} SELECT [Column] FROM [Table]\nORDER BY REPLACE(RIGHT(REPLICATE('0', 1000) + LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX)))) + REPLICATE('0', 100 - CHARINDEX('.', REVERSE(LTRIM(RTRIM(CAST([Column] AS VARCHAR(MAX))))), 1)), 1000), '.', '0')\n {1, 1.15, 1.5}"
},
{
"answer_id": 5587314,
"author": "plalx",
"author_id": 1211528,
"author_profile": "https://Stackoverflow.com/users/1211528",
"pm_score": 3,
"selected": false,
"text": "/**\n * Returns a string formatted for natural sorting. This function is very useful when having to sort alpha-numeric strings.\n *\n * @author Alexandre Potvin Latreille (plalx)\n * @param {nvarchar(4000)} string The formatted string.\n * @param {int} numberLength The length each number should have (including padding). This should be the length of the longest number. Defaults to 10.\n * @param {char(50)} sameOrderChars A list of characters that should have the same order. Ex: '.-/'. Defaults to empty string.\n *\n * @return {nvarchar(4000)} A string for natural sorting.\n * Example of use: \n * \n * SELECT Name FROM TableA ORDER BY Name\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1-1. \n * 2. A1-1. 2. A1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R11\n * 5. R2 5. R2\n *\n * \n * As we can see, humans would expect A1., A1-1., R1, R2, R11 but that's not how SQL is sorting it.\n * We can use this function to fix this.\n *\n * SELECT Name FROM TableA ORDER BY dbo.udf_NaturalSortFormat(Name, default, '.-')\n * TableA (unordered) TableA (ordered)\n * ------------ ------------\n * ID Name ID Name\n * 1. A1. 1. A1. \n * 2. A1-1. 2. A1-1.\n * 3. R1 --> 3. R1\n * 4. R11 4. R2\n * 5. R2 5. R11\n */\nALTER FUNCTION [dbo].[udf_NaturalSortFormat](\n @string nvarchar(4000),\n @numberLength int = 10,\n @sameOrderChars char(50) = ''\n)\nRETURNS varchar(4000)\nAS\nBEGIN\n DECLARE @sortString varchar(4000),\n @numStartIndex int,\n @numEndIndex int,\n @padLength int,\n @totalPadLength int,\n @i int,\n @sameOrderCharsLen int;\n\n SELECT \n @totalPadLength = 0,\n @string = RTRIM(LTRIM(@string)),\n @sortString = @string,\n @numStartIndex = PATINDEX('%[0-9]%', @string),\n @numEndIndex = 0,\n @i = 1,\n @sameOrderCharsLen = LEN(@sameOrderChars);\n\n -- Replace all char that have the same order by a space.\n WHILE (@i <= @sameOrderCharsLen)\n BEGIN\n SET @sortString = REPLACE(@sortString, SUBSTRING(@sameOrderChars, @i, 1), ' ');\n SET @i = @i + 1;\n END\n\n -- Pad numbers with zeros.\n WHILE (@numStartIndex <> 0)\n BEGIN\n SET @numStartIndex = @numStartIndex + @numEndIndex;\n SET @numEndIndex = @numStartIndex;\n\n WHILE(PATINDEX('[0-9]', SUBSTRING(@string, @numEndIndex, 1)) = 1)\n BEGIN\n SET @numEndIndex = @numEndIndex + 1;\n END\n\n SET @numEndIndex = @numEndIndex - 1;\n\n SET @padLength = @numberLength - (@numEndIndex + 1 - @numStartIndex);\n\n IF @padLength < 0\n BEGIN\n SET @padLength = 0;\n END\n\n SET @sortString = STUFF(\n @sortString,\n @numStartIndex + @totalPadLength,\n 0,\n REPLICATE('0', @padLength)\n );\n\n SET @totalPadLength = @totalPadLength + @padLength;\n SET @numStartIndex = PATINDEX('%[0-9]%', RIGHT(@string, LEN(@string) - @numEndIndex));\n END\n\n RETURN @sortString;\nEND\n"
},
{
"answer_id": 5682368,
"author": "jack.mike.info",
"author_id": 707910,
"author_profile": "https://Stackoverflow.com/users/707910",
"pm_score": 1,
"selected": false,
"text": "ORDER BY \ncast (substring(name,(PATINDEX('%[0-9]%',name)),len(name))as int)\n\n ##\n"
},
{
"answer_id": 7410173,
"author": "Gut Feeling",
"author_id": 816701,
"author_profile": "https://Stackoverflow.com/users/816701",
"pm_score": 2,
"selected": false,
"text": "varchar BR1\nBR2\nExternal Location\nIR1\nIR2\nIR3\nIR4\nIR5\nIR6\nIR7\nIR8\nIR9\nIR10\nIR11\nIR12\nIR13\nIR14\nIR16\nIR17\nIR15\nVCR\n ORDER BY substring(fieldName, 1, 1), LEN(fieldName)\n"
},
{
"answer_id": 13375351,
"author": "Simon",
"author_id": 888392,
"author_profile": "https://Stackoverflow.com/users/888392",
"pm_score": 2,
"selected": false,
"text": "CREATE or REPLACE FUNCTION pad_numbers(text) RETURNS text AS $$\n SELECT regexp_replace(regexp_replace(regexp_replace(regexp_replace(($1 collate \"C\"),\n E'(^|\\\\D)(\\\\d{1,3}($|\\\\D))', E'\\\\1000\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{4,6}($|\\\\D))', E'\\\\1000\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{7}($|\\\\D))', E'\\\\100\\\\2', 'g'),\n E'(^|\\\\D)(\\\\d{8}($|\\\\D))', E'\\\\10\\\\2', 'g');\n$$ LANGUAGE SQL;\n SELECT * FROM wtf w \n WHERE TRUE\n ORDER BY pad_numbers(w.my_alphanumeric_field)\n"
},
{
"answer_id": 19471828,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 3,
"selected": false,
"text": "[SqlFunction(DataAccess = DataAccessKind.None,\n SystemDataAccess = SystemDataAccessKind.None,\n IsDeterministic = true, IsPrecise = true)]\n CREATE FUNCTION Naturalize(@str AS nvarchar(max)) RETURNS nvarchar(450)\n EXTERNAL NAME ClrExtensions.Util.Naturalize\n const int maxLength = 450;\n Naturalize ALTER TABLE YourTable ADD nameNaturalized AS dbo.Naturalize(name) PERSISTED\n CREATE INDEX idx_YourTable_n ON YourTable (nameNaturalized)\n using System.Data.SqlTypes;\nusing System.Text;\nusing Microsoft.SqlServer.Server;\n\npublic static class Util\n{\n [SqlFunction(DataAccess = DataAccessKind.None, SystemDataAccess = SystemDataAccessKind.None, IsDeterministic = true, IsPrecise = true)]\n public static SqlString Naturalize(string str)\n {\n if (string.IsNullOrEmpty(str))\n return str;\n\n const int maxLength = 450;\n const int padLength = 15;\n\n bool isDecimal = false;\n bool wasSpace = false;\n int numStart = 0;\n int numLength = 0;\n\n var sb = new StringBuilder();\n for (var i = 0; i < str.Length; i++)\n {\n char c = str[i];\n if (c >= '0' && c <= '9')\n {\n if (numLength == 0)\n numStart = i;\n numLength++;\n }\n else\n {\n if (numLength > 0)\n {\n sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n numLength = 0;\n }\n if (c != ' ' || !wasSpace)\n sb.Append(c);\n isDecimal = c == '.';\n if (sb.Length > maxLength)\n break;\n }\n wasSpace = c == ' ';\n }\n if (numLength > 0)\n sb.Append(pad(str.Substring(numStart, numLength), isDecimal, padLength));\n\n if (sb.Length > maxLength)\n sb.Length = maxLength;\n return sb.ToString();\n }\n\n private static string pad(string num, bool isDecimal, int padLength)\n {\n return isDecimal ? num.PadRight(padLength, '0') : num.PadLeft(padLength, '0');\n }\n}\n"
},
{
"answer_id": 71357605,
"author": "ShrapNull",
"author_id": 1652234,
"author_profile": "https://Stackoverflow.com/users/1652234",
"pm_score": 0,
"selected": false,
"text": "CREATE FUNCTION udfAlphaNumericSortHelper (\n@string varchar(max)\n)\nRETURNS @results TABLE (\n txt varchar(max),\n num float\n)\nAS\nBEGIN\n\n DECLARE @txt varchar(max) = @string\n DECLARE @numStr varchar(max) = ''\n DECLARE @num float = 0\n DECLARE @lastChar varchar(1) = ''\n\n set @lastChar = RIGHT(@txt, 1)\n WHILE @lastChar <> '' and @lastChar is not null\n BEGIN \n IF ISNUMERIC(@lastChar) = 1\n BEGIN \n set @numStr = @lastChar + @numStr\n set @txt = Substring(@txt, 0, len(@txt))\n set @lastChar = RIGHT(@txt, 1)\n END\n ELSE\n BEGIN \n set @lastChar = null\n END\n END\n SET @num = CAST(@numStr as float)\n\n INSERT INTO @results select @txt, @num\n RETURN;\nEND\n declare @str nvarchar(250) = 'sox,fox,jen1,Jen0,jen15,jen02,jen0004,fox00,rec1,rec10,jen3,rec14,rec2,rec20,rec3,rec4,zip1,zip1.32,zip1.33,zip1.3,TT0001,TT01,TT002'\n\n\nSELECT tbl.value --, sorter.txt, sorter.num\nFROM STRING_SPLIT(@str, ',') as tbl\nCROSS APPLY dbo.udfAlphaNumericSortHelper(value) as sorter\nORDER BY sorter.txt, sorter.num, len(tbl.value)\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
34,510 |
<p>When writing multithreaded applications, one of the most common problems experienced is race conditions.</p>
<p>My questions to the community are:</p>
<ul>
<li>What is the race condition?</li>
<li>How do you detect them?</li>
<li>How do you handle them?</li>
<li>Finally, how do you prevent them from occurring?</li>
</ul>
|
[
{
"answer_id": 34537,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 5,
"selected": false,
"text": "if( object.a != 0 )\n object.avg = total / object.a\n object.a = 0\n a = 0"
},
{
"answer_id": 34550,
"author": "Lehane",
"author_id": 142,
"author_profile": "https://Stackoverflow.com/users/142",
"pm_score": 12,
"selected": true,
"text": "if (x == 5) // The \"Check\"\n{\n y = x * 2; // The \"Act\"\n\n // If another thread changed x in between \"if (x == 5)\" and \"y = x * 2\" above,\n // y will not be equal to 10.\n}\n // Obtain lock for x\nif (x == 5)\n{\n y = x * 2; // Now, nothing can change x until the lock is released. \n // Therefore y = 10\n}\n// release lock for x\n"
},
{
"answer_id": 34745,
"author": "privatehuff",
"author_id": 2570347,
"author_profile": "https://Stackoverflow.com/users/2570347",
"pm_score": 8,
"selected": false,
"text": "for ( int i = 0; i < 10000000; i++ )\n{\n x = x + 1; \n}\n for ( int i = 0; i < 10000000; i++ )\n{\n //lock x\n x = x + 1; \n //unlock x\n}\n"
},
{
"answer_id": 8222450,
"author": "realPK",
"author_id": 853001,
"author_profile": "https://Stackoverflow.com/users/853001",
"pm_score": 0,
"selected": false,
"text": "public class BankAccount {\n\n/**\n * @param args\n */\nint accountNumber;\ndouble accountBalance;\n\npublic synchronized boolean Deposit(double amount){\n double newAccountBalance=0;\n if(amount<=0){\n return false;\n }\n else {\n newAccountBalance = accountBalance+amount;\n accountBalance=newAccountBalance;\n return true;\n }\n\n}\npublic synchronized boolean Withdraw(double amount){\n double newAccountBalance=0;\n if(amount>accountBalance){\n return false;\n }\n else{\n newAccountBalance = accountBalance-amount;\n accountBalance=newAccountBalance;\n return true;\n }\n}\n\npublic static void main(String[] args) {\n // TODO Auto-generated method stub\n BankAccount b = new BankAccount();\n b.accountBalance=2000;\n System.out.println(b.Withdraw(3000));\n\n}\n"
},
{
"answer_id": 16861236,
"author": "Morsu",
"author_id": 2440915,
"author_profile": "https://Stackoverflow.com/users/2440915",
"pm_score": 0,
"selected": false,
"text": " public class ThreadRaceCondition {\n\n /**\n * @param args\n * @throws InterruptedException\n */\n public static void main(String[] args) throws InterruptedException {\n Account myAccount = new Account(22222222);\n\n // Expected deposit: 250\n for (int i = 0; i < 50; i++) {\n Transaction t = new Transaction(myAccount,\n Transaction.TransactionType.DEPOSIT, 5.00);\n t.start();\n }\n\n // Expected withdrawal: 50\n for (int i = 0; i < 50; i++) {\n Transaction t = new Transaction(myAccount,\n Transaction.TransactionType.WITHDRAW, 1.00);\n t.start();\n\n }\n\n // Temporary sleep to ensure all threads are completed. Don't use in\n // realworld :-)\n Thread.sleep(1000);\n // Expected account balance is 200\n System.out.println(\"Final Account Balance: \"\n + myAccount.getAccountBalance());\n\n }\n\n}\n\nclass Transaction extends Thread {\n\n public static enum TransactionType {\n DEPOSIT(1), WITHDRAW(2);\n\n private int value;\n\n private TransactionType(int value) {\n this.value = value;\n }\n\n public int getValue() {\n return value;\n }\n };\n\n private TransactionType transactionType;\n private Account account;\n private double amount;\n\n /*\n * If transactionType == 1, deposit else if transactionType == 2 withdraw\n */\n public Transaction(Account account, TransactionType transactionType,\n double amount) {\n this.transactionType = transactionType;\n this.account = account;\n this.amount = amount;\n }\n\n public void run() {\n switch (this.transactionType) {\n case DEPOSIT:\n deposit();\n printBalance();\n break;\n case WITHDRAW:\n withdraw();\n printBalance();\n break;\n default:\n System.out.println(\"NOT A VALID TRANSACTION\");\n }\n ;\n }\n\n public void deposit() {\n this.account.deposit(this.amount);\n }\n\n public void withdraw() {\n this.account.withdraw(amount);\n }\n\n public void printBalance() {\n System.out.println(Thread.currentThread().getName()\n + \" : TransactionType: \" + this.transactionType + \", Amount: \"\n + this.amount);\n System.out.println(\"Account Balance: \"\n + this.account.getAccountBalance());\n }\n}\n\nclass Account {\n private int accountNumber;\n private double accountBalance;\n\n public int getAccountNumber() {\n return accountNumber;\n }\n\n public double getAccountBalance() {\n return accountBalance;\n }\n\n public Account(int accountNumber) {\n this.accountNumber = accountNumber;\n }\n\n // If this method is not synchronized, you will see race condition on\n // Remove syncronized keyword to see race condition\n public synchronized boolean deposit(double amount) {\n if (amount < 0) {\n return false;\n } else {\n accountBalance = accountBalance + amount;\n return true;\n }\n }\n\n // If this method is not synchronized, you will see race condition on\n // Remove syncronized keyword to see race condition\n public synchronized boolean withdraw(double amount) {\n if (amount > accountBalance) {\n return false;\n } else {\n accountBalance = accountBalance - amount;\n return true;\n }\n }\n}\n"
},
{
"answer_id": 31424696,
"author": "bharanitharan",
"author_id": 358099,
"author_profile": "https://Stackoverflow.com/users/358099",
"pm_score": 0,
"selected": false,
"text": "int i = 0;\n CounterThread -> i = 1 \nDisplayThread -> i = 1 \nCounterThread -> i = 2 \nCounterThread -> i = 3 \nCounterThread -> i = 4 \nDisplayThread -> i = 4\n"
},
{
"answer_id": 45498041,
"author": "nybon",
"author_id": 84540,
"author_profile": "https://Stackoverflow.com/users/84540",
"pm_score": 5,
"selected": false,
"text": "race condition race condition"
},
{
"answer_id": 45651528,
"author": "Aleksei Moshkov",
"author_id": 5031817,
"author_profile": "https://Stackoverflow.com/users/5031817",
"pm_score": 2,
"selected": false,
"text": "AtomicInteger ai = new AtomicInteger(2);\nai.getAndAdd(5);\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
34,512 |
<p>When writing multi-threaded applications, one of the most common problems experienced are deadlocks. </p>
<p>My questions to the community are:</p>
<ol>
<li><p>What is a deadlock? </p></li>
<li><p>How do you detect them? </p></li>
<li><p>Do you handle them? </p></li>
<li><p>And finally, how do you prevent them from occurring?</p></li>
</ol>
|
[
{
"answer_id": 34546,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 4,
"selected": false,
"text": "Thread 1 Thread 2\n\nLock1->Lock(); Lock2->Lock();\nWaitForLock2(); WaitForLock1(); <-- Oops!\n"
},
{
"answer_id": 18998026,
"author": "onmyway133",
"author_id": 1418457,
"author_profile": "https://Stackoverflow.com/users/1418457",
"pm_score": 3,
"selected": false,
"text": "object locker1 = new object();\nobject locker2 = new object();\n\nnew Thread (() => {\n lock (locker1)\n {\n Thread.Sleep (1000);\n lock (locker2); // Deadlock\n }\n }).Start();\nlock (locker2)\n{\n Thread.Sleep (1000);\n lock (locker1); // Deadlock\n}\n"
},
{
"answer_id": 30101507,
"author": "Varun",
"author_id": 3454208,
"author_profile": "https://Stackoverflow.com/users/3454208",
"pm_score": 5,
"selected": false,
"text": "program"
},
{
"answer_id": 50011904,
"author": "Arun Raaj",
"author_id": 4334162,
"author_profile": "https://Stackoverflow.com/users/4334162",
"pm_score": 0,
"selected": false,
"text": "jcmd $PID Thread.print\n"
},
{
"answer_id": 51961244,
"author": "Vivek Pratap Singh",
"author_id": 3758710,
"author_profile": "https://Stackoverflow.com/users/3758710",
"pm_score": 1,
"selected": false,
"text": "public class Lazy {\n\n private static boolean initialized = false;\n\n static {\n Thread t = new Thread(new Runnable() {\n public void run() {\n initialized = true;\n }\n });\n\n t.start();\n\n try {\n t.join();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n System.out.println(initialized);\n }\n}\n"
},
{
"answer_id": 58605921,
"author": "Vlad Mihalcea",
"author_id": 1025118,
"author_profile": "https://Stackoverflow.com/users/1025118",
"pm_score": 2,
"selected": false,
"text": "ACID UPDATE DELETE Atomicity Thread stop interrupt"
},
{
"answer_id": 73669574,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 0,
"selected": false,
"text": "deadlock"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
34,516 |
<p>Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?</p>
|
[
{
"answer_id": 34530,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n///\n/// </summary>\n/// <param name=\"strFilePath\"></param>\n"
},
{
"answer_id": 34533,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 6,
"selected": true,
"text": "/// <summary>\n/// Authenticates a user based on a username and password.\n/// </summary>\n/// <param name=\"username\">The username.</param>\n/// <param name=\"password\">The password.</param>\n/// <returns>\n/// True, if authentication is successful, otherwise False.\n/// </returns>\n/// <remarks>\n/// For use with local systems\n/// </remarks>\npublic override bool Authenticate(string username, string password)\n"
},
{
"answer_id": 699654,
"author": "GameFreak",
"author_id": 26659,
"author_profile": "https://Stackoverflow.com/users/26659",
"pm_score": 0,
"selected": false,
"text": "/**\nDocumentation goes here.\n(flowerboxes optional) \n*/\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
34,518 |
<p>How do you sort an array of strings <a href="http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/" rel="nofollow noreferrer">naturally</a> in different programming languages? Post your implementation and what language it is in in the answer.</p>
|
[
{
"answer_id": 34528,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "Array.prototype.alphanumSort = function(caseInsensitive) {\n for (var z = 0, t; t = this[z]; z++) {\n this[z] = [], x = 0, y = -1, n = 0, i, j;\n\n while (i = (j = t.charAt(x++)).charCodeAt(0)) {\n var m = (i == 46 || (i >=48 && i <= 57));\n if (m !== n) {\n this[z][++y] = \"\";\n n = m;\n }\n this[z][y] += j;\n }\n }\n\n this.sort(function(a, b) {\n for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {\n if (caseInsensitive) {\n aa = aa.toLowerCase();\n bb = bb.toLowerCase();\n }\n if (aa !== bb) {\n var c = Number(aa), d = Number(bb);\n if (c == aa && d == bb) {\n return c - d;\n } else return (aa > bb) ? 1 : -1;\n }\n }\n return a.length - b.length;\n });\n\n for (var z = 0; z < this.length; z++)\n this[z] = this[z].join(\"\");\n}\n"
},
{
"answer_id": 34542,
"author": "Rytis",
"author_id": 979,
"author_profile": "https://Stackoverflow.com/users/979",
"pm_score": 3,
"selected": false,
"text": "ORDER BY natsort_canon(field_name, 'natural')"
},
{
"answer_id": 34780,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<stdlib.h> qsort /* non-functional mess deleted */\n #include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n\nint naturalstrcmp(const char **s1, const char **s2);\n\nint main(int argc, char **argv){\n /* Sort the command line arguments in place */\n qsort(&argv[1],argc-1,sizeof(char*),\n (int(*)(const void *, const void *))naturalstrcmp);\n\n while(--argc){\n printf(\"%s\\n\",(++argv)[0]);\n };\n}\n\nint naturalstrcmp(const char **s1p, const char **s2p){\n if ((NULL == s1p) || (NULL == *s1p)) {\n if ((NULL == s2p) || (NULL == *s2p)) return 0;\n return 1;\n };\n if ((NULL == s2p) || (NULL == *s2p)) return -1;\n\n const char *s1=*s1p;\n const char *s2=*s2p;\n\n do {\n if (isdigit(s1[0]) && isdigit(s2[0])){ \n /* Compare numbers as numbers */\n int c1 = strspn(s1,\"0123456789\"); /* Could be more efficient here... */\n int c2 = strspn(s2,\"0123456789\");\n if (c1 > c2) {\n return 1;\n } else if (c1 < c2) {\n return -1;\n };\n /* the digit strings have equal length, so compare digit by digit */\n while (c1--) {\n if (s1[0] > s2[0]){\n return 1;\n } else if (s1[0] < s2[0]){\n return -1;\n }; \n s1++;\n s2++;\n };\n } else if (s1[0] > s2[0]){\n return 1;\n } else if (s1[0] < s2[0]){\n return -1;\n }; \n s1++;\n s2++;\n } while ( (s1!='\\0') || (s2!='\\0') );\n return 0;\n}\n"
},
{
"answer_id": 341599,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "bool NaturalLess(const wstring &lhs, const wstring &rhs)\n{\n return StrCmpLogicalW(lhs.c_str(), rhs.c_str()) < 0;\n}\n\nvector<wstring> strings;\n// ... load the strings\nsort(strings.begin(), strings.end(), &NaturalLess);\n"
},
{
"answer_id": 341730,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 3,
"selected": false,
"text": "def sorted_nicely(strings): \n \"Sort strings the way humans are said to expect.\"\n return sorted(strings, key=natural_sort_key)\n\ndef natural_sort_key(key):\n import re\n return [int(t) if t.isdigit() else t for t in re.split(r'(\\d+)', key)]\n"
},
{
"answer_id": 341745,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/env python\n\"\"\"\n>>> items = u'a1 a003 b2 a2 a10 1 10 20 2 c100'.split()\n>>> items.sort(explorer_cmp)\n>>> for s in items:\n... print s,\n1 2 10 20 a1 a2 a003 a10 b2 c100\n>>> items.sort(key=natural_key, reverse=True)\n>>> for s in items:\n... print s,\nc100 b2 a10 a003 a2 a1 20 10 2 1\n\"\"\"\nimport re\n\ndef natural_key(astr):\n \"\"\"See http://www.codinghorror.com/blog/archives/001018.html\"\"\"\n return [int(s) if s.isdigit() else s for s in re.split(r'(\\d+)', astr)]\n\ndef natural_cmp(a, b):\n return cmp(natural_key(a), natural_key(b))\n\ntry: # use explorer's comparison function if available\n import ctypes\n explorer_cmp = ctypes.windll.shlwapi.StrCmpLogicalW\nexcept (ImportError, AttributeError):\n # not on Windows or old python version\n explorer_cmp = natural_cmp \n\nif __name__ == '__main__':\n import doctest; doctest.testmod()\n .isdecimal() .isdigit() .isdigit() int()"
},
{
"answer_id": 753548,
"author": "RHSeeger",
"author_id": 26816,
"author_profile": "https://Stackoverflow.com/users/26816",
"pm_score": 0,
"selected": false,
"text": "% lsort -dict {a b 1 c 2 d 13}\n1 2 13 a b c d\n"
},
{
"answer_id": 753739,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 1,
"selected": false,
"text": "type String_Array is array(Natural range <>) of Ada.Strings.Unbounded.Unbounded_String;\nfunction \"<\" (L, R : Ada.Strings.Unbounded.Unbounded_String) return boolean is\nbegin\n --// Natural ordering predicate here. Sorry to cheat in this part, but\n --// I don't exactly grok the requirement for \"natural\" ordering. Fill in \n --// your proper code here.\nend \"<\";\nprocedure Sort is new Ada.Containers.Generic_Array_Sort \n (Index_Type => Natural;\n Element_Type => Ada.Strings.Unbounded.Unbounded_String,\n Array_Type => String_Array\n );\n using Ada.Strings.Unbounded;\n\n Example : String_Array := (To_Unbounded_String (\"Joe\"),\n To_Unbounded_String (\"Jim\"),\n To_Unbounded_String (\"Jane\"),\n To_Unbounded_String (\"Fred\"),\n To_Unbounded_String (\"Bertha\"),\n To_Unbounded_String (\"Joesphus\"),\n To_Unbounded_String (\"Jonesey\"));\nbegin\n Sort (Example);\n ...\nend;\n"
},
{
"answer_id": 1344071,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 2,
"selected": false,
"text": "#include <stdlib.h>\n#include <ctype.h>\n\n/* like strcmp but compare sequences of digits numerically */\nint strcmpbynum(const char *s1, const char *s2) {\n for (;;) {\n if (*s2 == '\\0')\n return *s1 != '\\0';\n else if (*s1 == '\\0')\n return 1;\n else if (!(isdigit(*s1) && isdigit(*s2))) {\n if (*s1 != *s2)\n return (int)*s1 - (int)*s2;\n else\n (++s1, ++s2);\n } else {\n char *lim1, *lim2;\n unsigned long n1 = strtoul(s1, &lim1, 10);\n unsigned long n2 = strtoul(s2, &lim2, 10);\n if (n1 > n2)\n return 1;\n else if (n1 < n2)\n return -1;\n s1 = lim1;\n s2 = lim2;\n }\n }\n}\n qsort static int compare(const void *p1, const void *p2) {\n const char * const *ps1 = p1;\n const char * const *ps2 = p2;\n return strcmpbynum(*ps1, *ps2);\n}\n char *lines = ...;\nqsort(lines, next, sizeof(lines[0]), compare);\n"
},
{
"answer_id": 4001057,
"author": "adw",
"author_id": 484688,
"author_profile": "https://Stackoverflow.com/users/484688",
"pm_score": 1,
"selected": false,
"text": "def natural_key(s):\n return tuple(\n int(''.join(chars)) if isdigit else ''.join(chars)\n for isdigit, chars in itertools.groupby(s, str.isdigit)\n )\n >>> natural_key('abc-123foo456.xyz')\n('abc-', 123, 'foo', 456, '.xyz')\n >>> sorted(['1.1.1', '1.10.4', '1.5.0', '42.1.0', '9', 'banana'], key=natural_key)\n['1.1.1', '1.5.0', '1.10.4', '9', '42.1.0', 'banana']\n"
},
{
"answer_id": 6924517,
"author": "Thang Mai",
"author_id": 807672,
"author_profile": "https://Stackoverflow.com/users/807672",
"pm_score": 1,
"selected": false,
"text": "(ns alphanumeric-sort\n (:import [java.util.regex Pattern]))\n\n(defn comp-alpha-numerical\n \"Compare two strings alphanumerically.\"\n [a b]\n (let [regex (Pattern/compile \"[\\\\d]+|[a-zA-Z]+\")\n sa (re-seq regex a)\n sb (re-seq regex b)]\n (loop [seqa sa seqb sb]\n (let [counta (count seqa)\n countb (count seqb)]\n (if-not (not-any? zero? [counta countb]) (- counta countb)\n (let [c (first seqa)\n d (first seqb)\n c1 (read-string c)\n d1 (read-string d)]\n (if (every? integer? [c1 d1]) \n (def result (compare c1 d1)) (def result (compare c d)))\n (if-not (= 0 result) result (recur (rest seqa) (rest seqb)))))))))\n\n(sort comp-alpha-numerical [\"a1\" \"a003\" \"b2\" \"a10\" \"a2\" \"1\" \"10\" \"20\" \"2\" \"c100\"])\n"
},
{
"answer_id": 26478632,
"author": "grant sun",
"author_id": 3509287,
"author_profile": "https://Stackoverflow.com/users/3509287",
"pm_score": 0,
"selected": false,
"text": "<?php\n$temp_files = array('+====','-==',\"temp15-txt\",\"temp10.txt\",\n\"temp1.txt\",\"tempe22.txt\",\"temp2.txt\");\n$my_arr = $temp_files;\n\n\nnatsort($temp_files);\necho \"Natural order: \";\nprint_r($temp_files);\n\n\necho \"My Natural order: \";\nusort($my_arr,'my_nat_func');\nprint_r($my_arr);\n\n\nfunction is_alpha($a){\n return $a>='0'&&$a<='9' ;\n}\n\nfunction my_nat_func($a,$b){\n if(preg_match('/[0-9]/',$a)){\n if(preg_match('/[0-9]/',$b)){\n $i=0;\n while(!is_alpha($a[$i])) ++$i;\n $m = intval(substr($a,$i)); \n $i=0;\n while(!is_alpha($b[$i])) ++$i;\n $n = intval(substr($b,$i));\n return $m>$n?1:($m==$n?0:-1);\n }\n return 1;\n }else{\n if(preg_match('/[0-9]/',$b)){\n return -1;\n }\n return $a>$b?1:($a==$b?0:-1);\n }\n}\n"
},
{
"answer_id": 71668742,
"author": "vsk.rahul",
"author_id": 3116461,
"author_profile": "https://Stackoverflow.com/users/3116461",
"pm_score": 0,
"selected": false,
"text": "Comparator<String> Collections.sort(list, comparator) @Override\npublic int compare(String s1, String s2) {\n int len1 = s1.length();\n int len2 = s2.length();\n int lim = Math.min(len1, len2);\n char v1[] = s1.toCharArray();\n char v2[] = s2.toCharArray();\n\n int k = 0;\n while (k < lim) {\n char c1 = v1[k];\n char c2 = v2[k];\n if (c1 != c2) {\n if(this.isInteger(c1) && this.isInteger(c2)) {\n int i1 = grabContinousInteger(v1, k);\n int i2 = grabContinousInteger(v2, k);\n return i1 - i2;\n }\n return c1 - c2;\n }\n k++;\n }\n return len1 - len2;\n}\n\nprivate boolean isInteger(char c) {\n return c >= 48 && c <= 57; // ascii value 0-9\n}\n\nprivate int grabContinousInteger(char[] arr, int k) {\n \n int i = k;\n while(i < arr.length && this.isInteger(arr[i])) {\n i++;\n }\n return Integer.parseInt(new String(arr, k, i - k));\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] |
34,519 |
<p>A semaphore is a programming concept that is frequently used to solve multi-threading problems. My question to the community: </p>
<p>What is a semaphore and how do you use it?</p>
|
[
{
"answer_id": 40410,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": false,
"text": "V P V P P P"
},
{
"answer_id": 40473,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 9,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Threading;\n\nnamespace TheNightclub\n{\n public class Program\n {\n public static Semaphore Bouncer { get; set; }\n\n public static void Main(string[] args)\n {\n // Create the semaphore with 3 slots, where 3 are available.\n Bouncer = new Semaphore(3, 3);\n\n // Open the nightclub.\n OpenNightclub();\n }\n\n public static void OpenNightclub()\n {\n for (int i = 1; i <= 50; i++)\n {\n // Let each guest enter on an own thread.\n Thread thread = new Thread(new ParameterizedThreadStart(Guest));\n thread.Start(i);\n }\n }\n\n public static void Guest(object args)\n {\n // Wait to enter the nightclub (a semaphore to be released).\n Console.WriteLine(\"Guest {0} is waiting to entering nightclub.\", args);\n Bouncer.WaitOne(); \n\n // Do some dancing.\n Console.WriteLine(\"Guest {0} is doing some dancing.\", args);\n Thread.Sleep(500);\n\n // Let one guest out (release one semaphore).\n Console.WriteLine(\"Guest {0} is leaving the nightclub.\", args);\n Bouncer.Release(1);\n }\n }\n}\n"
},
{
"answer_id": 23545993,
"author": "aspen100",
"author_id": 2112500,
"author_profile": "https://Stackoverflow.com/users/2112500",
"pm_score": 4,
"selected": false,
"text": "thread A{\nsemaphore &s; //locks/semaphores are passed by reference! think about why this is so.\nA(semaphore &s): s(s){} //constructor\nfoo(){\n...\ns.P();\n;// some block of code B2\n...\n}\n\n//thread B{\nsemaphore &s;\nB(semaphore &s): s(s){} //constructor\nfoo(){\n...\n...\n// some block of code B1\ns.V();\n..\n}\n\nmain(){\nsemaphore s(0); // we start the semaphore at 0 (closed)\nA a(s);\nB b(s);\n}\n thread mutual_ex{\nsemaphore &s;\nmutual_ex(semaphore &s): s(s){} //constructor\nfoo(){\n...\ns.P();\n//critical section\ns.V();\n...\n...\ns.P();\n//critical section\ns.V();\n...\n\n}\n\nmain(){\nsemaphore s(1);\nmutual_ex m1(s);\nmutual_ex m2(s);\n}\n thread t1{\n...\ns.P();\n//block of code B1\n\nthread t2{\n...\ns.P();\n//block of code B2\n\nthread t3{\n...\n//block of code B3\ns.V();\ns.V();\n}\n"
},
{
"answer_id": 44971803,
"author": "NKumar",
"author_id": 5532090,
"author_profile": "https://Stackoverflow.com/users/5532090",
"pm_score": 5,
"selected": false,
"text": "semaphore mutex Mutex Semaphore"
},
{
"answer_id": 52093990,
"author": "Volodymyr",
"author_id": 1245166,
"author_profile": "https://Stackoverflow.com/users/1245166",
"pm_score": 3,
"selected": false,
"text": "ExecutorService executor = Executors.newFixedThreadPool(7);\n\nSemaphore semaphore = new Semaphore(4);\n\nRunnable longRunningTask = () -> {\n boolean permit = false;\n try {\n permit = semaphore.tryAcquire(1, TimeUnit.SECONDS);\n if (permit) {\n System.out.println(\"Semaphore acquired\");\n Thread.sleep(5);\n } else {\n System.out.println(\"Could not acquire semaphore\");\n }\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n } finally {\n if (permit) {\n semaphore.release();\n }\n }\n};\n\n// execute tasks\nfor (int j = 0; j < 10; j++) {\n executor.submit(longRunningTask);\n}\nexecutor.shutdown();\n Semaphore acquired\nSemaphore acquired\nSemaphore acquired\nSemaphore acquired\nCould not acquire semaphore\nCould not acquire semaphore\nCould not acquire semaphore\n"
},
{
"answer_id": 57520626,
"author": "sumit",
"author_id": 10828672,
"author_profile": "https://Stackoverflow.com/users/10828672",
"pm_score": 2,
"selected": false,
"text": "acquire() release() package practice;\n import java.util.concurrent.Semaphore;\n\n public class SemaphoreExample {\n public static void main(String[] args) {\n Semaphore s = new Semaphore(1);\n semaphoreTask s1 = new semaphoreTask(s);\n semaphoreTask s2 = new semaphoreTask(s);\n semaphoreTask s3 = new semaphoreTask(s);\n semaphoreTask s4 = new semaphoreTask(s);\n semaphoreTask s5 = new semaphoreTask(s);\n s1.start();\n s2.start();\n s3.start();\n s4.start();\n s5.start();\n }\n }\n\n class semaphoreTask extends Thread {\n Semaphore s;\n public semaphoreTask(Semaphore s) {\n this.s = s;\n }\n @Override\n public void run() {\n try {\n s.acquire();\n Thread.sleep(1000);\n System.out.println(Thread.currentThread().getName()+\" Going to perform some operation\");\n s.release();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n } \n }\n"
},
{
"answer_id": 71113133,
"author": "Pithikos",
"author_id": 474563,
"author_profile": "https://Stackoverflow.com/users/474563",
"pm_score": 0,
"selected": false,
"text": "lock.set()\na += 1\nlock.unset()\n lock lock"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
34,524 |
<p>A mutex is a programming concept that is frequently used to solve multi-threading problems. My question to the community: </p>
<p>What is a mutex and how do you use it?</p>
|
[
{
"answer_id": 34574,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 5,
"selected": false,
"text": "private static readonly Object instanceLock = new Object();\nprivate static MySingleton instance;\npublic static MySingleton Instance\n{\n lock(instanceLock)\n {\n if(instance == null)\n {\n instance = new MySingleton();\n }\n return instance;\n }\n}\n"
},
{
"answer_id": 51146022,
"author": "habib",
"author_id": 5559267,
"author_profile": "https://Stackoverflow.com/users/5559267",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Threading;\n\nclass Example\n{\n // Create a new Mutex. The creating thread does not own the mutex.\n private static Mutex mut = new Mutex();\n private const int numIterations = 1;\n private const int numThreads = 3;\n\n static void Main()\n {\n // Create the threads that will use the protected resource.\n for(int i = 0; i < numThreads; i++)\n {\n Thread newThread = new Thread(new ThreadStart(ThreadProc));\n newThread.Name = String.Format(\"Thread{0}\", i + 1);\n newThread.Start();\n }\n\n // The main thread exits, but the application continues to\n // run until all foreground threads have exited.\n }\n\n private static void ThreadProc()\n {\n for(int i = 0; i < numIterations; i++)\n {\n UseResource();\n }\n }\n\n // This method represents a resource that must be synchronized\n // so that only one thread at a time can enter.\n private static void UseResource()\n {\n // Wait until it is safe to enter.\n Console.WriteLine(\"{0} is requesting the mutex\", \n Thread.CurrentThread.Name);\n mut.WaitOne();\n\n Console.WriteLine(\"{0} has entered the protected area\", \n Thread.CurrentThread.Name);\n\n // Place code to access non-reentrant resources here.\n\n // Simulate some work.\n Thread.Sleep(500);\n\n Console.WriteLine(\"{0} is leaving the protected area\", \n Thread.CurrentThread.Name);\n\n // Release the Mutex.\n mut.ReleaseMutex();\n Console.WriteLine(\"{0} has released the mutex\", \n Thread.CurrentThread.Name);\n }\n}\n// The example displays output like the following:\n// Thread1 is requesting the mutex\n// Thread2 is requesting the mutex\n// Thread1 has entered the protected area\n// Thread3 is requesting the mutex\n// Thread1 is leaving the protected area\n// Thread1 has released the mutex\n// Thread3 has entered the protected area\n// Thread3 is leaving the protected area\n// Thread3 has released the mutex\n// Thread2 has entered the protected area\n// Thread2 is leaving the protected area\n// Thread2 has released the mutex\n"
},
{
"answer_id": 59878707,
"author": "Sandeep_black",
"author_id": 7277468,
"author_profile": "https://Stackoverflow.com/users/7277468",
"pm_score": 3,
"selected": false,
"text": "typedef union\n{\n struct __pthread_mutex_s\n {\n ***int __lock;***\n unsigned int __count;\n int __owner;\n#ifdef __x86_64__\n unsigned int __nusers;\n#endif\nint __kind;\n#ifdef __x86_64__\n short __spins;\n short __elision;\n __pthread_list_t __list;\n# define __PTHREAD_MUTEX_HAVE_PREV 1\n# define __PTHREAD_SPINS 0, 0\n#else\n unsigned int __nusers;\n __extension__ union\n {\n struct\n {\n short __espins;\n short __elision;\n# define __spins __elision_data.__espins\n# define __elision __elision_data.__elision\n# define __PTHREAD_SPINS { 0, 0 }\n } __elision_data;\n __pthread_slist_t __list;\n };\n#endif\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
34,536 |
<p>This most be the second most simple rollover effect, still I don't find any simple solution.</p>
<p><strong>Wanted:</strong> I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.</p>
<p>The following code works, but <em>is awful</em>. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.</p>
<pre><code><script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
</code></pre>
|
[
{
"answer_id": 34617,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js\"></script>\n<script type=\"text/javascript\">\n$(function () {\n $(\"#switches li\").mouseover(function () {\n var $this = $(this);\n $(\"#slides div\").hide();\n $(\"#slide\" + $this.attr(\"id\").replace(/switch/, \"\")).show();\n $(\"#switches li\").css(\"font-weight\", \"normal\");\n $this.css(\"font-weight\", \"bold\");\n });\n});\n</script>\n\n<ul id=\"switches\">\n <li id=\"switch1\" style=\"font-weight:bold;\">First slide</li>\n <li id=\"switch2\">Second slide</li>\n <li id=\"switch3\">Third slide</li>\n <li id=\"switch4\">Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div id=\"slide1\">Well well.</div>\n <div id=\"slide2\" style=\"display:none;\">Oh no!</div>\n <div id=\"slide3\" style=\"display:none;\">You again?</div>\n <div id=\"slide4\" style=\"display:none;\">I'm gone!</div>\n</div>\n"
},
{
"answer_id": 34646,
"author": "Dmitry Mukhin",
"author_id": 3448,
"author_profile": "https://Stackoverflow.com/users/3448",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\n\n$(document).ready(\n function(){\n $( '#switches li' ).mouseover(\n function(){\n $( \"#slides div\" ).hide();\n $( '#switches li' ).css( 'font-weight', 'normal' );\n $( this ).css( 'font-weight', 'bold' );\n $( '#slide' + $( this ).attr( 'id' ).replace( 'switch', '' ) ).show();\n }\n );\n }\n);\n\n</script>\n</head>\n<body>\n<ul id=\"switches\">\n <li id=\"switch1\" style=\"font-weight:bold;\">First slide</li>\n <li id=\"switch2\">Second slide</li>\n <li id=\"switch3\">Third slide</li>\n <li id=\"switch4\">Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div id=\"slide1\">Well well.</div>\n <div id=\"slide2\" style=\"display:none;\">Oh no!</div>\n <div id=\"slide3\" style=\"display:none;\">You again?</div>\n <div id=\"slide4\" style=\"display:none;\">I'm gone!</div>\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 34710,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 5,
"selected": true,
"text": "$(document).ready(function() {\n switches = $('#switches > li');\n slides = $('#slides > div');\n switches.each(function(idx) {\n $(this).data('slide', slides.eq(idx));\n }).hover(\n function() {\n switches.removeClass('active');\n slides.removeClass('active');\n $(this).addClass('active');\n $(this).data('slide').addClass('active');\n });\n}); #switches .active {\n font-weight: bold;\n}\n#slides div {\n display: none;\n}\n#slides div.active {\n display: block;\n} <html>\n\n<head>\n\n <title>test</title>\n\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n <script type=\"text/javascript\" src=\"switch.js\"></script>\n\n</head>\n\n<body>\n\n <ul id=\"switches\">\n <li class=\"active\">First slide</li>\n <li>Second slide</li>\n <li>Third slide</li>\n <li>Fourth slide</li>\n </ul>\n <div id=\"slides\">\n <div class=\"active\">Well well.</div>\n <div>Oh no!</div>\n <div>You again?</div>\n <div>I'm gone!</div>\n </div>\n\n</body>\n\n</html>"
},
{
"answer_id": 34718,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 3,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\nfunction switchTo(i) {\n $('#switches li').css('font-weight','normal').eq(i).css('font-weight','bold');\n $('#slides div').css('display','none').eq(i).css('display','block');\n}\n$(document).ready(function(){\n $('#switches li').mouseover(function(event){\n switchTo($('#switches li').index(event.target));\n });\n switchTo(0);\n});\n</script>\n<ul id=\"switches\">\n <li>First slide</li>\n <li>Second slide</li>\n <li>Third slide</li>\n <li>Fourth slide</li>\n</ul>\n<div id=\"slides\">\n <div>Well well.</div>\n <div>Oh no!</div>\n <div>You again?</div>\n <div>I'm gone!</div>\n</div>\n switchTo <li> <div> display:none list-item div bold display"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
] |
34,565 |
<p>Additionally, how can I format it as a string padded with zeros?</p>
|
[
{
"answer_id": 34582,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 7,
"selected": false,
"text": "rand(10 ** 10)\n '%010d' % rand(10 ** 10)\n rjust rand(10 ** 10).to_s.rjust(10,'0') \n"
},
{
"answer_id": 175678,
"author": "Grant Hutchins",
"author_id": 6304,
"author_profile": "https://Stackoverflow.com/users/6304",
"pm_score": 2,
"selected": false,
"text": "'%011d' % rand(1e10)\n 1e10 Float Kernel#rand to_i '%011d' % rand(10_000_000_000) # Note that underscores are ignored in integer literals\n"
},
{
"answer_id": 11442975,
"author": "Poseidon_Geek",
"author_id": 1269764,
"author_profile": "https://Stackoverflow.com/users/1269764",
"pm_score": 2,
"selected": false,
"text": "rand (10**10) code = rand(10**10)\nwhile code.to_s.length != 10\ncode = rand(11**11)\n"
},
{
"answer_id": 18161300,
"author": "Kreeki",
"author_id": 559316,
"author_profile": "https://Stackoverflow.com/users/559316",
"pm_score": 6,
"selected": false,
"text": "rand.to_s[2..11] \n => \"5950281724\"\n"
},
{
"answer_id": 18789508,
"author": "Gabriel Osorio",
"author_id": 2192331,
"author_profile": "https://Stackoverflow.com/users/2192331",
"pm_score": 3,
"selected": false,
"text": "Kernel#sprintf Kernel#format String#% # considered bad\n'%010d' % rand(10**10)\n\n# considered good\nsprintf('%010d', rand(10**10))\n % % # bad\n'%d %d' % [20, 10]\n# => '20 10'\n\n# good\nsprintf('%d %d', 20, 10)\n# => '20 10'\n\n# good\nsprintf('%{first} %{second}', first: 20, second: 10)\n# => '20 10'\n\nformat('%d %d', 20, 10)\n# => '20 10'\n\n# good\nformat('%{first} %{second}', first: 20, second: 10)\n# => '20 10'\n String#% your_array << 'foo' your_array.push('123')"
},
{
"answer_id": 25682945,
"author": "Tan Nguyen",
"author_id": 2245697,
"author_profile": "https://Stackoverflow.com/users/2245697",
"pm_score": 1,
"selected": false,
"text": "rand(9999999999).to_s.center(10, rand(9).to_s).to_i\n rand.to_s[2..11].to_i\n puts Benchmark.measure{(1..1000000).map{rand(9999999999).to_s.center(10, rand(9).to_s).to_i}}\n puts Benchmark.measure{(1..1000000).map{rand.to_s[2..11].to_i}}\n"
},
{
"answer_id": 30456635,
"author": "Kamil Lelonek",
"author_id": 1313175,
"author_profile": "https://Stackoverflow.com/users/1313175",
"pm_score": 4,
"selected": false,
"text": "rand.to_s[2..11].to_i rand.to_s[2..9] #=> \"04890612\"\n \"04890612\".to_i #=> 4890612\n 4890612.to_s.length #=> 7\n .to_i Integer(rand.to_s[2..9])\n ArgumentError: invalid value for Integer(): \"02939053\"\n .center rand(9) \n 0 rand(1..9)\n 1..9"
},
{
"answer_id": 31043708,
"author": "John La Rooy",
"author_id": 174728,
"author_profile": "https://Stackoverflow.com/users/174728",
"pm_score": 2,
"selected": false,
"text": "(1..10).map{\"0123456789\".chars.to_a.sample}.join\n=> \"6383411680\"\n"
},
{
"answer_id": 31043825,
"author": "art-solopov",
"author_id": 2733119,
"author_profile": "https://Stackoverflow.com/users/2733119",
"pm_score": 4,
"selected": false,
"text": "rand(1e9...1e10).to_i to_i 1e9 1e10 irb(main)> 1e9.class\n=> Float\n"
},
{
"answer_id": 35785079,
"author": "steenslag",
"author_id": 290394,
"author_profile": "https://Stackoverflow.com/users/290394",
"pm_score": 5,
"selected": false,
"text": "10.times.map{rand(10)}.join # => \"3401487670\"\n"
},
{
"answer_id": 39995528,
"author": "Rahul Patel",
"author_id": 2334864,
"author_profile": "https://Stackoverflow.com/users/2334864",
"pm_score": 2,
"selected": false,
"text": "Random.new.rand((10**(n - 1))..(10**n))\n Random.new.rand((10**(10 - 1))..(10**10))\n"
},
{
"answer_id": 43346807,
"author": "907th",
"author_id": 1247092,
"author_profile": "https://Stackoverflow.com/users/1247092",
"pm_score": 4,
"selected": false,
"text": "rand(1_000_000_000..9_999_999_999) # => random 10-digits number\n times map join 10.times.map { rand(0..9) }.join # => random 10-digit string (may start with 0!)\n \"%010d\" % 123348 # => \"0000123348\"\n KeePass::Password.generate(\"d{10}\") # => random 10-digit string (may start with 0!)\n"
},
{
"answer_id": 45458745,
"author": "Tom Lord",
"author_id": 1954610,
"author_profile": "https://Stackoverflow.com/users/1954610",
"pm_score": 1,
"selected": false,
"text": "regexp-examples require 'regexp-examples'\n\n/\\d{10}/.random_example # => \"0826423747\"\n String"
},
{
"answer_id": 50966721,
"author": "Anderson Marques",
"author_id": 6646873,
"author_profile": "https://Stackoverflow.com/users/6646873",
"pm_score": 0,
"selected": false,
"text": "Array.new() .times.map string_size = 9\nArray.new(string_size) do\n rand(10).to_s\nend\n"
},
{
"answer_id": 52075422,
"author": "Lalit Kumar Maurya",
"author_id": 1637683,
"author_profile": "https://Stackoverflow.com/users/1637683",
"pm_score": 2,
"selected": false,
"text": "rand(10 ** 9...10 ** 10)\n (1..1000).each { puts rand(10 ** 9...10 ** 10) }\n"
},
{
"answer_id": 53654592,
"author": "Mario Ruiz",
"author_id": 2546667,
"author_profile": "https://Stackoverflow.com/users/2546667",
"pm_score": -1,
"selected": false,
"text": "require 'string_pattern'\nputs \"10:N\".gen\n"
},
{
"answer_id": 54283486,
"author": "kazuwombat",
"author_id": 5992952,
"author_profile": "https://Stackoverflow.com/users/5992952",
"pm_score": 0,
"selected": false,
"text": " module StringUtil\n refine String.singleton_class do\n def generate_random_digits(size:)\n proc = lambda{ rand.to_s[2...(2 + size)] }\n if block_given?\n loop do\n generated = proc.call\n break generated if yield(generated) # check generated num meets condition\n end\n else\n proc.call\n end\n end\n end\n end\n using StringUtil\n String.generate_random_digits(3) => \"763\"\n String.generate_random_digits(3) do |num|\n User.find_by(code: num).nil?\n end => \"689\"(This is unique in Users code)\n"
},
{
"answer_id": 55379711,
"author": "Khalil Gharbaoui",
"author_id": 5641227,
"author_profile": "https://Stackoverflow.com/users/5641227",
"pm_score": 2,
"selected": false,
"text": "('%010d' % rand(0..9999999999)).to_s \"#{'%010d' % rand(0..9999999999)}\""
},
{
"answer_id": 56564214,
"author": "Eliot Sykes",
"author_id": 67834,
"author_profile": "https://Stackoverflow.com/users/67834",
"pm_score": 2,
"selected": false,
"text": "# This generates a 10-digit string, where the\n# minimum possible value is \"0000000000\", and the\n# maximum possible value is \"9999999999\"\nSecureRandom.random_number(10**10).to_s.rjust(10, '0')\n # Calculate the upper bound for the random number generator\n # upper_bound = 10,000,000,000\n upper_bound = 10**10\n\n # n will be an integer with a minimum possible value of 0,\n # and a maximum possible value of 9,999,999,999\n n = SecureRandom.random_number(upper_bound)\n\n # Convert the integer n to a string\n # unpadded_str will be \"0\" if n == 0\n # unpadded_str will be \"9999999999\" if n == 9_999_999_999\n unpadded_str = n.to_s\n\n # Pad the string with leading zeroes if it is less than\n # 10 digits long.\n # \"0\" would be padded to \"0000000000\"\n # \"123\" would be padded to \"0000000123\"\n # \"9999999999\" would not be padded, and remains unchanged as \"9999999999\"\n padded_str = unpadded_str.rjust(10, '0')\n"
},
{
"answer_id": 63454165,
"author": "Anton Semenichenko",
"author_id": 7809709,
"author_profile": "https://Stackoverflow.com/users/7809709",
"pm_score": 3,
"selected": false,
"text": "srand srand.to_s.last(10)"
},
{
"answer_id": 67246974,
"author": "MD Tawab Alam Khan",
"author_id": 11111981,
"author_profile": "https://Stackoverflow.com/users/11111981",
"pm_score": 0,
"selected": false,
"text": "x = 10 #Number of digit\n(rand(10 ** x) + 10**x).to_s[0..x-1]\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] |
34,571 |
<p>How do I use JUnit to test a class that has internal private methods, fields or nested classes?</p>
<p>It seems bad to change the access modifier for a method just to be able to run a test.</p>
|
[
{
"answer_id": 34658,
"author": "Cem Catikkas",
"author_id": 3087,
"author_profile": "https://Stackoverflow.com/users/3087",
"pm_score": 12,
"selected": true,
"text": "private private static private private static private static final Method method = TargetClass.getDeclaredMethod(methodName, argClasses);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, argObjects);\n Field field = TargetClass.getDeclaredField(fieldName);\nfield.setAccessible(true);\nfield.set(object, value);\n TargetClass.getDeclaredMethod(methodName, argClasses) private getDeclaredField setAccessible(true)"
},
{
"answer_id": 38425,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 5,
"selected": false,
"text": "// Import statements and package declarations\n\npublic class ClassToTest\n{\n private int decrement(int toDecrement) {\n toDecrement--;\n return toDecrement;\n }\n\n // Constructor and the rest of the class\n\n public static class StaticInnerTest extends TestCase\n {\n public StaticInnerTest(){\n super();\n }\n\n public void testDecrement(){\n int number = 10;\n ClassToTest toTest= new ClassToTest();\n int decremented = toTest.decrement(number);\n assertEquals(9, decremented);\n }\n\n public static void main(String[] args) {\n junit.textui.TestRunner.run(StaticInnerTest.class);\n }\n }\n}\n ClassToTest$StaticInnerTest"
},
{
"answer_id": 549558,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 3,
"selected": false,
"text": "setAccessible(true)"
},
{
"answer_id": 549592,
"author": "Thomas Hansen",
"author_id": 29746,
"author_profile": "https://Stackoverflow.com/users/29746",
"pm_score": 2,
"selected": false,
"text": "System.Reflection"
},
{
"answer_id": 1038507,
"author": "Diego Amicabile",
"author_id": 126875,
"author_profile": "https://Stackoverflow.com/users/126875",
"pm_score": 2,
"selected": false,
"text": "src classes test/src test/classes classes test/classes"
},
{
"answer_id": 3177465,
"author": "Richard Le Mesurier",
"author_id": 383414,
"author_profile": "https://Stackoverflow.com/users/383414",
"pm_score": 6,
"selected": false,
"text": "SecurityManager"
},
{
"answer_id": 4667692,
"author": "phareim",
"author_id": 373975,
"author_profile": "https://Stackoverflow.com/users/373975",
"pm_score": 5,
"selected": false,
"text": "import junitx.util.PrivateAccessor;\n\nPrivateAccessor.setField(myObjectReference, \"myCrucialButHardToReachPrivateField\", myNewValue);\nPrivateAccessor.invoke(myObjectReference, \"privateMethodName\", java.lang.Class[] parameterTypes, java.lang.Object[] args);\n"
},
{
"answer_id": 8139572,
"author": "marc wellman",
"author_id": 946904,
"author_profile": "https://Stackoverflow.com/users/946904",
"pm_score": 2,
"selected": false,
"text": "Test-Port t_ Test-Port Test-Port Test-Port"
},
{
"answer_id": 15192546,
"author": "Steven Bluen",
"author_id": 419109,
"author_profile": "https://Stackoverflow.com/users/419109",
"pm_score": 1,
"selected": false,
"text": "private /*@ spec_public @*/ int methodName(){\n...\n}\n"
},
{
"answer_id": 18859235,
"author": "Snicolas",
"author_id": 693752,
"author_profile": "https://Stackoverflow.com/users/693752",
"pm_score": 4,
"selected": false,
"text": "@UiThreadTest\npublic void testCompute() {\n\n // Given\n boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());\n\n // When\n boundBoxOfMainActivity.boundBox_getButtonMain().performClick();\n\n // Then\n assertEquals(\"42\", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());\n}\n"
},
{
"answer_id": 20990300,
"author": "Yuli Reiri",
"author_id": 1789360,
"author_profile": "https://Stackoverflow.com/users/1789360",
"pm_score": 4,
"selected": false,
"text": "protected <F> F getPrivateField(String fieldName, Object obj)\n throws NoSuchFieldException, IllegalAccessException {\n Field field =\n obj.getClass().getDeclaredField(fieldName);\n\n field.setAccessible(true);\n return (F)field.get(obj);\n}\n"
},
{
"answer_id": 26855013,
"author": "Steve Chambers",
"author_id": 1063716,
"author_profile": "https://Stackoverflow.com/users/1063716",
"pm_score": 5,
"selected": false,
"text": "ReflectionTestUtils.setField(theClass, \"theUnsettableField\", theMockObject);\n"
},
{
"answer_id": 30093076,
"author": "CoronA",
"author_id": 4497253,
"author_profile": "https://Stackoverflow.com/users/4497253",
"pm_score": 3,
"selected": false,
"text": "private void method(String s) Method method = targetClass.getDeclaredMethod(\"method\", String.class);\nmethod.setAccessible(true);\nreturn method.invoke(targetObject, \"mystring\");\n private void method(String s) interface Accessible {\n void method(String s);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.method(\"mystring\");\n private BigInteger amount; Field field = targetClass.getDeclaredField(\"amount\");\nfield.setAccessible(true);\nfield.set(object, BigInteger.valueOf(42));\n private BigInteger amount; interface Accessible {\n void setAmount(BigInteger amount);\n}\n\n...\nAccessible a = ObjectAccess.unlock(targetObject).features(Accessible.class);\na.setAmount(BigInteger.valueOf(42));\n"
},
{
"answer_id": 31020978,
"author": "Mikhail",
"author_id": 1781357,
"author_profile": "https://Stackoverflow.com/users/1781357",
"pm_score": 6,
"selected": false,
"text": "ReflectionTestUtils.invokeMethod()\n ReflectionTestUtils.invokeMethod(TestClazz, \"createTest\", \"input data\");\n"
},
{
"answer_id": 36115967,
"author": "supernova",
"author_id": 538160,
"author_profile": "https://Stackoverflow.com/users/538160",
"pm_score": 6,
"selected": false,
"text": "src/main/java/mypackage/MyClass.java src/test/java/mypackage/MyClassTest.java"
},
{
"answer_id": 37591098,
"author": "Olcay Tarazan",
"author_id": 2335016,
"author_profile": "https://Stackoverflow.com/users/2335016",
"pm_score": 4,
"selected": false,
"text": "import org.powermock.reflect.Whitebox;\n Whitebox.invokeMethod(obj, \"privateMethod\", \"param1\");\n"
},
{
"answer_id": 37618628,
"author": "Legna",
"author_id": 2197088,
"author_profile": "https://Stackoverflow.com/users/2197088",
"pm_score": 2,
"selected": false,
"text": "@Rule\npublic ExpectedException thrown = ExpectedException.none();\n\n@Autowired(required = true)\nprivate BizService svc;\n\n\n@Test\npublic void testValidateRequest() throws Exception {\n\n thrown.expect(BizException.class);\n thrown.expectMessage(expectMessage);\n\n BizRequest request = /* Mock it, read from source - file, etc. */;\n validateRequest(request);\n}\n\nprivate void validateRequest(BizRequest request) throws Exception {\n Method method = svc.getClass().getDeclaredMethod(\"validateRequest\", BizRequest.class);\n method.setAccessible(true);\n try {\n method.invoke(svc, request);\n }\n catch (InvocationTargetException e) {\n throw ((BizException)e.getCause());\n }\n }\n"
},
{
"answer_id": 39215279,
"author": "GROX13",
"author_id": 3930424,
"author_profile": "https://Stackoverflow.com/users/3930424",
"pm_score": 4,
"selected": false,
"text": "public class ClassToTest {\n\n private final String first = \"first\";\n private final List<String> second = new ArrayList<>();\n ...\n}\n public class ClassToTest {\n\n private final String first;\n private final List<String> second;\n\n public ClassToTest() {\n this(\"first\", new ArrayList<>());\n }\n\n public ClassToTest(final String first, final List<String> second) {\n this.first = first;\n this.second = second;\n }\n ...\n}\n Callable public ClassToTest() {\n this(...);\n}\n\npublic ClassToTest(final Callable<T> privateMethodLogic) {\n this.privateMethodLogic = privateMethodLogic;\n}\n"
},
{
"answer_id": 46121866,
"author": "Rahul",
"author_id": 7599315,
"author_profile": "https://Stackoverflow.com/users/7599315",
"pm_score": 1,
"selected": false,
"text": "MyClient classUnderTest = PowerMockito.spy(new MyClient());\n\n// Set the expected return value\nPowerMockito.doReturn(20).when(classUnderTest, \"myPrivateMethod\", anyString(), anyInt());\n// This is very important. Otherwise, it will not work\nclassUnderTest.myPrivateMethod();\n\n// Setting the private field value as someValue:\nWhitebox.setInternalState(classUnderTest, \"privateField\", someValue);\n String msg = Whitebox.invokeMethod(obj, \"privateMethodToBeTested\", \"param1\");\nAssert.assertEquals(privateMsg, msg);\n // To get the value of a private field\nMyClass obj = Whitebox.getInternalState(classUnderTest, \"foo\");\nassertThat(obj, is(notNull(MyClass.class))); // Or test value\n"
},
{
"answer_id": 48182688,
"author": "mohammad madani",
"author_id": 1125774,
"author_profile": "https://Stackoverflow.com/users/1125774",
"pm_score": 3,
"selected": false,
"text": "#define private public\n#define protected public\n"
},
{
"answer_id": 48430793,
"author": "Victor Grazi",
"author_id": 522729,
"author_profile": "https://Stackoverflow.com/users/522729",
"pm_score": 4,
"selected": false,
"text": " <dependency>\n <groupId>org.powermock</groupId>\n <artifactId>powermock-core</artifactId>\n <version>2.0.7</version>\n <scope>test</scope>\n </dependency>\n import org.powermock.reflect.Whitebox;\n...\nMyClass sut = new MyClass();\nSomeType rval = Whitebox.invokeMethod(sut, \"myPrivateMethod\", params, moreParams);\n"
},
{
"answer_id": 53768967,
"author": "Louis Saglio",
"author_id": 7629797,
"author_profile": "https://Stackoverflow.com/users/7629797",
"pm_score": 1,
"selected": false,
"text": "import org.jetbrains.annotations.TestOnly\n\nclass MyClass {\n\n private void aPrivateMethod() {}\n\n @TestOnly\n public void aPrivateMethodForTest() {\n aPrivateMethod()\n }\n}\n"
},
{
"answer_id": 55588184,
"author": "Ercan",
"author_id": 4308897,
"author_profile": "https://Stackoverflow.com/users/4308897",
"pm_score": 0,
"selected": false,
"text": "assert (\"Ercan\".equals(person1.name));\nassert (Person.count == 2);\n"
},
{
"answer_id": 56100192,
"author": "WesternGun",
"author_id": 4537090,
"author_profile": "https://Stackoverflow.com/users/4537090",
"pm_score": 2,
"selected": false,
"text": "PowerMock.Whitebox Powermock.Whitebox Whitebox Whitebox testImplementation 'org.mockito:mockito-core:1.10.19' org.mockito.internal test main test private @Autowired\nprivate SomeService service; // with a package private method \"doSomething()\"\n\n@Test\nvoid shouldReturnTrueDoSomething() {\n assertThat(doSomething(input), is(true)); // package private method testing\n}\n\n@Test\nvoid shouldReturnTrueWhenServiceThrowsException() {\n SomeService spy = Mockito.spy(service); // spying real object\n doThrow(new AppException()).when(spy).doSomething(input); // spy package private method\n ...\n\n}\n ReflectionUtils.setField()"
},
{
"answer_id": 57010282,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 2,
"selected": false,
"text": "@VisibleForTesting android.support.annotation @VisibleForTesting otherwise otherwise @VisibleForTesting package com.mypackage;\n\npublic class ClassA {\n\n @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)\n static void myMethod() {\n\n }\n}\n"
},
{
"answer_id": 57514468,
"author": "avtomaton",
"author_id": 2915032,
"author_profile": "https://Stackoverflow.com/users/2915032",
"pm_score": 0,
"selected": false,
"text": "Foo FooTest // prod.h: some production code header\n\n// forward declaration is enough\n// we should not include testing headers into production code\nclass FooTest;\n\nclass Foo\n{\n // that does not affect Foo's functionality\n // but now we have access to Foo's members from FooTest\n friend FooTest;\npublic:\n Foo();\nprivate:\n bool veryComplicatedPrivateFuncThatReallyRequiresTesting();\n}\n // test.cpp: some test\n#include <prod.h>\n\nclass FooTest\n{\npublic:\n void complicatedFisture() {\n Foo foo;\n ASSERT_TRUE(foo.veryComplicatedPrivateFuncThatReallyRequiresTesting());\n }\n}\n\nint main(int /*argc*/, char* argv[])\n{\n FooTest test;\n test.complicatedFixture(); // and it really works!\n}\n"
},
{
"answer_id": 58452308,
"author": "Mukundhan",
"author_id": 6769119,
"author_profile": "https://Stackoverflow.com/users/6769119",
"pm_score": 0,
"selected": false,
"text": "import com.google.common.base.Preconditions;\n\nimport org.springframework.test.util.ReflectionTestUtils;\n\n/**\n * <p>\n * Invoker\n * </p>\n *\n * @author\n * @created Oct-10-2019\n */\npublic class Invoker {\n private Object target;\n private String methodName;\n private Object[] arguments;\n\n public <T> T invoke() {\n try {\n Preconditions.checkNotNull(target, \"Target cannot be empty\");\n Preconditions.checkNotNull(methodName, \"MethodName cannot be empty\");\n if (null == arguments) {\n return ReflectionTestUtils.invokeMethod(target, methodName);\n } else {\n return ReflectionTestUtils.invokeMethod(target, methodName, arguments);\n }\n } catch (Exception e) {\n throw e;\n }\n }\n\n public Invoker withTarget(Object target) {\n this.target = target;\n return this;\n }\n\n public Invoker withMethod(String methodName) {\n this.methodName = methodName;\n return this;\n }\n\n public Invoker withArguments(Object... args) {\n this.arguments = args;\n return this;\n }\n\n}\n\nObject privateMethodResponse = new Invoker()\n .withTarget(targetObject)\n .withMethod(PRIVATE_METHOD_NAME_TO_INVOKE)\n .withArguments(arg1, arg2, arg3)\n .invoke();\nAssert.assertNotNutll(privateMethodResponse)\n"
},
{
"answer_id": 60675043,
"author": "Abhishek Sengupta",
"author_id": 9389293,
"author_profile": "https://Stackoverflow.com/users/9389293",
"pm_score": 2,
"selected": false,
"text": "ReflectionTestUtils.invokeMethod(new ClassName(), \"privateMethodName\");\n"
},
{
"answer_id": 62632701,
"author": "Ahmed Hussein",
"author_id": 7280140,
"author_profile": "https://Stackoverflow.com/users/7280140",
"pm_score": -1,
"selected": false,
"text": "namespace my_namespace {\n #ifdef UNIT_TEST\n class test_class;\n #endif\n\n class my_class {\n public:\n #ifdef UNIT_TEST\n friend class test_class;\n #endif\n private:\n void fun() { cout << \"I am private\" << endl; }\n }\n}\n #ifndef UNIT_TEST\n #define UNIT_TEST\n#endif\n\n#include \"my_class.h\"\n\nclass my_namespace::test_class {\n public:\n void fun() { my_obj.fun(); }\n private:\n my_class my_obj;\n}\n\nvoid my_unit_test() {\n test_class test_obj;\n test_obj.fun(); // here you accessed the private function ;)\n}\n"
},
{
"answer_id": 63069114,
"author": "m.nguyencntt",
"author_id": 3110488,
"author_profile": "https://Stackoverflow.com/users/3110488",
"pm_score": 2,
"selected": false,
"text": "public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {\n Student student = new Student();\n\n Field privateFieldName = Student.class.getDeclaredField(\"name\");\n privateFieldName.setAccessible(true);\n privateFieldName.set(student, \"Naruto\");\n\n Field privateFieldAge = Student.class.getDeclaredField(\"age\");\n privateFieldAge.setAccessible(true);\n privateFieldAge.set(student, \"28\");\n\n System.out.println(student.toString());\n\n Method privateMethodGetInfo = Student.class.getDeclaredMethod(\"getInfo\", String.class, String.class);\n privateMethodGetInfo.setAccessible(true);\n System.out.println(privateMethodGetInfo.invoke(student, \"Sasuke\", \"29\"));\n}\n\n\n@Setter\n@Getter\n@ToString\nclass Student {\n private String name;\n private String age;\n \n private String getInfo(String name, String age) {\n return name + \"-\" + age;\n }\n}\n"
},
{
"answer_id": 70938111,
"author": "d3rbastl3r",
"author_id": 2893873,
"author_profile": "https://Stackoverflow.com/users/2893873",
"pm_score": 1,
"selected": false,
"text": "public class ConwaysGameOfLife {\n\n private boolean[][] generationData = new boolean[128][128];\n\n /**\n * Compute the next generation and return the new state\n * Also saving the new state in generationData\n */\n public boolean[][] computeNextGeneration() {\n boolean[][] tempData = new boolean[128][128];\n\n for (int yPos=0; yPos<=generationData.length; yPos++) {\n for (int xPos=0; xPos<=generationData[yPos].length; xPos++) {\n int neighbors = countNeighbors(yPos, xPos);\n tempData[yPos][xPos] = determineCellState(neighbors, yPos, xPos);\n }\n }\n\n generationData = tempData;\n return generationData;\n }\n\n /**\n * Counting the neighbors for a cell on given position considering all the edge cases\n *\n * @return the amount of found neighbors for a cell\n */\n private int countNeighbors(int yPos, int xPos) {}\n\n /**\n * Determine the cell state depending on the amount of neighbors of a cell and on a current state of the cell\n *\n * @return the new cell state\n */\n private boolean determineCellState(int neighborsAmount, int yPos, int xPos) {}\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3098/"
] |
34,579 |
<p>I've recently been working with a MySQL database, and using MySQL workbench to design the Database.</p>
<p>When I use the export to SQL function, so I can actually get the layout in to the Database, I get:</p>
<blockquote>
<p>"Error 1005: Cannot create table"</p>
</blockquote>
<p>This appears to be related to Foreign Keys in the create table statement.</p>
<p>Does anybody have a work around for this that doesn't involve taking the constraints out and putting them back in later? That's a less than ideal solution given the size of the database.</p>
|
[
{
"answer_id": 34713,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 3,
"selected": false,
"text": "SHOW ENGINE INNODB STATUS;\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655/"
] |
34,581 |
<p>I expected the two <code>span</code> tags in the following sample to display next to each other, instead they display one below the other. If I set the <code>width</code> of the class <code>span</code>.right to 49% they display next to each other. I am not able to figure out why the right span is pushed down like the right span has some invisible <code>padding/margin</code> which makes it take more than 50%. I am trying to get this done without using html tables. Any ideas?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
}
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
border: none;
}
div.header {
width: 100%;
height: 80px;
vertical-align: top;
}
span.left {
height: 80px;
width: 50%;
display: inline-block;
background-color: pink;
}
span.right {
vertical-align: top;
display: inline-block;
text-align: right;
height: 80px;
width: 50%;
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>Test Page</title>
</head>
<body>
<div class='header'>
<span class='left'>Left Span 50% width</span>
<span class='right'>Right Span 50% width</span>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<hr />
<p>Thanks for the explanation. The <code>float:left</code> works beautifully with expected results in FF 3.1. Unfortunately, in IE6 the right side span renders 50% of the 50%, in effect giving it a width of 25% of the browser window. Setting its width to 100% achieves the desired results but breaks in FF 3.1 which is in standards compliance mode and I understand that. Getting it to work both in FF and IE 6, without resorting to hacks or using multiple CSS sheets has been a challenge</p>
|
[
{
"answer_id": 34587,
"author": "Teifion",
"author_id": 1384652,
"author_profile": "https://Stackoverflow.com/users/1384652",
"pm_score": 3,
"selected": true,
"text": "float: left;\n"
},
{
"answer_id": 34853,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 1,
"selected": false,
"text": "span.right {\n vertical-align:top; \n display:inline-block;\n text-align:right;\n height:80px;\n width:50%;\n *width:100%;\n background-color:red;\n}\n *width: 100%"
},
{
"answer_id": 16191163,
"author": "eba",
"author_id": 1237397,
"author_profile": "https://Stackoverflow.com/users/1237397",
"pm_score": 2,
"selected": false,
"text": "<div class='header'>\n <span class='left'>Left Span 50% width</span><span class='right'>Right Span 50% width</span>\n</div>\n <div class='header'>\n <span class='left'>Left Span 50% width</span><!--\n --><span class='right'>Right Span 50% width</span>\n</div>\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
] |
34,588 |
<p>When running my application I sometimes get an error about <code>too many files open</code>.</p>
<p>Running <code>ulimit -a</code> reports that the limit is 1024. How do I increase the limit above 1024? </p>
<p><strong>Edit</strong>
<code>ulimit -n 2048</code> results in a permission error.</p>
|
[
{
"answer_id": 34645,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 8,
"selected": true,
"text": "ulimit -n 2048 set rlim_fd_max = 166384\nset rlim_fd_cur = 8192\n kern.maxfilesperproc=166384\nkern.maxfiles=8192\n"
},
{
"answer_id": 923369,
"author": "Jonathan Stanton",
"author_id": 5137,
"author_profile": "https://Stackoverflow.com/users/5137",
"pm_score": 7,
"selected": false,
"text": "/etc/limits.conf /etc/security/limits.conf limits.conf * hard nofile 10000 ulimit -n 10000"
},
{
"answer_id": 8285278,
"author": "Vikrant Telkar",
"author_id": 1067805,
"author_profile": "https://Stackoverflow.com/users/1067805",
"pm_score": 5,
"selected": false,
"text": "/etc/security/limits.conf webuser hard nofile 64000\n su - webuser\n echo \"ulimit -n 64000\" >> .bashrc ; echo \"ulimit -n 64000\" >> .bash_profile\n $ ulimit -a | grep open\nopen files (-n) 64000\n"
},
{
"answer_id": 9521975,
"author": "Sysadmin",
"author_id": 1243439,
"author_profile": "https://Stackoverflow.com/users/1243439",
"pm_score": 3,
"selected": false,
"text": "ulimit -s unlimited /etc/init.d/httpd"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] |
34,595 |
<p>What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:</p>
<pre><code>function Hash(key)
return key mod PrimeNumber
end
</code></pre>
<p>(mod is the % operator in C and similar languages)</p>
<p>with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?</p>
|
[
{
"answer_id": 626599,
"author": "Nick Van Brunt",
"author_id": 30470,
"author_profile": "https://Stackoverflow.com/users/30470",
"pm_score": 3,
"selected": false,
"text": "unsigned fnv_hash_1a_32 ( void *key, int len ) {\n unsigned char *p = key;\n unsigned h = 0x811c9dc5;\n int i;\n\n for ( i = 0; i < len; i++ )\n h = ( h ^ p[i] ) * 0x01000193;\n\n return h;\n}\n\nunsigned long long fnv_hash_1a_64 ( void *key, int len ) {\n unsigned char *p = key;\n unsigned long long h = 0xcbf29ce484222325ULL;\n int i;\n\n for ( i = 0; i < len; i++ )\n h = ( h ^ p[i] ) * 0x100000001b3ULL;\n\n return h;\n}\n"
},
{
"answer_id": 63927109,
"author": "Wolfgang Brehm",
"author_id": 2119377,
"author_profile": "https://Stackoverflow.com/users/2119377",
"pm_score": 1,
"selected": false,
"text": "k (n*(n+1)/2) mod 2^k k"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3485/"
] |
34,635 |
<p>I think the file that is produced is an .asm file, any idea how to produce this in Visual Studio when you do a build?</p>
|
[
{
"answer_id": 34651,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "Configuration Properties -> C/C++ -> Output Files No Listing"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1952/"
] |
34,638 |
<p>The system I am currently working on requires some role-based security, which is well catered for in the Java EE stack. The system intends to be a framework for business domain experts to write their code on top of.</p>
<p>However, there is also a requirement for data <code>security</code>. That is, what information is visible to an end user.</p>
<p>This effectively means reducing visibility to rows (and perhaps even columns) in the database.</p>
<p>We are using Hibernate for our persistence. However, we are using our own annotations so as not to expose our persistence choice to the business domain experts. </p>
<p>For row based security this means we could add an annotation such as <code>@Secured</code> at the entity level, which would cause an extra column to be added to the underlying table to constrain our selects?</p>
<p>For column based security, we could perhaps have <code>@Secured</code> to either assist in query generation, or perhaps use an aspect to filter the information returned?</p>
<p>I'm curious to know how this might affect hibernate's caching mechanisms as well?</p>
<p>I'm sure a lot of others will have had the same issue, and I was wondering how you approached this?</p>
<p>Much appreciated...</p>
|
[
{
"answer_id": 37755,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 1,
"selected": false,
"text": "load() get()"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3295/"
] |
34,655 |
<p>I would like to have an <code>iframe</code> take as much vertical space as it needs to display its content and not display a scrollbar. Is it at all possible ?</p>
<p>Are there any workarounds?</p>
|
[
{
"answer_id": 34663,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "body {\n overflow-x: hidden;\n overflow-y: hidden;\n} \n"
},
{
"answer_id": 34686,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 5,
"selected": true,
"text": "IFRAME <script type=\"text/javascript\">\nthe_height = document.getElementById('the_iframe').contentWindow.document.body.scrollHeight;\ndocument.getElementById('the_iframe').height = the_height;\n</script>\n scrolling=\"no\" IFRAME the_height"
},
{
"answer_id": 288322,
"author": "Adam",
"author_id": 33503,
"author_profile": "https://Stackoverflow.com/users/33503",
"pm_score": 0,
"selected": false,
"text": "DOCTYPE IFRAME document.getElementById('the_iframe').contentWindow.document.body.scrollHeight\n iframe DOCTYPE IFRAME <script type=\"text/javascript\">\n $(document).ready(function(){\n $('iframe').each(function(){\n var context = $(this);\n context.load(function(event){ // attach the onload event to the iframe \n var body = $(this.contentWindow.document).find('body');\n if (body.length > 0 && $(body).find('*').length > 0) { // check if iframe has contents\n context.height($(body.get(0)).height() + 20);\n } else {\n context.hide(); // hide iframes with no contents\n }\n });\n });\n });\n</script>\n"
},
{
"answer_id": 288456,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 0,
"selected": false,
"text": "<iframe>"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983/"
] |
34,661 |
<p>I have an application that sends messages to an external web service. I build and deploy this application using <a href="http://msdn.microsoft.com/en-us/library/wea2sca5(VS.80).aspx" rel="nofollow noreferrer">MSBuild</a> and <a href="http://confluence.public.thoughtworks.org/display/CCNET/Welcome+to+CruiseControl.NET" rel="nofollow noreferrer">Cruisecontrol.NET</a>. As CCNET build and deploys the app it also runs a set of test using <a href="http://www.nunit.org/index.php" rel="nofollow noreferrer">NUnit</a>. I'd now like to test the web service communication as well. </p>
<p>My idea is that as part of the build process a web service should be generated (based on the external web services WSDL) and deployed to the build servers local web server. All the web service should do is to receive the message and place it on the file system so I then can check it using ordinary NUnit for example. This would also make development easier as new developers would only have to run the build script and be up and running (not have to spend time to set up a connection to the third party service). </p>
<p>Are there any <strong>existing utilities out there</strong> that easily mock a web service based on a WSDL? Anyone <strong>done something similar using MSBuild?</strong> </p>
<p>Are there <strong>other ways of testing this scenario?</strong> </p>
|
[
{
"answer_id": 177926,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 1,
"selected": false,
"text": "IService Data GetData() Data var testService = mockery.NewMock<IService>();\nExpect\n .Once\n .On(testService)\n .Method(\"GetService\")\n .WithNoArguments()\n .Will(\n Return.Value(new Data());\n mockery.VerifyAllExpectationsHaveBeenMet() GetData"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/298/"
] |
34,664 |
<p>Has anyone found a useful solution to the DesignMode problem when developing controls?</p>
<p>The issue is that if you nest controls then DesignMode only works for the first level. The second and lower levels DesignMode will always return FALSE.</p>
<p>The standard hack has been to look at the name of the process that is running and if it is "DevEnv.EXE" then it must be studio thus DesignMode is really TRUE.</p>
<p>The problem with that is looking for the ProcessName works its way around through the registry and other strange parts with the end result that the user might not have the required rights to see the process name. In addition this strange route is very slow. So we have had to pile additional hacks to use a singleton and if an error is thrown when asking for the process name then assume that DesignMode is FALSE.</p>
<p>A nice clean way to determine DesignMode is in order. Acually getting Microsoft to fix it internally to the framework would be even better!</p>
|
[
{
"answer_id": 34741,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": " public bool RealDesignMode()\n {\n if (Parent is MyBaseUserControl)\n {\n return (DesignMode ? true : (MyBaseUserControl) Parent.RealDesignMode;\n }\n\n return DesignMode;\n }\n"
},
{
"answer_id": 34842,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "static bool IsDesignMode(Control control)\n{\n PropertyInfo designModeProperty = typeof(Component).\n GetProperty(\"DesignMode\", BindingFlags.Instance | BindingFlags.NonPublic);\n\n while (designModeProperty != null && control != null)\n {\n if((bool)designModeProperty.GetValue(control, null))\n {\n return true;\n }\n control = control.Parent;\n }\n return false;\n}\n"
},
{
"answer_id": 346806,
"author": "hopla",
"author_id": 40972,
"author_profile": "https://Stackoverflow.com/users/40972",
"pm_score": 5,
"selected": false,
"text": "if (LicenseManager.UsageMode == LicenseUsageMode.Runtime)\n{\n bla bla bla...\n}\n"
},
{
"answer_id": 708594,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 7,
"selected": true,
"text": "System.ComponentModel.DesignMode property\n\nSystem.ComponentModel.LicenseManager.UsageMode property\n\nprivate string ServiceString()\n{\n if (GetService(typeof(System.ComponentModel.Design.IDesignerHost)) != null) \n return \"Present\";\n else\n return \"Not present\";\n}\n\npublic bool IsDesignerHosted\n{\n get\n {\n Control ctrl = this;\n\n while(ctrl != null)\n {\n if((ctrl.Site != null) && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n return false;\n }\n}\npublic static bool IsInDesignMode()\n{\n return System.Reflection.Assembly.GetExecutingAssembly()\n .Location.Contains(\"VisualStudio\"))\n}\n"
},
{
"answer_id": 2693338,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 5,
"selected": false,
"text": "/// <summary>\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode. IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and http://stackoverflow.com/a/2693338/238419 )\n/// </summary>\npublic bool IsDesignerHosted\n{\n get\n {\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n return true;\n\n Control ctrl = this;\n while (ctrl != null)\n {\n if ((ctrl.Site != null) && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n return false;\n }\n}\n"
},
{
"answer_id": 2849244,
"author": "Jonathan",
"author_id": 6910,
"author_profile": "https://Stackoverflow.com/users/6910",
"pm_score": 3,
"selected": false,
"text": "public MyUserControl()\n{\n InitializeComponent();\n m_IsInDesignMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);\n}\n\nprivate bool m_IsInDesignMode = true;\npublic bool IsInDesignMode { get { return m_IsInDesignMode; } }\n Sub New()\n InitializeComponent()\n\n m_IsInDesignMode = (LicenseManager.UsageMode = LicenseUsageMode.Designtime)\nEnd Sub\n\nPrivate ReadOnly m_IsInDesignMode As Boolean = True\nPublic ReadOnly Property IsInDesignMode As Boolean\n Get\n Return m_IsInDesignMode\n End Get\nEnd Property\n"
},
{
"answer_id": 3822767,
"author": "husayt",
"author_id": 15461,
"author_profile": "https://Stackoverflow.com/users/15461",
"pm_score": 3,
"selected": false,
"text": " /// <summary>\n /// Gets a value indicating whether this instance is in design mode.\n /// </summary>\n /// <value>\n /// <c>true</c> if this instance is in design mode; otherwise, <c>false</c>.\n /// </value>\n protected bool IsDesignMode\n {\n get { return DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime; }\n }\n"
},
{
"answer_id": 7281838,
"author": "Boris B.",
"author_id": 382783,
"author_profile": "https://Stackoverflow.com/users/382783",
"pm_score": 2,
"selected": false,
"text": "public static bool Runtime { get; private set }"
},
{
"answer_id": 12526432,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 2,
"selected": false,
"text": "public static bool IsRealDesignerMode(this Control c)\n{\n if (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime)\n return true;\n else\n {\n Control ctrl = c;\n\n while (ctrl != null)\n {\n if (ctrl.Site != null && ctrl.Site.DesignMode)\n return true;\n ctrl = ctrl.Parent;\n }\n\n return System.Diagnostics.Process.GetCurrentProcess().ProcessName == \"devenv\";\n }\n}\n"
},
{
"answer_id": 35041620,
"author": "user2785562",
"author_id": 2785562,
"author_profile": "https://Stackoverflow.com/users/2785562",
"pm_score": 2,
"selected": false,
"text": "private bool? m_IsDesignerHosted = null; //contains information about design mode state\n/// <summary>\n/// The DesignMode property does not correctly tell you if\n/// you are in design mode. IsDesignerHosted is a corrected\n/// version of that property.\n/// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n/// and https://stackoverflow.com/a/2693338/238419 )\n/// </summary>\n[Browsable(false)]\npublic bool IsDesignerHosted\n{\n get\n {\n if (m_IsDesignerHosted.HasValue)\n return m_IsDesignerHosted.Value;\n else\n {\n if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n {\n m_IsDesignerHosted = true;\n return true;\n }\n Control ctrl = this;\n while (ctrl != null)\n {\n if ((ctrl.Site != null) && ctrl.Site.DesignMode)\n {\n m_IsDesignerHosted = true;\n return true;\n }\n ctrl = ctrl.Parent;\n }\n m_IsDesignerHosted = false;\n return false;\n }\n }\n}\n"
},
{
"answer_id": 54243122,
"author": "RB Davidson",
"author_id": 113730,
"author_profile": "https://Stackoverflow.com/users/113730",
"pm_score": 0,
"selected": false,
"text": " public static class DesignTimeHelper\n {\n private static bool? _isAssemblyVisualStudio;\n private static bool? _isLicenseDesignTime;\n private static bool? _isProcessDevEnv;\n private static bool? _mIsDesignerHosted; \n\n /// <summary>\n /// Property <see cref=\"Form.DesignMode\"/> does not correctly report if a nested <see cref=\"UserControl\"/>\n /// is in design mode. InDesignMode is a corrected that property which .\n /// (see https://connect.microsoft.com/VisualStudio/feedback/details/553305\n /// and https://stackoverflow.com/a/2693338/238419 )\n /// </summary>\n public static bool InDesignMode(\n this Control userControl,\n string source = null)\n => IsLicenseDesignTime\n || IsProcessDevEnv\n || IsExecutingAssemblyVisualStudio\n || IsDesignerHosted(userControl);\n\n private static bool IsExecutingAssemblyVisualStudio\n => _isAssemblyVisualStudio\n ?? (_isAssemblyVisualStudio = Assembly\n .GetExecutingAssembly()\n .Location.Contains(value: \"VisualStudio\"))\n .Value;\n\n private static bool IsLicenseDesignTime\n => _isLicenseDesignTime\n ?? (_isLicenseDesignTime = LicenseManager.UsageMode == LicenseUsageMode.Designtime)\n .Value;\n\n private static bool IsDesignerHosted(\n Control control)\n {\n if (_mIsDesignerHosted.HasValue)\n return _mIsDesignerHosted.Value;\n\n while (control != null)\n {\n if (control.Site?.DesignMode == true)\n {\n _mIsDesignerHosted = true;\n return true;\n }\n\n control = control.Parent;\n }\n\n _mIsDesignerHosted = false;\n return false;\n }\n\n private static bool IsProcessDevEnv\n => _isProcessDevEnv\n ?? (_isProcessDevEnv = Process.GetCurrentProcess()\n .ProcessName == \"devenv\")\n .Value;\n }\n"
},
{
"answer_id": 70761163,
"author": "Mike L",
"author_id": 7292047,
"author_profile": "https://Stackoverflow.com/users/7292047",
"pm_score": 0,
"selected": false,
"text": "public static bool InDesignMode()\n{ \n return Process.GetCurrentProcess().ProcessName.Contains(\"DesignToolsServer\");\n}\n"
},
{
"answer_id": 74346003,
"author": "PhilH",
"author_id": 5714170,
"author_profile": "https://Stackoverflow.com/users/5714170",
"pm_score": 0,
"selected": false,
"text": "Control.IsAncestorSiteInDesignMode"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2862/"
] |
34,669 |
<p>I have a recursive algorithm which steps through a string, character by character, and parses it to create a tree-like structure. I want to be able to keep track of the character index the parser is currently at (for error messages as much as anything else) but am not keen on implementing something like a tuple to handle multiple returned types.</p>
<p>I tried using an Integer type, declared outside the method and passed into the recursive method, but because it's final, recursive call increments are "forgotten" when I return. (Because the increment of the Integer value makes the passed-by-value object reference point at a new object)</p>
<p>Is there a way to get something similar to work which won't pollute my code?</p>
|
[
{
"answer_id": 34689,
"author": "Andrew Harmel-Law",
"author_id": 2455,
"author_profile": "https://Stackoverflow.com/users/2455",
"pm_score": 2,
"selected": false,
"text": "int[] counter = {0};\n public List<Thing> doIt (String aString, int[] counter) { ... }\n counter[0]++;\n"
},
{
"answer_id": 34856,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 0,
"selected": false,
"text": "doIt public List<Thing> doIt(String aString) {\n List<Thing> list = new ArrayList<Thing>();\n int count = doItHelper(aString, list, 0);\n // ...\n return list;\n}\n\nprivate int doItHelper(String aString, List<Thing> list, int count) {\n // ...\n // do something that updates count\n count = doItHelper(aString, list, count);\n // ...\n return count;\n}\n doIt count public List<Thing> doIt(String aString) throws SomeCustomException {\n List<Thing> list = new ArrayList<Thing>();\n int count = doItHelper(aString, list, 0);\n // ...\n if (someErrorOccurred) {\n throw new SomeCustomException(\"Error occurred at chracter index \" + count, count);\n }\n return list;\n}\n"
},
{
"answer_id": 9588103,
"author": "Jonny",
"author_id": 232206,
"author_profile": "https://Stackoverflow.com/users/232206",
"pm_score": 1,
"selected": false,
"text": "private int recurse (int i) {\n\n if (someConditionkeepOnGoing) {\n i = recurse(i+1);\n }\n\n return i;\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2455/"
] |
34,674 |
<p>You can use a standard dot notation or a method call in Objective-C to access a property of an object in Objective-C.</p>
<pre><code>myObject.property = YES;
</code></pre>
<p>or</p>
<pre><code>[myObject setProperty:YES];
</code></pre>
<p>Is there a difference in performance (in terms of accessing the property)? Is it just a matter of preference in terms of coding style?</p>
|
[
{
"answer_id": 35636,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 5,
"selected": true,
"text": "@interface Foo : NSObject\n@property BOOL bar;\n@end\n\nFoo *foo = [[Foo alloc] init];\nfoo.bar = YES;\n[foo setBar:YES];\n getter setter @interface MyView : NSView\n@property(getter=isEmpty) BOOL empty;\n@end\n\nif ([someView isEmpty]) { /* ... */ }\nif (someView.empty) { /* ... */ }\n"
},
{
"answer_id": 61913,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 3,
"selected": false,
"text": "@synthesize @property (nonatomic, retain) NSString *myProp;\n @synthesize"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1987/"
] |
34,687 |
<p>When I try to do any svn command and supply the <code>--username</code> and/or <code>--password</code> options, it prompts me for my password anyways, and always will attempt to use my current user instead of the one specified by <code>--username</code>. Neither <code>--no-auth-cache</code> nor <code>--non-interactive</code> have any effect on this. This is a problem because I'm trying to call svn commands from a script, and I can't have it show the prompt.</p>
<p>For example, logged in as user1:</p>
<pre><code># $ svn update --username 'user2' --password 'password'
# [email protected]'s password:
</code></pre>
<p>Other options work correctly:</p>
<pre><code># $ svn --version --quiet
# 1.3.2
</code></pre>
<p>Why does it prompt me?<br>
And why is it asking for user1's password instead of user2's?<br>
I'm 99% sure all of my permissions are set correctly. Is there some config option for svn that switches off command-line passwords?<br>
Or is it something else entirely?</p>
<p>I'm running svn 1.3.2 (r19776) on Fedora Core 5 (Bordeaux).</p>
<hr>
<p>Here's a list of my environment variables (with sensitive information X'ed out). None of them seem to apply to SVN:</p>
<pre><code># HOSTNAME=XXXXXX
# TERM=xterm
# SHELL=/bin/sh
# HISTSIZE=1000
# KDE_NO_IPV6=1
# SSH_CLIENT=XXX.XXX.XXX.XXX XXXXX XX
# QTDIR=/usr/lib/qt-3.3
# QTINC=/usr/lib/qt-3.3/include
# SSH_TTY=/dev/pts/2
# USER=XXXXXX
# LS_COLORS=no=00:fi=00:di=00;34:ln=00;36:pi=40;33:so=00;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=00;32:*.cmd=00;32:*.exe=00;32:*.com=00;32:*.btm=00;32:*.bat=00;32:*.sh=00;32:*.csh=00;32:*.tar=00;31:*.tgz=00;31:*.arj=00;31:*.taz=00;31:*.lzh=00;31:*.zip=00;31:*.z=00;31:*.Z=00;31:*.gz=00;31:*.bz2=00;31:*.bz=00;31:*.tz=00;31:*.rpm=00;31:*.cpio=00;31:*.jpg=00;35:*.gif=00;35:*.bmp=00;35:*.xbm=00;35:*.xpm=00;35:*.png=00;35:*.tif=00;35:
# KDEDIR=/usr
# MAIL=/var/spool/mail/XXXXXX
# PATH=/usr/lib/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin
# INPUTRC=/etc/inputrc
# PWD=/home/users/XXXXXX/my_repository
# KDE_IS_PRELINKED=1
# LANG=en_US.UTF-8
# SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
# SHLVL=1
# HOME=/home/users/XXXXXX
# LOGNAME=XXXXXX
# QTLIB=/usr/lib/qt-3.3/lib
# CVS_RSH=ssh
# SSH_CONNECTION=69.202.73.122 60998 216.7.19.47 22
# LESSOPEN=|/usr/bin/lesspipe.sh %s
# G_BROKEN_FILENAMES=1
# _=/bin/env
# OLDPWD=/home/users/XXXXXX
</code></pre>
|
[
{
"answer_id": 34755,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 0,
"selected": false,
"text": "--no-auth-cache svn update"
},
{
"answer_id": 34911,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 6,
"selected": false,
"text": "--no-auth-cache --non-interactive"
},
{
"answer_id": 36519216,
"author": "Andre Holzner",
"author_id": 288875,
"author_profile": "https://Stackoverflow.com/users/288875",
"pm_score": 0,
"selected": false,
"text": "svn relocate svn switch --relocate \\\n svn+ssh://olduser@svnserver/path/to/repo \\\n svn+ssh://newuser@svnserver/path/to/repo\n svn+ssh://olduser@svnserver/path/to/repo URL: svn info newuser svn update"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3625/"
] |
34,705 |
<p>We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question.</p>
<ol>
<li><p>What is the reccomended approach for dealing with a large number of forms that all have different data. Right now were are trying to take a structured approach in setting up a js "class" for each page, with an init, wireClickEvents etc.. to try to have everything conformed.</p></li>
<li><p>Is there any "best practices" with creating repetitive jQuery code or any type of reccomended structure other than just throwing a bunch of functions in a js file?</p></li>
</ol>
|
[
{
"answer_id": 4629484,
"author": "ordnungswidrig",
"author_id": 9069,
"author_profile": "https://Stackoverflow.com/users/9069",
"pm_score": 0,
"selected": false,
"text": "form1validate\nform1aftersubmit\nform2validate\nform2aftersubmit\n (function() {\n var foo = 1;\n})();\n\n(function() {\n if(foo == 1) alert(\"namespace separation failed!\")\n})();\n // this is a validator for one form\n var form1validator = function() {\n if($(\"input[name=name]\",this).attr(\"value\").length < 1 &&\n $(\"input[name=organisation]\",this).attr(\"value\").length < 1)\n return \"Either name or organisation required\" \n }\n\n // and this for a second form\n var form2validator = function() {\n if($(\"input[name=age]\",this).attr(\"value\").length < 21\n return \"Age of 21 required\"\n }\n\n // and a function to display a validation result\n var displayResult = function(r) {\n $(this).prepend(\"<span></span>\").text(r);\n }\n\n // we use them as higher order functions like that\n\n $(\"#form1\").onSubmit(validator(form1validator, displayResult, function() {\n //on submit\n ...send some xhr request or like that\n });\n\n $(\"#form2\").onSubmit(validator(form2validator, displayResult, function() {\n this.submit() // simply submit form\n });\n\n $(\"#form1b\").onSubmit(validator(form1validator, function(r) {\n alert(\"There was an validation error \" + r);\n }, function() {\n //on submit\n ...send some xhr request or like that\n });\n\n\n // the validator function itself would be defined as\n\n function validator(formValidator, displayResult, onSubmit) {\n var r = formValidator.apply(this)\n if(typeof(r) === 'undefined')\n onSubmit(this)\n else\n displayResult(r)\n }\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2993/"
] |
34,708 |
<p>A few months back I was tasked with implementing a unique and random code for our web application. The code would have to be user friendly and as small as possible, but still be essentially random (so users couldn't easily predict the next code in the sequence).</p>
<p>It ended up generating values that looked something like this:</p>
<pre><code>Af3nT5Xf2
</code></pre>
<p>Unfortunately, I was never satisfied with the implementation. Guid's were out of the question, they were simply too big and difficult for users to type in. I was hoping for something more along the lines of 4 or 5 characters/digits, but our particular implementation would generate noticeably patterned sequences if we encoded to less than 9 characters.</p>
<p>Here's what we ended up doing:</p>
<p>We pulled a unique sequential 32bit id from the database. We then inserted it into the center bits of a 64bit RANDOM integer. We created a lookup table of easily typed and recognized characters (A-Z, a-z, 2-9 skipping easily confused characters such as L,l,1,O,0, etc.). Finally, we used that lookup table to base-54 encode the 64-bit integer. The high bits were random, the low bits were random, but the center bits were sequential.</p>
<p>The final result was a code that was much smaller than a guid and looked random, even though it absolutely wasn't.</p>
<p>I was never satisfied with this particular implementation. What would you guys have done?</p>
|
[
{
"answer_id": 34727,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 3,
"selected": false,
"text": "byte[] randomBytes = new byte[4];\nRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\nrng.GetBytes(randomBytes);\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
34,712 |
<p>I have some UI in VB 2005 that looks great in XP Style, but goes hideous in Classic Style.</p>
<p>Any ideas about how to detect which mode the user is in and re-format the forms on the fly?</p>
<hr>
<p>Post Answer Edit:</p>
<p>Thanks Daniel, looks like this will work. I'm using the first solution you posted with the GetCurrentThemeName() function.</p>
<p>I'm doing the following:</p>
<p><strong>Function Declaration:</strong>
<pre><code> Private Declare Unicode Function GetCurrentThemeName Lib "uxtheme" (ByVal stringThemeName As System.Text.StringBuilder, ByVal lengthThemeName As Integer, ByVal stringColorName As System.Text.StringBuilder, ByVal lengthColorName As Integer, ByVal stringSizeName As System.Text.StringBuilder, ByVal lengthSizeName As Integer) As Int32
</pre></code></p>
<p><strong><em>Code Body:</em></strong>
<pre><code>
Dim stringThemeName As New System.Text.StringBuilder(260)
Dim stringColorName As New System.Text.StringBuilder(260)
Dim stringSizeName As New System.Text.StringBuilder(260)</p>
<p>GetCurrentThemeName(stringThemeName, 260, stringColorName, 260, stringSizeName, 260)
MsgBox(stringThemeName.ToString)
</pre></code></p>
<p>The MessageBox comes up Empty when i'm in Windows Classic Style/theme, and Comes up with "C:\WINDOWS\resources\Themes\luna\luna.msstyles" if it's in Windows XP style/theme. I'll have to do a little more checking to see what happens if the user sets another theme than these two, but shouldn't be a big issue.</p>
|
[
{
"answer_id": 34729,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": true,
"text": "[DllImport(\"dwmapi.dll\", PreserveSig = false)]\npublic static extern bool DwmIsCompositionEnabled();\n"
},
{
"answer_id": 104081,
"author": "Richard Morgan",
"author_id": 2258,
"author_profile": "https://Stackoverflow.com/users/2258",
"pm_score": 1,
"selected": false,
"text": "if (Application.RenderWithVisualStyles)\n{\n // you're themed\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3648/"
] |
34,717 |
<p>Is it possible to embed an audio object (mp3, wma, whatever) in a web-enabled InfoPath form ? </p>
<p>If it is, how do you do it ?</p>
|
[
{
"answer_id": 34891,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 1,
"selected": false,
"text": "public void FormEvents_Loading(object sender, LoadingEventArgs e)\n{\n string imgPath = \"http://yoursite/yourimage.jpeg\";\n\n XPathNodeIterator xpni = MainDataSource.CreateNavigator().SelectSingleNode(\"/my:FormName/my:RichTextControlName\", NamespaceManager).SelectChildren(XPathNodeType.All);\n xpni.Current.InnerXml = \"<img xmlns=\\\"http://www.w3.org/1999/xhtml\\\" src=\\\"\" + filePath + \"\\\" width=\\\"200px\\\" height=\\\"55px\\\" />\"; \n}\n"
},
{
"answer_id": 35143,
"author": "Nathan DeWitt",
"author_id": 1753,
"author_profile": "https://Stackoverflow.com/users/1753",
"pm_score": 2,
"selected": true,
"text": "<object>"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753/"
] |
34,732 |
<p>How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library).</p>
<p>I'm using gcc 4.0.2, if that makes a difference.</p>
|
[
{
"answer_id": 34758,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "nm -g objcopy nm -g"
},
{
"answer_id": 34796,
"author": "Steve Gury",
"author_id": 1578,
"author_profile": "https://Stackoverflow.com/users/1578",
"pm_score": 10,
"selected": true,
"text": "nm nm -gD yourLib.so\n nm -gDC yourLib.so\n objdump -C $ objdump -TC libz.so\n\nlibz.so: file format elf64-x86-64\n\nDYNAMIC SYMBOL TABLE:\n0000000000002010 l d .init 0000000000000000 .init\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 free\n0000000000000000 DF *UND* 0000000000000000 GLIBC_2.2.5 __errno_location\n0000000000000000 w D *UND* 0000000000000000 _ITM_deregisterTMCloneTable\n readelf $ readelf -Ws libz.so\nSymbol table '.dynsym' contains 112 entries:\n Num: Value Size Type Bind Vis Ndx Name\n 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND\n 1: 0000000000002010 0 SECTION LOCAL DEFAULT 10\n 2: 0000000000000000 0 FUNC GLOBAL DEFAULT UND free@GLIBC_2.2.5 (14)\n 3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND __errno_location@GLIBC_2.2.5 (14)\n 4: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterTMCloneTable\n"
},
{
"answer_id": 1620583,
"author": "P Shved",
"author_id": 158676,
"author_profile": "https://Stackoverflow.com/users/158676",
"pm_score": 7,
"selected": false,
"text": ".so readelf -Ws /usr/lib/libexample.so\n .so readelf -Ws /usr/lib/libstdc++.so.6 | grep '^\\([[:space:]]\\+[^[:space:]]\\+\\)\\{6\\}[[:space:]]\\+[[:digit:]]\\+'\n readelf -Ws /usr/lib/libstdc++.so.6 | awk '{print $8}';\n"
},
{
"answer_id": 2073825,
"author": "Pavel Lapin",
"author_id": 212229,
"author_profile": "https://Stackoverflow.com/users/212229",
"pm_score": 6,
"selected": false,
"text": "objdump -TC /usr/lib/libexample.so\n"
},
{
"answer_id": 14737593,
"author": "cavila",
"author_id": 936787,
"author_profile": "https://Stackoverflow.com/users/936787",
"pm_score": 5,
"selected": false,
"text": "nm -D libNAME.so\n nm -g libNAME.a\n"
},
{
"answer_id": 26739013,
"author": "Adi Shavit",
"author_id": 135862,
"author_profile": "https://Stackoverflow.com/users/135862",
"pm_score": 4,
"selected": false,
"text": ".so readelf objdump nm"
},
{
"answer_id": 48122967,
"author": "user7610",
"author_id": 1047788,
"author_profile": "https://Stackoverflow.com/users/1047788",
"pm_score": 5,
"selected": false,
"text": ".so nm nm --demangle --dynamic --defined-only --extern-only <my.so> # nm --demangle --dynamic --defined-only --extern-only /usr/lib64/libqpid-proton-cpp.so | grep work | grep add\n0000000000049500 T proton::work_queue::add(proton::internal::v03::work)\n0000000000049580 T proton::work_queue::add(proton::void_function0&)\n000000000002e7b0 W proton::work_queue::impl::add_void(proton::internal::v03::work)\n000000000002b1f0 T proton::container::impl::add_work_queue()\n000000000002dc50 T proton::container::impl::container_work_queue::add(proton::internal::v03::work)\n000000000002db60 T proton::container::impl::connection_work_queue::add(proton::internal::v03::work)\n"
},
{
"answer_id": 54591492,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 2,
"selected": false,
"text": "objdump -h /path/to/object\n objdump -g /path/to/object\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3051/"
] |
34,734 |
<p>I've tried two different methods of reusing code. I have a solution full of just class library projects with generic code that I reuse in almost every project I work on. When I get to work on a new project, I will reuse code from this code library in one of two ways:</p>
<ol>
<li>I have tried bringing the projects I need from this code library into my project.</li>
<li>I have also tried compiling down to a .dll and referencing the .dll from a folder in the root of my current solution.</li>
</ol>
<p>While the second method seems easier and lighter to implement, I always find myself making small tweaks to the original code to fit it into the context of my current project.</p>
<p>I know this is a bit of a vague question, but has anyone had success with other methods of reusing class libraries on new solutions?</p>
|
[
{
"answer_id": 34764,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 1,
"selected": false,
"text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\.NETFramework\\AssemblyFolders\\ComapnyName]\n@=\"C:\\\\CentralLocation\"\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
34,735 |
<p>I'm having trouble getting a rotary encoder to work properly with AVR micro controllers. The encoder is a mechanical <a href="http://no.farnell.com/1520815/passives/product.us0?sku=alps-ec12d1524401" rel="noreferrer">ALPS encoder</a>, and I'm using <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf" rel="noreferrer">Atmega168</a>.</p>
<p><strong>Clarification</strong></p>
<p>I have tried using an External Interrupt to listen to the pins, but it seems like it is too slow. When Pin A goes high, the interrupt procedure starts and then checks if Pin B is high. The idea is that if Pin B is high the moment Pin A went high, then it is rotating counter clock-wise. If Pin B is low, then it is rotating clock-wise. But it seems like the AVR takes too long to check Pin B, so it is always read as high. </p>
<p>I've also tried to create a program that simply blocks until Pin B or Pin A changes. But it might be that there is too much noise when the encoder is rotated, because this does not work either. My last attempt was to have a timer which stores the last 8 values in a buffer and checks if it is going from low to high. This did not work either.</p>
<p>I have tried scoping the encoder, and it seems to use between 2 and 4ms from the first Pin changes till the other Pin changes.</p>
|
[
{
"answer_id": 257613,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "/* into 0 service rutine */\nif(CHB)\n{\n if(flagB)\n Count++;\n FlagB=0;\n}\nelse\n{\n if(FlagB)\n count--:\n FlagB=0:\n}\n\n/* into 1 service rutine */\nFlagB=1;\n\n/* make this give to you a windows time of 1/4 of T of the encoder resolution\n that is in angle term: 360/ (4*resolution)\n */\n"
},
{
"answer_id": 312420,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": " _________\n | |\n | Encoder |\n |_________|\n | | |\n | | |\n 100n | O | 100n \n GND O-||-+ GND +-||-O GND\n | | \n \\ /\n 3K3 / \\ 3K3\n \\ /\n | | \nVCC O-/\\/-+ +-\\/\\-O VCC\n 15K | | 15K\n | |\n O O\n A B\n #include <avr/io.h>\n\n#define PIN_A (PINB&1)\n#define PIN_B ((PINB>>1)&1)\n\nint main(void){\n uint8_t st0 = 0;\n uint8_t st1 = 0;\n uint8_t dir = 0;\n uint8_t temp = 0;\n uint8_t counter = 0;\n DDRD = 0xFF;\n DDRB = 0;\n while(1){ \n if(dir == 0){\n if(PIN_A & (!PIN_B)){\n dir = 2;\n }else if(PIN_B & (!PIN_A)){\n dir = 4;\n }else{\n dir = 0;\n }\n }else if(dir == 2){\n if(PIN_A & (!PIN_B)){\n dir = 2;\n }else if((!PIN_A) & (!PIN_B)){\n counter--;\n dir = 0;\n }else{\n dir = 0;\n }\n }else if(dir == 4){\n if(PIN_B & (!PIN_A)){\n dir = 4;\n }else if((!PIN_A) & (!PIN_B)){\n counter++;\n dir = 0;\n }else{\n dir = 0;\n }\n }else if(PIN_B & PIN_A){\n dir = 0;\n }\n PORTD = ~counter;\n }\n return 0;\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1585/"
] |
34,768 |
<p>I have recently installed .net 3.5 SP1. When I deployed a compiled web site that contained a form with its action set:</p>
<pre><code><form id="theForm" runat="server" action="post.aspx">
</code></pre>
<p>I received this error.<br>
Method not found: 'Void System.Web.UI.HtmlControls.HtmlForm.set_Action(System.String)'.<br>
If a fellow developer who has not installed SP1 deploys the compiled site it works fine. Does anyone know of any solutions for this?</p>
|
[
{
"answer_id": 34776,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 1,
"selected": false,
"text": "public String Action { set { DoStuff(); } }\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2903/"
] |
34,784 |
<p>What is a good setup for .hgignore file when working with Visual Studio 2008?</p>
<p>I mostly develop on my own, only occasionly I clone the repository for somebody else to work on it.</p>
<p>I'm thinking about obj folders, .suo, .sln, .user files etc.. Can they just be included or are there file I shouldn't include?</p>
<p>Thanks!</p>
<p>p.s.: at the moment I do the following : ignore all .pdb files and all obj folders.</p>
<pre><code># regexp syntax.
syntax: glob
*.pdb
syntax: regexp
/obj/
</code></pre>
|
[
{
"answer_id": 34805,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": "*.csproj.user /obj/* /bin/* *.ncb *.suo"
},
{
"answer_id": 226447,
"author": "jm.",
"author_id": 814,
"author_profile": "https://Stackoverflow.com/users/814",
"pm_score": 4,
"selected": false,
"text": "syntax: glob\n*.user\n*.ncb\n*.nlb\n*.suo\n*.aps\n*.clw\n*.pdb\n*\\Debug\\*\n*\\Release\\*\n"
},
{
"answer_id": 744333,
"author": "Even Mien",
"author_id": 73794,
"author_profile": "https://Stackoverflow.com/users/73794",
"pm_score": 9,
"selected": true,
"text": "# Ignore file for Visual Studio 2008\n\n# use glob syntax\nsyntax: glob\n\n# Ignore Visual Studio 2008 files\n*.obj\n*.exe\n*.pdb\n*.user\n*.aps\n*.pch\n*.vspscc\n*_i.c\n*_p.c\n*.ncb\n*.suo\n*.tlb\n*.tlh\n*.bak\n*.cache\n*.ilk\n*.log\n*.lib\n*.sbr\n*.scc\n[Bb]in\n[Dd]ebug*/\nobj/\n[Rr]elease*/\n_ReSharper*/\n[Tt]est[Rr]esult*\n[Bb]uild[Ll]og.*\n*.[Pp]ublish.xml\n"
},
{
"answer_id": 2294025,
"author": "AlGonzalez",
"author_id": 276368,
"author_profile": "https://Stackoverflow.com/users/276368",
"pm_score": 3,
"selected": false,
"text": "syntax: glob\n#-- Files\n*.bak.*\n*.bak\nthumbs.db\n\n#-- Directories\nApp_Data/*\nbin/\nobj/\n_ReSharper.*/\ntmp/\n\n#-- Microsoft Visual Studio specific\n*.user\n*.suo\n\n#-- MonoDevelop specific\n*.pidb\n*.userprefs\n*.usertasks\n"
},
{
"answer_id": 2555413,
"author": "Damian Powell",
"author_id": 30321,
"author_profile": "https://Stackoverflow.com/users/30321",
"pm_score": 5,
"selected": false,
"text": "syntax: glob\n\n* - [Cc]opy\n* - [Cc]opy/\n* - [Cc]opy (?)/\n* - [Cc]opy.*\n* - [Cc]opy (?).*\n**/.*\n**/scss/*.css\n*.*scc\n*.FileListAbsolute.txt\n*.aps\n*.bak\n*.bin\n*.[Cc]ache\n*.clw\n*.css.map\n*.eto\n*.exe\n*.fb6lck\n*.fbl6\n*.fbpInf\n*.ilk\n*.lib\n*.log\n*.ncb\n*.nlb\n*.nupkg\n*.obj\n*.old\n*.orig\n*.patch\n*.pch\n*.pdb\n*.plg\n*.[Pp]ublish.xml\n*.rdl.data\n*.sbr\n*.scc\n*.sig\n*.sqlsuo\n*.suo\n*.svclog\n*.tlb\n*.tlh\n*.tli\n*.tmp\n*.user\n*.vshost.*\n*.docstates\n*DXCore.Solution\n*_i.c\n*_p.c\n__MVC_BACKUP/\n_[Rr]e[Ss]harper.*/\n_UpgradeReport_Files/\nAnkh.Load\nBackup*\n[Bb]in/\nbower_components/\n[Bb]uild/\nCVS/\n[Dd]ebug/\n[Ee]xternal/\nhgignore[.-]*\nignore[.-]*\nlint.db\nnode_modules/\n[Oo]bj/\n[Pp]ackages/\nPrecompiledWeb/\n[Pp]ublished/\n[Rr]elease/\nsvnignore[.-]*\n[Tt]humbs.db\nUpgradeLog*.*\n"
},
{
"answer_id": 2578567,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 2,
"selected": false,
"text": "output\nPrecompiledWeb\n_UpgradeReport_Files\n\n#Guidance Automation Toolkit\n*.gpState\n#patches\n*.patch\n"
},
{
"answer_id": 7798061,
"author": "Nathan Donnellan",
"author_id": 997216,
"author_profile": "https://Stackoverflow.com/users/997216",
"pm_score": 2,
"selected": false,
"text": "# use glob syntax\nsyntax: glob\n\n# Matlab ignore files\n*.asv\n\n# Microsoft Office\n~$*\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34784",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
] |
34,790 |
<p>The <code>datepicker</code> function only works on the first input box that is created.</p>
<p>I'm trying to duplicate a datepicker by cloning the <code>div</code> that is containing it.</p>
<pre><code><a href="#" id="dupMe">click</a>
<div id="template">
input-text <input type="text" value="text1" id="txt" />
date time picker <input type="text" id="example" value="(add date)" />
</div>
</code></pre>
<p>To initialize the datepicker, according to the <a href="http://docs.jquery.com/UI/Datepicker" rel="nofollow noreferrer">jQuery UI documentation</a> I only have to do <code>$('#example').datepicker();</code> and it does work, but only on the first datepicker that is created.</p>
<p>The code to duplicate the <code>div</code> is the following:</p>
<pre><code>$("a#dupMe").click(function(event){
event.preventDefault();
i++;
var a = $("#template")
.clone(true)
.insertBefore("#template")
.hide()
.fadeIn(1000);
a.find("input#txt").attr('value', i);
a.find("input#example").datepicker();
});
</code></pre>
<p>The strangest thing is that on the <code>document.ready</code> I have:</p>
<pre><code>$('#template #example').datepicker();
$("#template #txt").click(function() { alert($(this).val()); });
</code></pre>
<p>and if I click on the <code>#txt</code> it always works.</p>
|
[
{
"answer_id": 34807,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 4,
"selected": false,
"text": "<input type=\"text\" id=\"BeginDate\" class=\"calendar\" />\n<input type=\"text\" id=\"EndDate\" class=\"calendar\" />\n document.ready $('.calendar').datepicker();\n"
},
{
"answer_id": 34855,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 4,
"selected": true,
"text": "div function makeDatePickers() {\n $(\"#template input[type=text]\").datepicker();\n}\n"
},
{
"answer_id": 1423156,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": ".datepicker() .datepicker('destroy') $('#addaddress').click(function() {\n var count = $('.address_template').size();\n var html = $('.address_template').eq(0).html();\n $('#addaddress').before('<div class=\"address_template\">' + html + '</div>');\n $('.address_template H1').eq(count).html(\"Previous Address \" + count);\n $('.address_date').eq(count).attr(\"class\",\"address_date\");\n $('.address_date').eq(count).attr(\"id\",\"movein\" + count);\n $(\"#movein\" + count).datepicker();\n});\n"
},
{
"answer_id": 9199379,
"author": "philip_kobernik",
"author_id": 1128839,
"author_profile": "https://Stackoverflow.com/users/1128839",
"pm_score": 0,
"selected": false,
"text": "var clonedObject = this.el.find('.jLo:last-child')\nclonedObject.find('input.ui-datepicker').each(function(index, element) {\n $(element).removeClass('hasDatepicker');\n $(element).datepicker();\n});\nclonedObject.appendTo('.jLo');\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
] |
34,798 |
<p>I have a gridview that is within an updatepanel for a modal popup I have on a page.<br>
The issue is that the entire page refreshes every time I click an imagebutton that is within my gridview. This causes my entire page to load and since I have grayed out the rest of the page so that the user cannot click on it this is very annoying.</p>
<p>Does any one know what I am missing. </p>
<p><strong>Edit:</strong> I entered a better solution at the bottom</p>
|
[
{
"answer_id": 35082,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 0,
"selected": false,
"text": " <base target=\"_self\" /> \n"
},
{
"answer_id": 35189,
"author": "Steven Williams",
"author_id": 3294,
"author_profile": "https://Stackoverflow.com/users/3294",
"pm_score": 1,
"selected": false,
"text": "<asp:Button ID=\"btnRefresh\" runat=\"server\" OnClick=\"btnRefresh_Click\" Style=\"display: none\" UseSubmitBehavior=\"false\" />\n"
},
{
"answer_id": 403473,
"author": "Josh Mein",
"author_id": 2486,
"author_profile": "https://Stackoverflow.com/users/2486",
"pm_score": 2,
"selected": true,
"text": "<xhtmlConformance mode=\"Legacy\"/>\n"
},
{
"answer_id": 13273075,
"author": "Scotty.NET",
"author_id": 1123275,
"author_profile": "https://Stackoverflow.com/users/1123275",
"pm_score": 0,
"selected": false,
"text": "<asp:UpdatePanel ... /> <asp:LinkButton ... /> UpdateMode=\"Conditional\" UpdatePanel ViewStateMode=\"Enabled\" <asp:Content ... /> Disabled MasterPage ClientIDMode=\"Static\" <%@ Page ... />"
},
{
"answer_id": 33972528,
"author": "Bortus",
"author_id": 3968481,
"author_profile": "https://Stackoverflow.com/users/3968481",
"pm_score": 0,
"selected": false,
"text": "string PopupURL = Common.GetAppPopupPath() + \"Popups/StockChart.aspx?s=\" + symbol;\nhlLargeChart.Attributes.Add(\"onclick\", String.Format(\"ShowPopupStdControls(PCStockChartWindow,'{0}');return false;\", PopupURL));\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
34,802 |
<p>I'm trying to write a custom WPF ValidationRule to enforce that a certain property is unique within the context of a given collection. For example: I am editing a collection of custom objects bound to a ListView and I need to ensure that the Name property of each object in the collection is unique. Does anyone know how to do this?</p>
|
[
{
"answer_id": 34885,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": true,
"text": "class YourCollectionType : DependencyObject {\n\n [PROPERTY DEPENDENCY OF ObservableCollection<YourType> NAMED: BoundList]\n\n}\n YourCollectionType ListToCheck { get; set; }\n <Binding.ValidationRules>\n <YourValidationRule>\n <YourValidationRule.ListToCheck> \n <YourCollectionType BoundList=\"{Binding Path=TheCollectionYouWantToCheck}\" />\n </YourValidationRule.ListToCheck>\n </YourValidationRule>\n</Binding.ValidationRules>\n"
},
{
"answer_id": 46980091,
"author": "Patrick",
"author_id": 278889,
"author_profile": "https://Stackoverflow.com/users/278889",
"pm_score": 1,
"selected": false,
"text": "<UniqueValueValidationRule.OtherValues> <CollectionContainer> DataContext <TextBox.Resources> <CollectionViewSource> {StaticResource} OtherValues OtherValues.Collection <TextBox>\n <TextBox.Resources>\n <CollectionViewSource x:Key=\"otherNames\" Source=\"{Binding OtherNames}\"/>\n </TextBox.Resources>\n <TextBox.Text>\n <Binding Path=\"Name\">\n <Binding.ValidationRules>\n <t:UniqueValueValidationRule>\n <t:UniqueValueValidationRule.OtherValues>\n <CollectionContainer Collection=\"{Binding Source={StaticResource otherNames}}\"/>\n </t:UniqueValueValidationRule.OtherValues>\n </t:UniqueValueValidationRule>\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n </TextBox>\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] |
34,806 |
<p>I have a little dilemma that maybe you can help me sort out. </p>
<p>I've been working today in modifying ASP.NET's Membership to add a level of indirection. Basically, ASP.NET's Membership supports Users and Roles, leaving all authorization rules to be based on whether a user belongs to a Role or not. </p>
<p>What I need to do is add the concept of Function, where a user will belong to a role (or roles) and the role will have one or more functions associated with them, allowing us to authorize a specific action based on if the user belongs to a role which has a function assigned. </p>
<p>Having said that, my problem has nothing to do with it, it's a generic class design issue. </p>
<p>I want to provide an abstract method in my base RoleProvider class to create the function (and persist it), but I want to make it optional to save a description for that function, so I need to create my CreateFunction method with an overload, one signature accepting the name, and the other accepting the name and the description. </p>
<p>I can think of the following scenarios: </p>
<ol>
<li><p>Create both signatures with the abstract modifier. This has the problem that the implementer may not respect the best practice that says that one overload should call the other one with the parameters normalized, and the logic should only be in the final one (the one with all the parameters). Besides, it's not nice to require both methods to be implemented by the developer. </p></li>
<li><p>Create the first like virtual, and the second like abstract. Call the second from the first, allow the implementer to override the behavior. It has the same problem, the implementer could make "bad decisions" when overriding it. </p></li>
<li><p>Same as before, but do not allow the first to be overriden (remove the virtual modifier). The problem here is that the implementer has to be aware that the method could be called with a null description and has to handle that situation. </p></li>
</ol>
<p>I think the best option is the third one... </p>
<p>How is this scenario handled in general? When you design an abstract class and it contains overloaded methods. It isn't that uncommon I think... </p>
|
[
{
"answer_id": 34832,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": true,
"text": "class Base {\n public final constructor(name) {\n constructor(name, null)\n end\n\n public abstract constructor(name, description);\n}\n class Base {\n public abstract constructor(name);\n\n public final constructor(name, description) {\n constructor(name)\n this.set_description(description)\n }\n\n private final set_description(description) {\n ...\n }\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
34,818 |
<p>In terms of performance and optimizations:</p>
<ul>
<li>When constructing a table in SQL Server, does it matter what order I put the columns in?</li>
<li>Does it matter if my primary key is the first column?</li>
<li>When constructing a multi-field index, does it matter if the columns are adjacent?</li>
<li>Using ALTER TABLE syntax, is it possible to specify in what position I want to add a column?
<ul>
<li>If not, how can I move a column to a difference position?</li>
</ul></li>
</ul>
|
[
{
"answer_id": 2732820,
"author": "egrunin",
"author_id": 147463,
"author_profile": "https://Stackoverflow.com/users/147463",
"pm_score": -1,
"selected": false,
"text": "image text ntext"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
34,848 |
<p>When using a <code>Zend_Form</code>, the only way to validate that an input is not left blank is to do</p>
<pre><code>$element->setRequired(true);
</code></pre>
<p>If this is not set and the element is blank, it appears to me that validation is not run on the element.</p>
<p>If I do use <code>setRequired()</code>, the element is automatically given the standard NotEmpty validator. The thing is that the error message with this validator sucks, "Value is empty, but a non-empty value is required". I want to change this message. At the moment I have done this by changing the <code>Zend_Validate_NotEmpty</code> class, but this is a bit hacky.</p>
<p>I would ideally like to be able to use my own class (derived from <code>Zend_Validate_NotEmpty</code>) to perform the not empty check.</p>
|
[
{
"answer_id": 35894,
"author": "crono",
"author_id": 1462,
"author_profile": "https://Stackoverflow.com/users/1462",
"pm_score": 3,
"selected": true,
"text": "$name = new Zend_Form_Element_Text('name');\n$name->setLabel('Full Name: ')\n ->setRequired(true)\n ->addFilter('StripTags')\n ->addFilter('StringTrim')\n ->addValidator($MyNotEmpty);\n $MyNotEmpty = new Zend_Validate_NotEmpty();\n$MyNotEmpty->setMessage($trans->translate('err.IS_EMPTY'),Zend_Validate_NotEmpty::IS_EMPTY);\n"
},
{
"answer_id": 191889,
"author": "Toxygene",
"author_id": 8428,
"author_profile": "https://Stackoverflow.com/users/8428",
"pm_score": 2,
"selected": false,
"text": "$username = new Zend_Form_Element_Text('username');\n$username->setRequired(true)\n ->addValidator('NotEmpty', true, array('messages' => array('isEmpty' => 'Empty!')));\n"
},
{
"answer_id": 318213,
"author": "duma",
"author_id": 245644,
"author_profile": "https://Stackoverflow.com/users/245644",
"pm_score": 2,
"selected": false,
"text": "// In the form class:\n$username = $this->createElement('text', 'username');\n$username->setRequired(); // Note that this seems to be required!\n$username->addValidator('NotEmpty', true, array(\n 'messages' => array(\n 'isEmpty' => 'my localized err msg')));\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1349865/"
] |
34,868 |
<p>In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the <a href="http://php.net/date" rel="noreferrer"><code>date()</code></a> function, the manual reads:</p>
<pre><code>string date ( string $format [, int $timestamp = time() ] )
</code></pre>
<p>Where <code>$timestamp</code> is an optional parameter, and when left blank it defaults to the <a href="http://php.net/time" rel="noreferrer"><code>time()</code></a> function's return value.</p>
<p>How do you go about creating optional parameters like this when defining a custom function in PHP?</p>
|
[
{
"answer_id": 34869,
"author": "Jeff Winkworth",
"author_id": 1306,
"author_profile": "https://Stackoverflow.com/users/1306",
"pm_score": 9,
"selected": true,
"text": "= function dosomething($var1, $var2, $var3 = 'somevalue'){\n // Rest of function here...\n}\n"
},
{
"answer_id": 34877,
"author": "mk.",
"author_id": 1797,
"author_profile": "https://Stackoverflow.com/users/1797",
"pm_score": 4,
"selected": false,
"text": "function date ($format, $timestamp='') {\n}\n"
},
{
"answer_id": 34999,
"author": "gregh",
"author_id": 2687,
"author_profile": "https://Stackoverflow.com/users/2687",
"pm_score": 5,
"selected": false,
"text": "function whatever($var1, $var2, $var3=\"constant\", $var4=\"another\")\n"
},
{
"answer_id": 35034,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 6,
"selected": false,
"text": "function foo($foo, $bar = false)\n{\n if(!$bar)\n {\n $bar = $foo;\n }\n}\n $bar"
},
{
"answer_id": 16881443,
"author": "Lars Gyrup Brink Nielsen",
"author_id": 1071200,
"author_profile": "https://Stackoverflow.com/users/1071200",
"pm_score": 4,
"selected": false,
"text": "function date($format, $timestamp = null)\n{\n if ($timestamp === null) {\n $timestamp = time();\n }\n\n // Format the timestamp according to $format\n}\n function foo($required, $optional = 42)\n{\n // This function can be passed one or more arguments\n}\n null $timestamp = time() array() [] null"
},
{
"answer_id": 35749448,
"author": "Gergely Lukacsy",
"author_id": 1957951,
"author_profile": "https://Stackoverflow.com/users/1957951",
"pm_score": 4,
"selected": false,
"text": "... function <functionName> ([<type> ]...<$paramName>) {}\n function someVariadricFunc(...$arguments) {\n foreach ($arguments as $arg) {\n // do some stuff with $arg...\n }\n}\n\nsomeVariadricFunc(); // an empty array going to be passed\nsomeVariadricFunc('apple'); // provides a one-element array\nsomeVariadricFunc('apple', 'pear', 'orange', 'banana');\n"
},
{
"answer_id": 70110910,
"author": "Arkadii Chyzhov",
"author_id": 5554825,
"author_profile": "https://Stackoverflow.com/users/5554825",
"pm_score": 3,
"selected": false,
"text": "function func(?Object $object) {}\n func(null); //as nullable parameter\nfunc(new Object()); // as parameter of declared type\n function func(Object $object = null) {} // In case of objects\nfunction func(?Object $object = null) {} // or the same with nullable parameter\n\nfunction func(string $object = '') {} // In case of scalar type - string, with string value as default value\nfunction func(string $object = null) {} // In case of scalar type - string, with null as default value\nfunction func(?string $object = '') {} // or the same with nullable parameter\n\nfunction func(int $object = 0) {} // In case of scalar type - integer, with integer value as default value\nfunction func(int $object = null) {} // In case of scalar type - integer, with null as default value\nfunction func(?int $object = 0) {} // or the same with nullable parameter\n func(); // as optional parameter\nfunc(null); // as nullable parameter\nfunc(new Object()); // as parameter of declared type\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34868",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2687/"
] |
34,879 |
<p>I need debug some old code that uses a Hashtable to store response from various threads.</p>
<p>I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.</p>
<p>How can this be done?</p>
|
[
{
"answer_id": 34884,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "foreach(string key in hashTable.Keys)\n{\n Console.WriteLine(String.Format(\"{0}: {1}\", key, hashTable[key]));\n}\n"
},
{
"answer_id": 34887,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 2,
"selected": false,
"text": "\n public static void PrintKeysAndValues( Hashtable myList ) {\n IDictionaryEnumerator myEnumerator = myList.GetEnumerator();\n Console.WriteLine( \"\\t-KEY-\\t-VALUE-\" );\n while ( myEnumerator.MoveNext() )\n Console.WriteLine(\"\\t{0}:\\t{1}\", myEnumerator.Key, myEnumerator.Value);\n Console.WriteLine();\n }\n"
},
{
"answer_id": 34894,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 1,
"selected": false,
"text": "foreach (string HashKey in TargetHash.Keys)\n{\n Console.WriteLine(\"Key: \" + HashKey + \" Value: \" + TargetHash[HashKey]);\n}\n"
},
{
"answer_id": 34909,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "System.Collections.IDictionaryEnumerator enumerator = hashTable.GetEnumerator();\n\nwhile (enumerator.MoveNext())\n{\n string key = enumerator.Key.ToString();\n string value = enumerator.Value.ToString();\n\n Console.WriteLine((\"Key = '{0}'; Value = '{0}'\", key, value);\n}\n"
},
{
"answer_id": 35024,
"author": "Jake Pearson",
"author_id": 632,
"author_profile": "https://Stackoverflow.com/users/632",
"pm_score": 3,
"selected": false,
"text": "foreach(DictionaryEntry entry in hashtable)\n{\n Console.WriteLine(entry.Key + \":\" + entry.Value);\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
34,913 |
<p>I'm experimenting with Linq and am having trouble figuring out grouping. I've gone through several tutorials but for some reason can't figure this out.</p>
<p>As an example, say I have a table (SiteStats) with multiple website IDs that stores a count of how many visitors by type have accessed each site in total and for the past 30 days.</p>
<pre><code>╔════════╦═════════════╦════════╦══════╗
║ SiteId ║ VisitorType ║ Last30 ║ Total║
╠════════╬═════════════╬════════╬══════╣
║ 1 ║ 1 ║ 10 ║ 100 ║
║ 1 ║ 2 ║ 40 ║ 140 ║
║ 2 ║ 1 ║ 20 ║ 180 ║
╚════════╩═════════════╩════════╩══════╝
</code></pre>
<p>In SQL, I can easily get the counts for SiteID 1 with the following:</p>
<pre><code>SELECT SiteId,
SUM(Last30) AS Last30Sum
FROM Sites
WHERE SiteId = 1
GROUP BY SiteId
</code></pre>
<p>and should get a row like...</p>
<pre><code>╔════════╦════════════╗
║ SiteId ║ Last30Total║
╠════════╬════════════╣
║ 1 ║ 50 ║
╚════════╩════════════╝
</code></pre>
<p>However I'm not sure how to get this result using Linq. I've tried:</p>
<pre><code>var statsRecord = from ss in db.SiteStats
where ss.SiteId == siteId
group ss by ss.SiteId into ss
select ss;
</code></pre>
<p>but I'm not able to get back the total with something like <code>statsRecord.Last30</code></p>
<p>Can someone please let me know where I'm going wrong? Any help is appreciated.</p>
|
[
{
"answer_id": 34951,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 2,
"selected": false,
"text": "public class Site\n{\n static void Main()\n {\n List<Site> sites = new List<Site>()\n {\n new Site() { SiteID = 1, VisitorType = 1, Last30 = 10, Total = 100, },\n new Site() { SiteID = 1, VisitorType = 2, Last30 = 40, Total = 140, },\n new Site() { SiteID = 2, VisitorType = 1, Last30 = 20, Total = 180, },\n };\n\n var totals =\n from s in sites\n group s by s.SiteID into grouped\n select new\n {\n SiteID = grouped.Key,\n Last30Sum = \n (from value in grouped\n select value.Last30).Sum(),\n };\n\n foreach (var total in totals)\n {\n Console.WriteLine(\"Site: {0}, Last30Sum: {1}\", total.SiteID, total.Last30Sum);\n }\n }\n\n public int SiteID { get; set; }\n public int VisitorType { get; set; }\n public int Last30 { get; set; }\n public int Total { get; set; }\n}\n"
},
{
"answer_id": 36678,
"author": "Ben Laan",
"author_id": 2918,
"author_profile": "https://Stackoverflow.com/users/2918",
"pm_score": 6,
"selected": true,
"text": "var totals =\nfrom s in sites\ngroup s by s.SiteID into grouped\nselect new\n{\n SiteID = grouped.Key,\n Last30Sum = grouped.Sum( s => s.Last30 )\n};\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034/"
] |
34,914 |
<p>The manual page for <code>XML::Parser::Style::Objects</code> is horrible. A simple hello world style program would really be helpful.</p>
<p>I really wanted to do something like this: (not real code of course)</p>
<pre><code>use XML::Parser;
my $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');
my $tree = $p->parsefile('foo.xml');
$tree->doSomething();
MyNode::doSomething() {
my $self = shift;
print "This is a normal node";
for $kid ($self->Kids)
{
$kid->doSomething();
}
}
MyNode::special::doSomething() {
my $self = shift;
print "This is a special node";
}
</code></pre>
|
[
{
"answer_id": 35467,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": true,
"text": "use XML::Parser;\n\npackage MyNode::inner;\n sub doSomething {\n my $self = shift;\n print \"This is an inner node containing : \";\n print $self->{Kids}->[0]->{Text};\n print \"\\n\";\n }\npackage MyNode::Characters;\n sub doSomething {}\npackage MyNode::foo;\n sub doSomething {\n my $self = shift;\n print \"This is an external node\\n\";\n for $kid (@ { $self->{Kids} }) {\n $kid->doSomething();\n }\n }\n\npackage main;\n\nmy $p = XML::Parser->new(Style => 'Objects', Pkg => 'MyNode');\nmy $tree = $p->parsefile('foo.xml');\nfor (@$tree) {\n $_->doSomething();\n}\n <foo> <inner>some text</inner> <inner>something else</inner></foo>\n >perl -w \"tree.pl\" \nThis is an external node\nThis is an inner node containing : some text\nThis is an inner node containing : something else\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] |
34,920 |
<p>What is the best way to create a lock on a file in Perl?</p>
<p>Is it best to flock on the file or to create a lock file to place a lock on and check for a lock on the lock file?</p>
|
[
{
"answer_id": 34933,
"author": "Chris Bunch",
"author_id": 422,
"author_profile": "https://Stackoverflow.com/users/422",
"pm_score": 6,
"selected": true,
"text": "use Fcntl ':flock'; # Import LOCK_* constants\n\n# We will use this file path in error messages and function calls.\n# Don't type it out more than once in your code. Use a variable.\nmy $file = '/path/to/some/file';\n\n# Open the file for appending. Note the file path is quoted\n# in the error message. This helps debug situations where you\n# have a stray space at the start or end of the path.\nopen(my $fh, '>>', $file) or die \"Could not open '$file' - $!\";\n\n# Get exclusive lock (will block until it does)\nflock($fh, LOCK_EX) or die \"Could not lock '$file' - $!\";\n\n# Do something with the file here...\n\n# Do NOT use flock() to unlock the file if you wrote to the\n# file in the \"do something\" section above. This could create\n# a race condition. The close() call below will unlock the\n# file for you, but only after writing any buffered data.\n\n# In a world of buffered i/o, some or all of your data may not \n# be written until close() completes. Always, always, ALWAYS \n# check the return value of close() if you wrote to the file!\nclose($fh) or die \"Could not write '$file' - $!\";\n flock()"
},
{
"answer_id": 79295,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 1,
"selected": false,
"text": "open (FILE, '>>', test.dat') ; # open the file \nflock FILE, 2; # try to lock the file \n# do something with the file here \nclose(FILE); # close the file\n open (FILE, '<', test.dat');\n flock FILE, 2;\n open (FILE, '>', test.dat'); #single arrow truncates double appends\n flock FILE, 2;\n open (LOCK_FILE, '<', test.dat.lock') or die \"Could not obtain lock\";\nflock LOCK_FILE, 2;\nopen (FILE, '<', test.dat') or die \"Could not open file\";\n# read file\n# ...\nopen (FILE, '>', test.dat') or die \"Could not reopen file\";\n#write file\nclose (FILE);\nclose (LOCK_FILE);\n"
},
{
"answer_id": 81019,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "open open my $fh, '+<', 'test.dat'\n or die \"Couldn’t open test.dat: $!\\n\";\n seek truncate close truncate $fh, tell $fh open open open"
},
{
"answer_id": 182465,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 2,
"selected": false,
"text": "use strict;\n\nuse Fcntl ':flock'; # Import LOCK_* constants\n\n# We will use this file path in error messages and function calls.\n# Don't type it out more than once in your code. Use a variable.\nmy $file = '/path/to/some/file';\n\n# Open the file for appending. Note the file path is in quoted\n# in the error message. This helps debug situations where you\n# have a stray space at the start or end of the path.\nopen(my $fh, '>>', $file) or die \"Could not open '$file' - $!\";\n\n# Get exclusive lock (will block until it does)\nflock($fh, LOCK_EX);\n\n\n# Do something with the file here...\n\n\n# Do NOT use flock() to unlock the file if you wrote to the\n# file in the \"do something\" section above. This could create\n# a race condition. The close() call below will unlock it\n# for you, but only after writing any buffered data.\n\n# In a world of buffered i/o, some or all of your data will not \n# be written until close() completes. Always, always, ALWAYS \n# check the return value on close()!\nclose($fh) or die \"Could not write '$file' - $!\";\n"
},
{
"answer_id": 1427007,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "open (TST,\"+< readwrite_test.txt\") or die \"Cannot open file\\n$!\";\nflock(TST, LOCK_EX);\n# Read the file:\n@LINES=<TST>;\n# Wipe the file:\nseek(TST, 0, 0); truncate(TST, 0);\n# Do something with the contents here:\npush @LINES,\"grappig, he!\\n\";\n$LINES[3]=\"Gekke henkie!\\n\";\n# Write the file:\nforeach $l (@LINES)\n{\n print TST $l;\n}\nclose(TST) or die \"Cannot close file\\n$!\";\n"
},
{
"answer_id": 11473761,
"author": "sean ur",
"author_id": 1523990,
"author_profile": "https://Stackoverflow.com/users/1523990",
"pm_score": 1,
"selected": false,
"text": "use Fcntl qw(:DEFAULT :flock :seek :Fcompat);\nuse File::FcntlLock;\nsub acquire_lock {\n my $fn = shift;\n my $justPrint = shift || 0;\n confess \"Too many args\" if defined shift;\n confess \"Not enough args\" if !defined $justPrint;\n\n my $rv = TRUE;\n my $fh;\n sysopen($fh, $fn, O_RDWR | O_CREAT) or LOGDIE \"failed to open: $fn: $!\";\n $fh->autoflush(1);\n ALWAYS \"acquiring lock: $fn\";\n my $fs = new File::FcntlLock;\n $fs->l_type( F_WRLCK );\n $fs->l_whence( SEEK_SET );\n $fs->l_start( 0 );\n $fs->lock( $fh, F_SETLKW ) or LOGDIE \"failed to get write lock: $fn:\" . $fs->error;\n my $num = <$fh> || 0;\n return ($fh, $num);\n}\n\nsub release_lock {\n my $fn = shift;\n my $fh = shift;\n my $num = shift;\n my $justPrint = shift || 0;\n\n seek($fh, 0, SEEK_SET) or LOGDIE \"seek failed: $fn: $!\";\n print $fh \"$num\\n\" or LOGDIE \"write failed: $fn: $!\";\n truncate($fh, tell($fh)) or LOGDIE \"truncate failed: $fn: $!\";\n my $fs = new File::FcntlLock;\n $fs->l_type(F_UNLCK);\n ALWAYS \"releasing lock: $fn\";\n $fs->lock( $fh, F_SETLK ) or LOGDIE \"unlock failed: $fn: \" . $fs->error;\n close($fh) or LOGDIE \"close failed: $fn: $!\";\n}\n"
},
{
"answer_id": 25940666,
"author": "Mark Lawrence",
"author_id": 1450404,
"author_profile": "https://Stackoverflow.com/users/1450404",
"pm_score": 1,
"selected": false,
"text": "use Lock::Socket qw/lock_socket/;\nmy $lock = lock_socket(5197); # raises exception if lock already taken\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1539/"
] |
34,925 |
<p>I've seen quite a few posts on changes in .NET 3.5 SP1, but stumbled into one that I've yet to see documentation for yesterday. I had code working just fine on my machine, from VS, msbuild command line, everything, but it failed on the build server (running .NET 3.5 RTM).</p>
<pre><code>[XmlRoot("foo")]
public class Foo
{
static void Main()
{
XmlSerializer serializer = new XmlSerializer(typeof(Foo));
string xml = @"<foo name='ack' />";
using (StringReader sr = new StringReader(xml))
{
Foo foo = serializer.Deserialize(sr) as Foo;
}
}
[XmlAttribute("name")]
public string Name { get; set; }
public Foo Bar { get; private set; }
}
</code></pre>
<p>In SP1, the above code runs just fine. In RTM, you get an InvalidOperationException:</p>
<blockquote>
<p>Unable to generate a temporary class (result=1).
error CS0200: Property or indexer 'ConsoleApplication2.Foo.Bar' cannot be assign to -- it is read only</p>
</blockquote>
<p>Of course, all that's needed to make it run under RTM is adding [XmlIgnore] to the Bar property.</p>
<p>My google fu is apparently not up to finding documentation of these kinds of changes. Is there a change list anywhere that lists this change (and similar under-the-hood changes that might jump up and shout "gotcha")? Is this a bug or a feature? </p>
<p><strong>EDIT</strong>: In SP1, if I added a <code><Bar /></code> element, or set [XmlElement] for the Bar property, it won't get deserialized. It doesn't fail pre-SP1 when it tries to deserialize--it throws an exception when the XmlSerializer is constructed.</p>
<p>This makes me lean more toward it being a bug, especially if I set an [XmlElement] attribute for Foo.Bar. If it's unable to do what I ask it to do, it should be throwing an exception instead of silently ignoring Foo.Bar. Other invalid combinations/settings of XML serialization attributes result in an exception.</p>
<p><strong>EDIT</strong>: Thank you, TonyB, I'd not known about setting the temp files location. For those that come across similar issues in the future, you do need an additional config flag:</p>
<pre><code><system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="1" />
</switches>
</system.diagnostics>
<system.xml.serialization>
<xmlSerializer tempFilesLocation="c:\\foo"/>
</system.xml.serialization>
</code></pre>
<p>Even with setting an [XmlElement] attribute on the Bar property, no mention was made of it in the generated serialization assembly--which fairly firmly puts this in the realm of a silently swallowed error (aka, a bug). Either that or the designers have decided [XmlIgnore] is no longer necessary for properties that can't be set--and you'd expect to see that in release notes, <a href="http://support.microsoft.com/kb/951847" rel="nofollow noreferrer">change lists</a>, or the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlignoreattribute.aspx" rel="nofollow noreferrer">XmlIgnoreAttribute documentation</a>.</p>
|
[
{
"answer_id": 35223,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 3,
"selected": true,
"text": "<system.xml.serialization> \n <xmlSerializer tempFilesLocation=\"c:\\\\foo\"/> \n</system.xml.serialization> \n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2314/"
] |
34,926 |
<p>my <b>SSRS DataSet</b> returns a field with HTML, e.g.</p>
<pre><code><b>blah blah </b><i> blah </i>.
</code></pre>
<p>how do i strip all the HTML tags? has to be done with <b>inline</b> VB.NET</p>
<p>Changing the data in the table is not an option.</p>
<p><strong>Solution found</strong> ... = System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, "<[^>]+>","")</p>
|
[
{
"answer_id": 35012,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 5,
"selected": true,
"text": "= System.Text.RegularExpressions.Regex.Replace(StringWithHTMLtoStrip, \"<[^>]+>\",\"\")"
},
{
"answer_id": 23781709,
"author": "Peter",
"author_id": 58553,
"author_profile": "https://Stackoverflow.com/users/58553",
"pm_score": 1,
"selected": false,
"text": "Dim mRemoveTagRegex AS NEW System.Text.RegularExpressions.Regex(\"<(.|\\n)+?>\", System.Text.RegularExpressions.RegexOptions.Compiled)\n\nFunction RemoveHtml(ByVal text As string) AS string\n If text IsNot Nothing Then\n Return mRemoveTagRegex.Replace(text, \"\")\n End If \nEnd Function\n Code.RemoveHtml(Fields!Content.Value)"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
34,938 |
<p>I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.</p>
<p>if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?</p>
<pre><code>if ( (condition1) | (condition2) ){
// do this
}
</code></pre>
<p>or would I need to nest two if statements to only check the second condition if the first evaluates to false?</p>
<pre><code>if (condition1){
// do this
}else if (condition2){
// do this
}
</code></pre>
<p>I am working in PHP, however, I assume that this may be language-agnostic.</p>
|
[
{
"answer_id": 34954,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 4,
"selected": true,
"text": "a || b();\n if(!a)\n b();\n a && b();\n if(a)\n b();\n"
},
{
"answer_id": 34961,
"author": "Farinha",
"author_id": 2841,
"author_profile": "https://Stackoverflow.com/users/2841",
"pm_score": 2,
"selected": false,
"text": "<?php\n/* ch06ex07 – shows no output because of short circuit evaluation */\n\nif (true || $intVal = 5) // short circuits after true\n{\n\necho $intVal; // will be empty because the assignment never took place\n}\n\n?>\n"
},
{
"answer_id": 34963,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 2,
"selected": false,
"text": " if (condition1 | condition2) {\n ...\n}\n \nif (condition1 || condition2) {\n ...\n}\n condition2 condition1 || if else"
},
{
"answer_id": 34997,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 0,
"selected": false,
"text": "| $a OR $b &&"
},
{
"answer_id": 35391,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "if( pObj != NULL && *pObj == \"username\" ) {\n // Do something...\n}\n pObj if"
},
{
"answer_id": 35399,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "If FirstName = \"Luke\" OrElse FirstName = \"Darth\" Then\n Console.Writeline \"Greetings Exalted One!\"\nEnd If\n If FirstName = \"Luke\" AndAlso LastName = \"Skywalker\" Then\n Console.Writeline \"You are the one and only.\"\nEnd If\n"
},
{
"answer_id": 77527,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if (i < array.size() && array[i]==foo) ...\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083/"
] |
34,955 |
<p>When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors?</p>
|
[
{
"answer_id": 41043,
"author": "Joe Schneider",
"author_id": 1541,
"author_profile": "https://Stackoverflow.com/users/1541",
"pm_score": 6,
"selected": true,
"text": "ByteComparator.obj : error LNK2019: unresolved external symbol \"int __cdecl does_not_exist(void)\" (?does_not_exist@@YAHXZ) referenced in function \"void __cdecl TextScan(struct FileTextStats &,char const *,char const *,bool,bool,__int64)\" (?TextScan@@YAXAAUFileTextStats@@PBD1_N2_J@Z)\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
] |
34,975 |
<p>The company I work for is starting to have issues with their current branching model and I was wondering what different kinds of branching strategies the community has been exposed to?</p>
<p>Are there any good ones for different situations? What does your company use? What are the advantages and disadvantages of them??</p>
|
[
{
"answer_id": 59510,
"author": "Andrew Burns",
"author_id": 3683,
"author_profile": "https://Stackoverflow.com/users/3683",
"pm_score": 3,
"selected": false,
"text": "/trunk\n/branches\n/sandbox\n/vendor\n/ccnet\n"
},
{
"answer_id": 2461043,
"author": "bo bo",
"author_id": 67706,
"author_profile": "https://Stackoverflow.com/users/67706",
"pm_score": 0,
"selected": false,
"text": " trunk - tags\n |\n next\n / \\ \\\nbugfix f1 f2\n / \\ \\ \n f11 f21 f22\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2328/"
] |
34,977 |
<p>I have a protocol that requires a length field up to 32-bits, and it must be
generated at runtime to describe how many bytes are in a given packet.</p>
<p>The code below is kind of ugly but I am wondering if this can be refactored to
be slightly more efficient or easily understandable. The problem is that the
code will only generate enough bytes to describe the length of the packet, so
less than 255 bytes = 1 byte of length, less than 65535 = 2 bytes of length
etc...</p>
<pre><code>{
extern char byte_stream[];
int bytes = offset_in_packet;
int n = length_of_packet;
/* Under 4 billion, so this can be represented in 32 bits. */
int t;
/* 32-bit number used for temporary storage. */
/* These are the bytes we will break up n into. */
unsigned char first, second, third, fourth;
t = n & 0xFF000000;
/* We have used AND to "mask out" the first byte of the number. */
/* The only bits which can be on in t are the first 8 bits. */
first = t >> 24;
if (t) {
printf("byte 1: 0x%02x\n",first );
byte_stream[bytes] = first; bytes++;
write_zeros = 1;
}
/* Now we shift t so that it is between 0 and 255. This is the first, highest byte of n. */
t = n & 0x00FF0000;
second = t >> 16;
if (t || write_zeros) {
printf("byte 2: 0x%02x\n", second );
byte_stream[bytes] = second; bytes++;
write_zeros = 1;
}
t = n & 0x0000FF00;
third = t >> 8;
if ( t || write_zeros) {
printf("byte 3: 0x%02x\n", third );
byte_stream[bytes] = third; bytes++;
write_zeros = 1;
}
t = n & 0x000000FF;
fourth = t;
if (t || write_zeros) {
printf("byte 4: 0x%02x\n", fourth);
byte_stream[bytes] = fourth; bytes++;
}
}
</code></pre>
|
[
{
"answer_id": 35027,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "{\n extern char byte_stream[];\n int bytes = offset_in_packet;\n int n = length_of_packet; /* Under 4 billion, so this can be represented in 32 bits. */\n int t; /* 32-bit number used for temporary storage. */\n int i;\n\n unsigned char curByte;\n\n for (i = 0; i < 4; i++) {\n t = n & (0xFF000000 >> (i * 16));\n\n curByte = t >> (24 - (i * 8));\n if (t || write_zeros) {\n printf(\"byte %d: 0x%02x\\n\", i, curByte );\n byte_stream[bytes] = curByte;\n bytes++;\n write_zeros = 1;\n }\n\n }\n\n}\n"
},
{
"answer_id": 35036,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 0,
"selected": false,
"text": "int i; \nint write_zeros = 0; \nfor (i = 3; i >=0 ; --i) { \n t = (n >> (8 * i)) & 0xff; \n if (t || write_zeros) { \n write_zeros = 1; \n printf (\"byte %d : 0x%02x\\n\", 4-i, t); \n byte_stream[bytes++] = t;\n } \n}\n"
},
{
"answer_id": 41051,
"author": "Bart",
"author_id": 4343,
"author_profile": "https://Stackoverflow.com/users/4343",
"pm_score": 1,
"selected": true,
"text": "/* append byte b to stream, increment index */\n/* really needs to check length of stream before appending */\nvoid output( int i, unsigned char b, char stream[], int *index )\n{\n printf(\"byte %d: 0x%02x\\n\", i, b);\n stream[(*index)++] = b;\n}\n\n\nvoid answer( char bytestream[], unsigned int *bytes, unsigned int n)\n{\n /* mask out four bytes from word n */\n first = (n & 0xFF000000) >> 24;\n second = (n & 0x00FF0000) >> 16;\n third = (n & 0x0000FF00) >> 8;\n fourth = (n & 0x000000FF) >> 0;\n\n /* conditionally output each byte starting with the */\n /* first non-zero byte */\n if (first) \n output( 1, first, bytestream, bytes);\n\n if (first || second) \n output( 2, second, bytestream, bytes);\n\n if (first || second || third) \n output( 3, third, bytestream, bytes);\n\n if (first || second || third || fourth) \n output( 4, fourth, bytestream, bytes);\n }\n if (n>0x00FFFFFF) \n output( 1, first, bytestream, bytes);\n\n if (n>0x0000FFFF) \n output( 2, second, bytestream, bytes);\n\n if (n>0x000000FF) \n output( 3, third, bytestream, bytes);\n\n if (1) \n output( 4, fourth, bytestream, bytes);\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3663/"
] |
34,987 |
<p>I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?</p>
<p>Possible non-solutions:</p>
<pre><code>vector<string> v;
v.push_back("abc");
b.push_back("xyz");
for(int i = 0; i < v.size(); i++)
cout << v[i] << endl;
</code></pre>
<p>Problems - no way to create the vector on one line with a list of strings</p>
<p>Possible non-solution 2:</p>
<pre><code>string list[] = {"abc", "xyz"};
</code></pre>
<p>Problems - no way to get the number of strings automatically (that I know of).</p>
<p>There must be an easy way of doing this.</p>
|
[
{
"answer_id": 35006,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 5,
"selected": false,
"text": "arraysize #define arraysize(ar) (sizeof(ar) / sizeof(ar[0]))\n"
},
{
"answer_id": 35182,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <iterator>\n\nint main() {\n const char* const list[] = {\"zip\", \"zam\", \"bam\"};\n const size_t len = sizeof(list) / sizeof(list[0]);\n\n for (size_t i = 0; i < len; ++i)\n std::cout << list[i] << \"\\n\";\n\n const std::vector<string> v(list, list + len);\n std::copy(v.begin(), v.end(), std::ostream_iterator<string>(std::cout, \"\\n\"));\n}\n"
},
{
"answer_id": 35323,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 5,
"selected": false,
"text": "vector<string> char* char* strarray[] = {\"hey\", \"sup\", \"dogg\"};\nvector<string> strvector(strarray, strarray + 3);\n DEFINE_STR_VEC(strvector, \"hi\", \"there\", \"everyone\");"
},
{
"answer_id": 35356,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 2,
"selected": false,
"text": "#define arraysize(ar) (sizeof(ar) / sizeof(ar[0])) some_function(string parameter[]) some_function(string *parameter)"
},
{
"answer_id": 35424,
"author": "Anthony Cramp",
"author_id": 488,
"author_profile": "https://Stackoverflow.com/users/488",
"pm_score": 7,
"selected": false,
"text": "std::vector<std::string> v = {\"Hello\", \"World\"};\n"
},
{
"answer_id": 37330,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 2,
"selected": false,
"text": "template<typename T, int N>\ninline size_t array_size(T(&)[N])\n{\n return N;\n}\n\n#define ARRAY_SIZE(X) (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)\n"
},
{
"answer_id": 47267,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "#include <boost/foreach.hpp>\n\nconst char* list[] = {\"abc\", \"xyz\"};\nBOOST_FOREACH(const char* str, list)\n{\n cout << str << endl;\n}\n"
},
{
"answer_id": 66180,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "const char *list[] = {\"dog\", \"cat\", NULL};\nfor (char **iList = list; *iList != NULL; ++iList)\n{\n cout << *iList;\n}\n"
},
{
"answer_id": 124480,
"author": "Ross Smith",
"author_id": 21426,
"author_profile": "https://Stackoverflow.com/users/21426",
"pm_score": 2,
"selected": false,
"text": "begin end const char* array[] = { \"cat\", \"dog\", \"horse\" };\nvector<string> vec(begin(array), end(array));\n"
},
{
"answer_id": 1893430,
"author": "Dominic.wig",
"author_id": 184997,
"author_profile": "https://Stackoverflow.com/users/184997",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <boost/assign/list_of.hpp>\n\nint main()\n{\n const std::vector< std::string > v = boost::assign::list_of( \"abc\" )( \"xyz\" );\n std::copy(\n v.begin(),\n v.end(),\n std::ostream_iterator< std::string >( std::cout, \"\\n\" ) );\n}\n"
},
{
"answer_id": 8820663,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "char array_of_strings[][] char array_of_strings[200][8192]; strcpy(line[i],tempBuffer);"
},
{
"answer_id": 35067543,
"author": "kajol jain",
"author_id": 5853232,
"author_profile": "https://Stackoverflow.com/users/5853232",
"pm_score": 1,
"selected": false,
"text": "string s[100]; s[2][90] s[i].size()"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/34987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/779/"
] |
35,002 |
<p><strong>Is there anything built into the core C# libraries that can give me an immutable Dictionary?</strong> </p>
<p>Something along the lines of <em>Java's</em>:</p>
<pre><code>Collections.unmodifiableMap(myMap);
</code></pre>
<p>And just to clarify, I am not looking to stop the keys / values themselves from being changed, just the structure of the Dictionary. I want something that fails fast and loud if any of IDictionary's mutator methods are called (<code>Add, Remove, Clear</code>).</p>
|
[
{
"answer_id": 35144,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "var dict = new Dictionary<string, string>();\n\ndict.Add(\"Hello\", \"World\");\ndict.Add(\"The\", \"Quick\");\ndict.Add(\"Brown\", \"Fox\");\n\nvar dictCopy = dict.Select(\n item => new KeyValuePair<string, string>(item.Key, item.Value));\n\n// returns dictCopy;\n"
},
{
"answer_id": 35666,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 7,
"selected": true,
"text": "public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>\n{\n IDictionary<TKey, TValue> _dict;\n\n public ReadOnlyDictionary(IDictionary<TKey, TValue> backingDict)\n {\n _dict = backingDict;\n }\n\n public void Add(TKey key, TValue value)\n {\n throw new InvalidOperationException();\n }\n\n public bool ContainsKey(TKey key)\n {\n return _dict.ContainsKey(key);\n }\n\n public ICollection<TKey> Keys\n {\n get { return _dict.Keys; }\n }\n\n public bool Remove(TKey key)\n {\n throw new InvalidOperationException();\n }\n\n public bool TryGetValue(TKey key, out TValue value)\n {\n return _dict.TryGetValue(key, out value);\n }\n\n public ICollection<TValue> Values\n {\n get { return _dict.Values; }\n }\n\n public TValue this[TKey key]\n {\n get { return _dict[key]; }\n set { throw new InvalidOperationException(); }\n }\n\n public void Add(KeyValuePair<TKey, TValue> item)\n {\n throw new InvalidOperationException();\n }\n\n public void Clear()\n {\n throw new InvalidOperationException();\n }\n\n public bool Contains(KeyValuePair<TKey, TValue> item)\n {\n return _dict.Contains(item);\n }\n\n public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)\n {\n _dict.CopyTo(array, arrayIndex);\n }\n\n public int Count\n {\n get { return _dict.Count; }\n }\n\n public bool IsReadOnly\n {\n get { return true; }\n }\n\n public bool Remove(KeyValuePair<TKey, TValue> item)\n {\n throw new InvalidOperationException();\n }\n\n public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()\n {\n return _dict.GetEnumerator();\n }\n\n System.Collections.IEnumerator \n System.Collections.IEnumerable.GetEnumerator()\n {\n return ((System.Collections.IEnumerable)_dict).GetEnumerator();\n }\n}\n"
},
{
"answer_id": 1104668,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 2,
"selected": false,
"text": "private readonly int _finalCount;\n\n/// <summary>\n/// Takes a count of how many key-value pairs should be allowed.\n/// Dictionary can be modified to add up to that many pairs, but no\n/// pair can be modified or removed after it is added. Intended to be\n/// used with an object initializer.\n/// </summary>\n/// <param name=\"count\"></param>\npublic ReadOnlyDictionary(int count)\n{\n _dict = new SortedDictionary<TKey, TValue>();\n _finalCount = count;\n}\n\n/// <summary>\n/// To allow object initializers, this will allow the dictionary to be\n/// added onto up to a certain number, specifically the count set in\n/// one of the constructors.\n/// </summary>\n/// <param name=\"key\"></param>\n/// <param name=\"value\"></param>\npublic void Add(TKey key, TValue value)\n{\n if (_dict.Keys.Count < _finalCount)\n {\n _dict.Add(key, value);\n }\n else\n {\n throw new InvalidOperationException(\n \"Cannot add pair <\" + key + \", \" + value + \"> because \" +\n \"maximum final count \" + _finalCount + \" has been reached\"\n );\n }\n}\n ReadOnlyDictionary<string, string> Fields =\n new ReadOnlyDictionary<string, string>(2)\n {\n {\"hey\", \"now\"},\n {\"you\", \"there\"}\n };\n"
},
{
"answer_id": 1428665,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "using System.Linq;\n// (...)\nvar dictionary = new Dictionary<string, object>();\n// (...)\nvar read_only = dictionary.ToLookup(kv => kv.Key, kv => kv.Value);\n"
},
{
"answer_id": 6471072,
"author": "David Moles",
"author_id": 27358,
"author_profile": "https://Stackoverflow.com/users/27358",
"pm_score": 2,
"selected": false,
"text": "ReadOnly() Algorithms"
},
{
"answer_id": 8585197,
"author": "uglybugger",
"author_id": 94697,
"author_profile": "https://Stackoverflow.com/users/94697",
"pm_score": 1,
"selected": false,
"text": "private readonly Dictionary<string, string> _someDictionary;\n\npublic IEnumerable<KeyValuePair<string, string>> SomeDictionary\n{\n get { return _someDictionary; }\n}\n foo.SomeDictionary.ToDictionary(kvp => kvp.Key);\n foo.SomeDictionary.First(kvp => kvp.Key == \"SomeKey\");\n"
},
{
"answer_id": 12463109,
"author": "Dylan Meador",
"author_id": 684831,
"author_profile": "https://Stackoverflow.com/users/684831",
"pm_score": 4,
"selected": false,
"text": "IDictionary"
},
{
"answer_id": 19387663,
"author": "Fredrik Solhaug",
"author_id": 2883636,
"author_profile": "https://Stackoverflow.com/users/2883636",
"pm_score": 1,
"selected": false,
"text": "public interface IMyDomainObjectDictionary \n{\n IMyDomainObject GetMyDomainObject(string key);\n}\n\ninternal class MyDomainObjectDictionary : IMyDomainObjectDictionary \n{\n public IDictionary<string, IMyDomainObject> _myDictionary { get; set; }\n public IMyDomainObject GetMyDomainObject(string key) {.._myDictionary .TryGetValue..etc...};\n}\n"
},
{
"answer_id": 61090094,
"author": "Andrej Lucansky",
"author_id": 1503963,
"author_profile": "https://Stackoverflow.com/users/1503963",
"pm_score": 2,
"selected": false,
"text": "using System.Collections.Immutable;\n\npublic MyClass {\n private Dictionary<KeyType, ValueType> myDictionary;\n\n public ImmutableDictionary<KeyType, ValueType> GetImmutable()\n {\n return myDictionary.ToImmutableDictionary();\n }\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
35,007 |
<p>Every time I create an object that has a collection property I go back and forth on the best way to do it?</p>
<ol>
<li>public property with a getter that
returns a reference to private variable</li>
<li>explicit get_ObjList and set_ObjList
methods that return and create new or cloned
objects every time</li>
<li>explicit get_ObjList that returns an
IEnumerator and a set_ObjList that
takes IEnumerator</li>
</ol>
<p>Does it make a difference if the collection is an array (i.e., objList.Clone()) versus a List?</p>
<p>If returning the actual collection as a reference is so bad because it creates dependencies, then why return any property as a reference? Anytime you expose an child object as a reference the internals of that child can be changed without the parent "knowing" unless the child has a property changed event. Is there a risk for memory leaks?</p>
<p>And, don't options 2 and 3 break serialization? Is this a catch 22 or do you have to implement custom serialization anytime you have a collection property?</p>
<p>The generic ReadOnlyCollection seems like a nice compromise for general use. It wraps an IList and restricts access to it. Maybe this helps with memory leaks and serialization. However it still has <a href="http://www.coversant.net/Coversant/Blogs/tabid/88/EntryID/34/Default.aspx" rel="noreferrer">enumeration concerns</a> </p>
<p>Maybe it just depends. If you don't care that the collection is modified, then just expose it as a public accessor over a private variable per #1. If you don't want other programs to modify the collection then #2 and/or #3 is better.</p>
<p>Implicit in the question is why should one method be used over another and what are the ramifications on security, memory, serialization, etc.?</p>
|
[
{
"answer_id": 35065,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "public ReadOnlyCollection<SomeClass> Collection\n{\n get\n {\n return new ReadOnlyCollection<SomeClass>(myList);\n }\n}\n Clear();\nAdd(SomeClass class);\n"
},
{
"answer_id": 35154,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 0,
"selected": false,
"text": "clearAll() addAll()"
},
{
"answer_id": 38410,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 7,
"selected": true,
"text": "private readonly Collection<T> myCollection_ = new ...;\npublic Collection<T> MyCollection {\n get { return this.myCollection_; }\n}\n Items ItemsControl ItemsSource ItemsControl private readonly List<T> myPrivateCollection_ = new ...;\nprivate ReadOnlyCollection<T> myPrivateCollectionView_;\npublic ReadOnlyCollection<T> MyCollection {\n get {\n if( this.myPrivateCollectionView_ == null ) { /* lazily initialize view */ }\n return this.myPrivateCollectionView_;\n }\n}\n ReadOnlyCollection<T> IList<T> public IEnumerable<T> MyCollection {\n get {\n foreach( T item in this.myPrivateCollection_ )\n yield return item;\n }\n}\n private T[] myArray_;\npublic T[] GetMyArray( ) {\n T[] copy = new T[this.myArray_.Length];\n this.myArray_.CopyTo( copy, 0 );\n return copy;\n // Note: if you are using LINQ, calling the 'ToArray( )' \n // extension method will create a copy for you.\n}\n SetMyArray( T[] array ) public T this[int index] {\n get { return this.myArray_[index]; }\n set {\n // TODO: validate new value; raise change event; etc.\n this.myArray_[index] = value;\n }\n}\n"
},
{
"answer_id": 32914905,
"author": "jbe",
"author_id": 103988,
"author_profile": "https://Stackoverflow.com/users/103988",
"pm_score": 1,
"selected": false,
"text": "IReadOnlyList<T> IReadOnlyCollection<T> public class AddressBook\n{\n private readonly List<Contact> contacts;\n\n public AddressBook()\n {\n this.contacts = new List<Contact>();\n }\n\n public IReadOnlyList<Contact> Contacts { get { return contacts; } }\n\n public void AddContact(Contact contact)\n {\n contacts.Add(contact);\n }\n\n public void RemoveContact(Contact contact)\n {\n contacts.Remove(contact);\n }\n}\n ReadOnlyCollection<T> IEnumerable<T>"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582/"
] |
35,011 |
<p>I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?</p>
|
[
{
"answer_id": 35057,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 6,
"selected": true,
"text": "FOR %a IN (C:\\MyFolderWithAssemblies\\*.dll) DO GACUTIL /i %a\n"
},
{
"answer_id": 35064,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 4,
"selected": false,
"text": "FOR %1 IN (*) DO Gacutil /i %1\n"
},
{
"answer_id": 30016364,
"author": "Legends",
"author_id": 2581562,
"author_profile": "https://Stackoverflow.com/users/2581562",
"pm_score": 2,
"selected": false,
"text": "for ... in"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/667/"
] |
35,026 |
<p>I need to convert a named instance of SQL server 2005, to a default instance.</p>
<p>Is there a way to do this without a reinstall?</p>
<hr>
<p>The problem is, 2 out of 6 of the developers, installed with a named instance. So its becoming a pain changing connection strings for the other 4 of us. I am looking for the path of least resistance to getting these 2 back on to our teams standard setup. </p>
<p>Each has expressed that this is going to be, too much trouble and that it will take away from their development time. I assumed that it would take some time to resolve, in the best interest of all involved, I tried combing through configuration apps installed and didn't see anything, so I figured someone with more knowledge of the inner workings would be here.</p>
|
[
{
"answer_id": 11921896,
"author": "Zasz",
"author_id": 626084,
"author_profile": "https://Stackoverflow.com/users/626084",
"pm_score": 9,
"selected": false,
"text": "SQL Server Configuration Manager SQL Server Network Configuration Protocols for INSTANCENAME TCP/IP Enabled TCP/IP Properties IP Addresses IPAll TCP Dynamic Ports TCP Port 1433 Ok SQL Server Services SQL Server (INSTANCENAME) Restart"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1220/"
] |
35,037 |
<p>I have a directory with PDF files that I need to create an index for. It is a PHP page with a list of links:</p>
<pre><code><A HREF="path to file">filename</A>
</code></pre>
<p>The filenames can be complicated:</p>
<pre><code>LVD 2-1133 - Ändring av dumpningslina (1984-11-20).pdf
</code></pre>
<p>What is the correct way to link to this file on a Linux/Apache server?</p>
<p>Is there a PHP function to do this conversion?</p>
|
[
{
"answer_id": 35046,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 0,
"selected": false,
"text": "\n <?php\n echo urlencode(\"åäö\"); \n ?>\n \n %E5%E4%F6\n"
},
{
"answer_id": 35048,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 0,
"selected": false,
"text": "urlencode()"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2703/"
] |
35,047 |
<p>Perhaps the biggest risk in pushing new functionality to live lies with the database modifications required by the new code. In Rails, I believe they have 'migrations', in which you can programmatically make changes to your development host, and then make the same changes live along with the code that uses the revised schema. And roll both backs if needs be, in a synchronized fashion.</p>
<p>Has anyone come across a similar toolset for PHP/MySQL? Would love to hear about it, or any programmatic or process solutions to help make this less risky...</p>
|
[
{
"answer_id": 35440,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 3,
"selected": false,
"text": "000-clean.sql # wipe out everything in the DB\n001-schema.sql # create the initial DB objects\n002-fk.sql # apply referential integrity (simple if kept separate)\n003-reference-pop.sql # populate reference data\n004-release-pop.sql # populate release data\n005-add-new-table.sql # modification\n006-rename-table.sql # another modification...\n"
},
{
"answer_id": 3488657,
"author": "Mike Howsden",
"author_id": 227651,
"author_profile": "https://Stackoverflow.com/users/227651",
"pm_score": 2,
"selected": false,
"text": "0-init.sql \n1-add-name-to-user.sql\n2-add-bio.sql\n BEGIN;\n-- comment about what this is doing\nALTER TABLE user ADD COLUMN bio text NULL;\n\nUPDATE db_schema SET version = 2;\nCOMMIT;\n #!/bin/sh\n\nVERSION=`psql -q -t <<EOF\n\\set ON_ERROR_STOP on\nSELECT version FROM db_schema;\nEOF\n`\n\n[ $? -eq 0 ] && {\n echo $VERSION\n exit 0\n}\n\necho 0\n #!/bin/sh\n\nCURRENT=`./current`\nLATEST=`ls -vr *.sql |egrep -o \"^[0-9]+\" |head -n1`\n\necho current is $CURRENT\necho latest is $LATEST\n\n[[ $CURRENT -gt $LATEST ]] && {\n echo That seems to be a problem.\n exit 1\n}\n\n[[ $CURRENT -eq $LATEST ]] && exit 0\n\n#SCRIPT_SET=\"-q\"\nSCRIPT_SET=\"\"\n\nfor (( I = $CURRENT + 1 ; I <= $LATEST ; I++ )); do\n SCRIPT=`ls $I-*.sql |head -n1`\n echo \"Adding '$SCRIPT'\"\n SCRIPT_SET=\"$SCRIPT_SET $SCRIPT\"\ndone\n\necho \"Applying updates...\"\necho $SCRIPT_SET\nfor S in $SCRIPT_SET ; do\n psql -v ON_ERROR_STOP=TRUE -f $S || {\n echo FAIL\n exit 1\n }\ndone\necho OK\n export PGDATABASE=\"dbname\"\nexport PGUSER=\"mike\"\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/137/"
] |
35,050 |
<p>After the suggestion to use a library for <a href="https://stackoverflow.com/questions/34486/what-more-is-needed-for-ajax-than-this-function">my ajax needs</a> I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart.</p>
<p>Thus, can anybody <br />
A) Give a rundown of the differences or <br />
B) Point me (and others like me) somewhere that has such a list.
<br /><br />Failing that plan C is to go with whichever gets mentioned the most here.</p>
|
[
{
"answer_id": 35101,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 2,
"selected": false,
"text": "function clickedme(event) {\n alert('Someone clicked me!');\n}\n$('#clickdivs div').click(clickedme);\n <div id=\"clickdivs\">\n <div>Click Here</div>\n <div>And Here</div>\n <p>Not here</p>\n <div>Click Here Too</div>\n</div>\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
35,070 |
<p>What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.</p>
<p>Or, if there's a better way to unit test against the registry...</p>
|
[
{
"answer_id": 35092,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 2,
"selected": false,
"text": "regedit.exe regedit.exe \"mytest.reg\""
},
{
"answer_id": 35162,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 4,
"selected": true,
"text": "REGEDIT4\n\n[-HKEY_CURRENT_USER\\Software\\<otherpath>]\n - Regedit regedit /s \"myfile.reg\"\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
35,076 |
<p>I'm working with a SQL Server 2000 database that likely has a few dozen tables that are no longer accessed. I'd like to clear out the data that we no longer need to be maintaining, but I'm not sure how to identify which tables to remove.</p>
<p>The database is shared by several different applications, so I can't be 100% confident that reviewing these will give me a complete list of the objects that are used.</p>
<p>What I'd like to do, if it's possible, is to get a list of tables that haven't been accessed at all for some period of time. No reads, no writes. How should I approach this?</p>
|
[
{
"answer_id": 35100,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 4,
"selected": true,
"text": "select * from ...\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3344/"
] |
35,102 |
<p>In emacs, I've read the following code snippet in <code>simple.el</code>:</p>
<pre><code>(frame-parameter frame 'buried-buffer-list)
</code></pre>
<p>What is the exact meaning of the <code>'buried-buffer-list</code> parameter?
What it is used for?</p>
|
[
{
"answer_id": 35100,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 4,
"selected": true,
"text": "select * from ...\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3673/"
] |
35,103 |
<p>I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.</p>
<p>Essentially if someone modifies this file outside of the program the program should fail to load it again.</p>
<p>EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.</p>
<p>The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.</p>
<hr>
<p>It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes.</p>
|
[
{
"answer_id": 35116,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 5,
"selected": true,
"text": "write(MD5(SecretKey + ConfigFileText));\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191/"
] |
35,106 |
<p>I've found <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.scriptingjsonserializationsection.scriptingjsonserializationsection.aspx" rel="noreferrer"><code>ScriptingJsonSerializationSection</code></a> but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <code><System.Web.Services.WebMethod()></code> and <code><System.Web.Script.Services.ScriptMethod()></code> attributes so there must be a built-in way that I'm missing. </p>
<p>PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.</p>
|
[
{
"answer_id": 35125,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 5,
"selected": true,
"text": "Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer\nDim jsonString as String = jsonSerialiser.Serialize(yourObject)\n"
},
{
"answer_id": 35128,
"author": "Joseph Kingry",
"author_id": 3046,
"author_profile": "https://Stackoverflow.com/users/3046",
"pm_score": 3,
"selected": false,
"text": "System.ServiceModel.Web.DataContractJsonSerializer"
},
{
"answer_id": 35133,
"author": "Steven Williams",
"author_id": 3294,
"author_profile": "https://Stackoverflow.com/users/3294",
"pm_score": 1,
"selected": false,
"text": "System.Web.Script.Serialization.JavaScriptSerializer\n"
},
{
"answer_id": 35136,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 2,
"selected": false,
"text": "using System.Web.Script.Serialization;\n\npublic static string ToJSON(this object objectToSerialize)\n{\n JavaScriptSerializer jss = new JavaScriptSerializer();\n return jss.Serialize(objectToSerialize);\n}\n\n/// <typeparam name=\"T\">The type we are deserializing the JSON to.</typeparam>\npublic static T FromJSON<T>(this string json)\n{\n JavaScriptSerializer jss = new JavaScriptSerializer();\n return jss.Deserialize<T>(json);\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
35,123 |
<p>What did I do wrong?</p>
<p>Here is an excerpt from my code:</p>
<pre><code>public void createPartControl(Composite parent) {
parent.setLayout(new FillLayout());
ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);
scrollBox.setExpandHorizontal(true);
mParent = new Composite(scrollBox, SWT.NONE);
scrollBox.setContent(mParent);
FormLayout layout = new FormLayout();
mParent.setLayout(layout);
// Adds a bunch of controls here
mParent.layout();
mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));
}
</code></pre>
<p>...but it clips the last button:
<img src="https://i.stack.imgur.com/1ubzc.png" alt="alt text" title="Screenshot"></p>
<p>bigbrother82: That didn't work.</p>
<p>SCdF: I tried your suggestion, and now the scrollbars are gone. I need to work some more on that.</p>
|
[
{
"answer_id": 36306,
"author": "Jacob Schoen",
"author_id": 3340,
"author_profile": "https://Stackoverflow.com/users/3340",
"pm_score": 2,
"selected": false,
"text": "mParent.layout();\n mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));\n public void createPartControl(Composite parent) {\n parent.setLayout(new FillLayout());\n ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);\n scrollBox.setExpandHorizontal(true);\n mParent = new Composite(scrollBox, SWT.NONE);\n scrollBox.setContent(mParent);\n FormLayout layout = new FormLayout();\n mParent.setLayout(layout);\n // Adds a bunch of controls here\n mParent.setSize(mParent.computeSize(SWT.DEFAULT, SWT.DEFAULT, true));\n mParent.layout();\n}\n"
},
{
"answer_id": 159454,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 5,
"selected": true,
"text": "ScrolledComposite mParent setMinHeight() public void createPartControl(Composite parent) {\n parent.setLayout(new FillLayout());\n ScrolledComposite scrollBox = new ScrolledComposite(parent, SWT.V_SCROLL);\n scrollBox.setExpandHorizontal(true);\n scrollBox.setExpandVertical(true);\n\n // Using 0 here ensures the horizontal scroll bar will never appear. If\n // you want the horizontal bar to appear at some threshold (say 100\n // pixels) then send that value instead.\n scrollBox.setMinWidth(0);\n\n mParent = new Composite(scrollBox, SWT.NONE);\n\n FormLayout layout = new FormLayout();\n mParent.setLayout(layout);\n\n // Adds a bunch of controls here\n\n mParent.addListener(SWT.Resize, new Listener() {\n int width = -1;\n public void handleEvent(Event e) {\n int newWidth = mParent.getSize().x;\n if (newWidth != width) {\n scrollBox.setMinHeight(mParent.computeSize(newWidth, SWT.DEFAULT).y);\n width = newWidth;\n }\n }\n }\n\n // Wait until here to set content pane. This way the resize listener will\n // fire when the scrolled composite first resizes mParent, which in turn\n // computes the minimum height and calls setMinHeight()\n scrollBox.setContent(mParent);\n}\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3657/"
] |
35,167 |
<p>I know that the following is true</p>
<pre><code>int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010
</code></pre>
<p>But, if you shift too far, the bits fall off the end. Where this happens is a matter of the size of integer you are working with.</p>
<p>Is there a way to perform a shift so that the bits rotate around to the other side? I'm looking for a single operation, not a for loop.</p>
|
[
{
"answer_id": 35172,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 7,
"selected": true,
"text": "uint i = 17;\nuint j = i << 1 | i >> 31;\n /*some unsigned numeric type*/ input = 17;\nvar result = input << n | input >> (b - n);\n"
},
{
"answer_id": 185743,
"author": "jaircazarin-old-account",
"author_id": 20915,
"author_profile": "https://Stackoverflow.com/users/20915",
"pm_score": 4,
"selected": false,
"text": "private UInt32 RotateLeft(UInt32 x, Byte n)\n{\n return UInt32((x << n) | (x >> (32 - n)));\n}\n"
},
{
"answer_id": 1042452,
"author": "yeyeyerman",
"author_id": 110466,
"author_profile": "https://Stackoverflow.com/users/110466",
"pm_score": 2,
"selected": false,
"text": "static public uint ShiftRight(uint z_value, int z_shift)\n{\n return ((z_value >> z_shift) | (z_value << (16 - z_shift))) & 0x0000FFFF;\n}\n\nstatic public uint ShiftLeft(uint z_value, int z_shift)\n{\n return ((z_value << z_shift) | (z_value >> (16 - z_shift))) & 0x0000FFFF;\n}\n"
},
{
"answer_id": 60161031,
"author": "phuclv",
"author_id": 995714,
"author_profile": "https://Stackoverflow.com/users/995714",
"pm_score": 3,
"selected": false,
"text": "BitOperations.RotateLeft() BitOperations.RotateRight() BitOperations.RotateRight(12, 3);\nBitOperations.RotateLeft(34L, 5);\n BitRotator.RotateLeft() BitRotator.RotateRight()"
},
{
"answer_id": 66592889,
"author": "Soleil",
"author_id": 1447389,
"author_profile": "https://Stackoverflow.com/users/1447389",
"pm_score": 1,
"selected": false,
"text": "uint public static uint ROR(this uint x, int nbitsShift)\n => (x >> nbitsShift) | (x << (32 - nbitsShift));\n\npublic static uint ROL(this uint x, int nbitsShift)\n => (x << nbitsShift) | (x >> (32 - nbitsShift));\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] |
35,178 |
<p>I am working on a C++ code base that was recently moved from X/Motif to Qt. I am trying to write a Perl script that will replace all occurrences of Boolean (from X) with bool. The script just does a simple replacement. </p>
<pre><code>s/\bBoolean\b/bool/g
</code></pre>
<p>There are a few conditions. </p>
<p>1) We have CORBA in our code and \b matches CORBA::Boolean which should <strong>not</strong> be changed.<br>
2) It should not match if it was found as a string (i.e. "Boolean")</p>
<p><strong>Updated:</strong></p>
<p>For #1, I used lookbehind</p>
<pre><code>s/(?<!:)\bBoolean\b/bool/g;
</code></pre>
<p>For #2, I used lookahead.</p>
<pre><code>s/(?<!:)\bBoolean\b(?!")/bool/g</pre>
</code></pre>
<p>This will most likely work for my situation but how about the following improvements?</p>
<p>3) Do not match if in the middle of a string (thanks <a href="https://stackoverflow.com/users/3101/nohat">nohat</a>).<br>
4) Do not match if in a comment. (// or /**/) </p>
|
[
{
"answer_id": 35198,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "s/[^:]\\bBoolean\\b(?!\")/bool/g\n"
},
{
"answer_id": 35203,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 1,
"selected": false,
"text": "s/[^:]\\bBoolean\\b[^\"]/bool/g\n"
},
{
"answer_id": 86920,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 0,
"selected": false,
"text": "my $line_comment = qr! (?> // .* \\n? ) !x;\nmy $multiline_comment = qr! (?> /\\* [^*]* (?: \\* (?: [^/*] [^*]* )? )* )* \\*/ ) !x;\nmy $string = qr! (?> \" [^\"\\\\]* (?: \\\\ . [^\"\\\\]* )* \" ) !x;\nmy $boolean_type = qr! (?<!:) \\b Boolean \\b !x;\n\n$code =~ s{ \\G (\n $line_comment\n | $multiline_comment\n | $string\n | ( $boolean_type )\n | .\n) }{\n defined $2 ? 'bool' : $1\n}gex;\n"
},
{
"answer_id": 88938,
"author": "Victor",
"author_id": 14514,
"author_profile": "https://Stackoverflow.com/users/14514",
"pm_score": 0,
"selected": false,
"text": "m/\"[^\"]*Boolean[^\"]*\"/\n"
},
{
"answer_id": 95149,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 1,
"selected": false,
"text": "#define Boolean bool\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897/"
] |
35,185 |
<p>What would be the best algorithm for finding a number that occurs only once in a list which has all other numbers occurring exactly twice.</p>
<p>So, in the list of integers (lets take it as an array) each integer repeats exactly twice, except one. To find that one, what is the best algorithm.</p>
|
[
{
"answer_id": 35195,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 4,
"selected": false,
"text": "if(HT.Contains(item)) -> HT.Remove(item)\nelse\nht.add(item)\n"
},
{
"answer_id": 35235,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": -1,
"selected": false,
"text": "def find_dupe(array)\n h={}\n array.detect { |e| h[e]||(h[e]=true; false) }\nend\n find_dupe([1,2,3,4,5,1]) n*(n+1)/2 def find_dupe_for_consecutive_integers(array)\n n=array.size-1 # subtract one from array.size because of the dupe\n array.sum - n*(n+1)/2\nend\n"
},
{
"answer_id": 35271,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 8,
"selected": true,
"text": "int arr[] = {3, 2, 5, 2, 1, 5, 3};\n\nint num = 0, i;\n\nfor (i=0; i < 7; i++)\n num ^= arr[i];\n\nprintf(\"%i\\n\", num);\n"
},
{
"answer_id": 25834770,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 1,
"selected": false,
"text": "a = [1,2,3,4,123,1,2,.........]\nt = a.length-1\nfor i in 0..t\n s = a.index(a[i])+1\n b = a[s..t]\n w = b.include?a[i]\n if w == false\n puts a[i]\n end\nend\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] |
35,186 |
<p>I'm getting a <code>NoSuchMethodError</code> error when running my Java program. What's wrong and how do I fix it?</p>
|
[
{
"answer_id": 35350,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 3,
"selected": false,
"text": "Class.getDeclaredMethod(\"someMethodName\", .....) getDeclaredMethod NoSuchMethodException TestUtilities"
},
{
"answer_id": 36617,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "NoSuchMethodException NoSuchMethodError"
},
{
"answer_id": 42097,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 6,
"selected": false,
"text": "java -verbose:class <other args>\n"
},
{
"answer_id": 31451884,
"author": "Quảng Trường Thời Đại",
"author_id": 5123156,
"author_profile": "https://Stackoverflow.com/users/5123156",
"pm_score": 2,
"selected": false,
"text": "filenotnull=/DayMoreConfig.conf\n16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775\n16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) ) \nException in thread \"main\" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V\n at gateway.smpp.USSDClient.bind(USSDClient.java:139)\n at gateway.USSDGW.initSmppConnection(USSDGW.java:274)\n at gateway.USSDGW.<init>(USSDGW.java:184)\n at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)\n\n-bash-3.00$ \n"
},
{
"answer_id": 33004790,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 4,
"selected": false,
"text": "clean install\n"
},
{
"answer_id": 46686696,
"author": "AnonymousCoder",
"author_id": 1454390,
"author_profile": "https://Stackoverflow.com/users/1454390",
"pm_score": 1,
"selected": false,
"text": "Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I\n Employee.java EmpId int String ReportGeneration.java getEmpId() ReportGeneration.java Employee.class ReportGeneration.class"
},
{
"answer_id": 49997295,
"author": "WHOIF",
"author_id": 8693157,
"author_profile": "https://Stackoverflow.com/users/8693157",
"pm_score": 2,
"selected": false,
"text": "mvn clean javac NoSuchMethodError"
},
{
"answer_id": 50179330,
"author": "Mihai Savin",
"author_id": 4289110,
"author_profile": "https://Stackoverflow.com/users/4289110",
"pm_score": 1,
"selected": false,
"text": "void invest(Currency money){...}\n void invest(Euro money){...}\n public static void main(String args[]) {\n Bank myBank = new Bank();\n\n Euro capital = new Euro();\n myBank.invest(capital);\n}\n #7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V\n"
},
{
"answer_id": 50558413,
"author": "Dave Inlow",
"author_id": 9856495,
"author_profile": "https://Stackoverflow.com/users/9856495",
"pm_score": 2,
"selected": false,
"text": "App/ \n src/\n com.example/ \n Projection.java\nTest/ \n src/\n com.example/\n Projection.java\n"
},
{
"answer_id": 55582143,
"author": "invzbl3",
"author_id": 8370915,
"author_profile": "https://Stackoverflow.com/users/8370915",
"pm_score": 3,
"selected": false,
"text": " Exception in thread \"main\" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V\n at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)\n at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)\n at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)\n at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)\n click in your POM the combination -> Ctrl+Alt+Shift+U right click in your POM -> Maven -> Show dependencies <jackson.version>2.8.7</jackson.version>\n <dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>${jackson.version}</version>\n</dependency>\n <dependency>\n <groupId>group-a</groupId>\n <artifactId>artifact-a</artifactId>\n <version>1.0</version>\n <exclusions>\n <exclusion>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n </exclusion>\n </exclusions>\n </dependency>\n"
},
{
"answer_id": 56736243,
"author": "Gaurav Khare",
"author_id": 3662213,
"author_profile": "https://Stackoverflow.com/users/3662213",
"pm_score": 2,
"selected": false,
"text": "com.xyz.TestClass A B A B NoSuchMethodError"
},
{
"answer_id": 65420248,
"author": "Nachiket Doke",
"author_id": 5530721,
"author_profile": "https://Stackoverflow.com/users/5530721",
"pm_score": 1,
"selected": false,
"text": "NoSuchMethodError"
},
{
"answer_id": 66332755,
"author": "Cihat Özdenoğlu",
"author_id": 11190435,
"author_profile": "https://Stackoverflow.com/users/11190435",
"pm_score": 2,
"selected": false,
"text": "<plugin>\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-enforcer-plugin</artifactId>\n<version>3.0.0-M3</version>\n<configuration>\n <rules>\n <dependencyConvergence />\n </rules>\n</configuration>\n</plugin>\n\n mvn enforcer:enforce\n"
},
{
"answer_id": 69387076,
"author": "Murat Yıldız",
"author_id": 1604048,
"author_profile": "https://Stackoverflow.com/users/1604048",
"pm_score": 0,
"selected": false,
"text": "mockito-core 3.3.3 3.4.3"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535/"
] |
35,194 |
<p>Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008? Please note I am not referring to placing your actual source control system on that drive, but rather your working folder.</p>
<p>Thanks</p>
|
[
{
"answer_id": 35350,
"author": "rcreswick",
"author_id": 3446,
"author_profile": "https://Stackoverflow.com/users/3446",
"pm_score": 3,
"selected": false,
"text": "Class.getDeclaredMethod(\"someMethodName\", .....) getDeclaredMethod NoSuchMethodException TestUtilities"
},
{
"answer_id": 36617,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": false,
"text": "NoSuchMethodException NoSuchMethodError"
},
{
"answer_id": 42097,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 6,
"selected": false,
"text": "java -verbose:class <other args>\n"
},
{
"answer_id": 31451884,
"author": "Quảng Trường Thời Đại",
"author_id": 5123156,
"author_profile": "https://Stackoverflow.com/users/5123156",
"pm_score": 2,
"selected": false,
"text": "filenotnull=/DayMoreConfig.conf\n16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775\n16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) ) \nException in thread \"main\" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V\n at gateway.smpp.USSDClient.bind(USSDClient.java:139)\n at gateway.USSDGW.initSmppConnection(USSDGW.java:274)\n at gateway.USSDGW.<init>(USSDGW.java:184)\n at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)\n\n-bash-3.00$ \n"
},
{
"answer_id": 33004790,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 4,
"selected": false,
"text": "clean install\n"
},
{
"answer_id": 46686696,
"author": "AnonymousCoder",
"author_id": 1454390,
"author_profile": "https://Stackoverflow.com/users/1454390",
"pm_score": 1,
"selected": false,
"text": "Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I\n Employee.java EmpId int String ReportGeneration.java getEmpId() ReportGeneration.java Employee.class ReportGeneration.class"
},
{
"answer_id": 49997295,
"author": "WHOIF",
"author_id": 8693157,
"author_profile": "https://Stackoverflow.com/users/8693157",
"pm_score": 2,
"selected": false,
"text": "mvn clean javac NoSuchMethodError"
},
{
"answer_id": 50179330,
"author": "Mihai Savin",
"author_id": 4289110,
"author_profile": "https://Stackoverflow.com/users/4289110",
"pm_score": 1,
"selected": false,
"text": "void invest(Currency money){...}\n void invest(Euro money){...}\n public static void main(String args[]) {\n Bank myBank = new Bank();\n\n Euro capital = new Euro();\n myBank.invest(capital);\n}\n #7 = Methodref #2.#22 // Bank.invest:(LCurrency;)V\n"
},
{
"answer_id": 50558413,
"author": "Dave Inlow",
"author_id": 9856495,
"author_profile": "https://Stackoverflow.com/users/9856495",
"pm_score": 2,
"selected": false,
"text": "App/ \n src/\n com.example/ \n Projection.java\nTest/ \n src/\n com.example/\n Projection.java\n"
},
{
"answer_id": 55582143,
"author": "invzbl3",
"author_id": 8370915,
"author_profile": "https://Stackoverflow.com/users/8370915",
"pm_score": 3,
"selected": false,
"text": " Exception in thread \"main\" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V\n at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)\n at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)\n at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)\n at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)\n click in your POM the combination -> Ctrl+Alt+Shift+U right click in your POM -> Maven -> Show dependencies <jackson.version>2.8.7</jackson.version>\n <dependency>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n <version>${jackson.version}</version>\n</dependency>\n <dependency>\n <groupId>group-a</groupId>\n <artifactId>artifact-a</artifactId>\n <version>1.0</version>\n <exclusions>\n <exclusion>\n <groupId>com.fasterxml.jackson.core</groupId>\n <artifactId>jackson-databind</artifactId>\n </exclusion>\n </exclusions>\n </dependency>\n"
},
{
"answer_id": 56736243,
"author": "Gaurav Khare",
"author_id": 3662213,
"author_profile": "https://Stackoverflow.com/users/3662213",
"pm_score": 2,
"selected": false,
"text": "com.xyz.TestClass A B A B NoSuchMethodError"
},
{
"answer_id": 65420248,
"author": "Nachiket Doke",
"author_id": 5530721,
"author_profile": "https://Stackoverflow.com/users/5530721",
"pm_score": 1,
"selected": false,
"text": "NoSuchMethodError"
},
{
"answer_id": 66332755,
"author": "Cihat Özdenoğlu",
"author_id": 11190435,
"author_profile": "https://Stackoverflow.com/users/11190435",
"pm_score": 2,
"selected": false,
"text": "<plugin>\n<groupId>org.apache.maven.plugins</groupId>\n<artifactId>maven-enforcer-plugin</artifactId>\n<version>3.0.0-M3</version>\n<configuration>\n <rules>\n <dependencyConvergence />\n </rules>\n</configuration>\n</plugin>\n\n mvn enforcer:enforce\n"
},
{
"answer_id": 69387076,
"author": "Murat Yıldız",
"author_id": 1604048,
"author_profile": "https://Stackoverflow.com/users/1604048",
"pm_score": 0,
"selected": false,
"text": "mockito-core 3.3.3 3.4.3"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2343/"
] |
35,208 |
<p>I have a page with many forms in panels and usercontrols, and a requiredfield validator I just added to one form is preventing all of my other forms from submitting. what's the rule that I'm not following?</p>
|
[
{
"answer_id": 35226,
"author": "Jonathan S.",
"author_id": 2034,
"author_profile": "https://Stackoverflow.com/users/2034",
"pm_score": 4,
"selected": true,
"text": "<asp:TextBox ID=\"txt1\" ValidationGroup=\"Group1\" ruant=\"server\" />\n<asp:RequiredFieldValidator ID=\"rfv1\" ... ValidationGroup=\"Group1\" />\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
35,211 |
<p>The compiler usually chokes when an event doesn't appear beside a <code>+=</code> or a <code>-=</code>, so I'm not sure if this is possible.</p>
<p>I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:</p>
<pre><code>using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
// act here
} // throws on Dispose() if MyEventToWatch hasn't fired
</code></pre>
<p>My questions are twofold:</p>
<ol>
<li>Will the compiler choke? And if so, any suggestions on how to prevent this?</li>
<li>How can I parse the Expression object from the constructor in order to attach to the <code>MyEventToWatch</code> event of <code>target</code>?</li>
</ol>
|
[
{
"answer_id": 36255,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 2,
"selected": false,
"text": "public event DelegateType EventName;\n"
},
{
"answer_id": 37315,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 3,
"selected": true,
"text": "x => x.MyEvent ( x, h ) => x.MyEvent += h EventInfo EventInfo AddEventHandler RemoveEventHandler Delegate Combine Remove public sealed class EventWatcher : IDisposable {\n private readonly object target_;\n private readonly string eventName_;\n private readonly FieldInfo eventField_;\n private readonly Delegate listener_;\n private bool eventWasRaised_;\n\n public static EventWatcher Create<T>( T target, Expression<Func<T,Delegate>> accessor ) {\n return new EventWatcher( target, accessor );\n }\n\n private EventWatcher( object target, LambdaExpression accessor ) {\n this.target_ = target;\n\n // Retrieve event definition from expression.\n var eventAccessor = accessor.Body as MemberExpression;\n this.eventField_ = eventAccessor.Member as FieldInfo;\n this.eventName_ = this.eventField_.Name;\n\n // Create our event listener and add it to the declaring object's event field.\n this.listener_ = CreateEventListenerDelegate( this.eventField_.FieldType );\n var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n var newEventList = Delegate.Combine( currentEventList, this.listener_ );\n this.eventField_.SetValue( this.target_, newEventList );\n }\n\n public void SetEventWasRaised( ) {\n this.eventWasRaised_ = true;\n }\n\n private Delegate CreateEventListenerDelegate( Type eventType ) {\n // Create the event listener's body, setting the 'eventWasRaised_' field.\n var setMethod = typeof( EventWatcher ).GetMethod( \"SetEventWasRaised\" );\n var body = Expression.Call( Expression.Constant( this ), setMethod );\n\n // Get the event delegate's parameters from its 'Invoke' method.\n var invokeMethod = eventType.GetMethod( \"Invoke\" );\n var parameters = invokeMethod.GetParameters( )\n .Select( ( p ) => Expression.Parameter( p.ParameterType, p.Name ) );\n\n // Create the listener.\n var listener = Expression.Lambda( eventType, body, parameters );\n return listener.Compile( );\n }\n\n void IDisposable.Dispose( ) {\n // Remove the event listener.\n var currentEventList = this.eventField_.GetValue( this.target_ ) as Delegate;\n var newEventList = Delegate.Remove( currentEventList, this.listener_ );\n this.eventField_.SetValue( this.target_, newEventList );\n\n // Ensure event was raised.\n if( !this.eventWasRaised_ )\n throw new InvalidOperationException( \"Event was not raised: \" + this.eventName_ );\n }\n}\n try {\n using( EventWatcher.Create( o, x => x.MyEvent ) ) {\n //o.RaiseEvent( ); // Uncomment for test to succeed.\n }\n Console.WriteLine( \"Event raised successfully\" );\n}\ncatch( InvalidOperationException ex ) {\n Console.WriteLine( ex.Message );\n}\n"
},
{
"answer_id": 5521046,
"author": "bryanbcook",
"author_id": 30809,
"author_profile": "https://Stackoverflow.com/users/30809",
"pm_score": 1,
"selected": false,
"text": "public sealed class EventWatcher : IDisposable {\n private readonly object _target;\n private readonly EventInfo _eventInfo;\n private readonly Delegate _listener;\n private bool _eventWasRaised;\n\n public static EventWatcher Create<T>(T target, string eventName) {\n EventInfo eventInfo = typeof(T).GetEvent(eventName);\n if (eventInfo == null)\n throw new ArgumentException(\"Event was not found.\", eventName);\n return new EventWatcher(target, eventInfo);\n }\n\n private EventWatcher(object target, EventInfo eventInfo) {\n _target = target;\n _eventInfo = event;\n _listener = CreateEventDelegateForType(_eventInfo.EventHandlerType);\n _eventInfo.AddEventHandler(_target, _listener);\n }\n\n // SetEventWasRaised()\n // CreateEventDelegateForType\n\n void IDisposable.Dispose() {\n _eventInfo.RemoveEventHandler(_target, _listener);\n if (!_eventWasRaised)\n throw new InvalidOperationException(\"event was not raised.\");\n }\n}\n using(EventWatcher.Create(o, \"MyEvent\")) {\n o.RaiseEvent();\n}\n"
},
{
"answer_id": 11084822,
"author": "sacha barber",
"author_id": 1089655,
"author_profile": "https://Stackoverflow.com/users/1089655",
"pm_score": 2,
"selected": false,
"text": "+= -= MarshalByRefObject public interface ISomeClassWithEvent {\n event EventHandler<EventArgs> Changed;\n}\n\n\npublic class SomeClassWithEvent : ISomeClassWithEvent {\n public event EventHandler<EventArgs> Changed;\n\n protected virtual void OnChanged(EventArgs e) {\n if (Changed != null)\n Changed(this, e);\n }\n}\n Action<T> T public class EventWatcher<T> {\n public void WatchEvent(Action<T> eventToWatch) {\n CustomProxy<T> proxy = new CustomProxy<T>(InvocationType.Event);\n T tester = (T) proxy.GetTransparentProxy();\n eventToWatch(tester);\n\n Console.WriteLine(string.Format(\"Event to watch = {0}\", proxy.Invocations.First()));\n }\n}\n Action<T> CustomProxy<T> += -= public enum InvocationType { Event }\n\npublic class CustomProxy<T> : RealProxy {\n private List<string> invocations = new List<string>();\n private InvocationType invocationType;\n\n public CustomProxy(InvocationType invocationType) : base(typeof(T)) {\n this.invocations = new List<string>();\n this.invocationType = invocationType;\n }\n\n public List<string> Invocations {\n get { \n return invocations; \n }\n }\n\n [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.Infrastructure)]\n [DebuggerStepThrough]\n public override IMessage Invoke(IMessage msg) {\n String methodName = (String) msg.Properties[\"__MethodName\"];\n Type[] parameterTypes = (Type[]) msg.Properties[\"__MethodSignature\"];\n MethodBase method = typeof(T).GetMethod(methodName, parameterTypes);\n\n switch (invocationType) {\n case InvocationType.Event:\n invocations.Add(ReplaceAddRemovePrefixes(method.Name));\n break;\n // You could deal with other cases here if needed\n }\n\n IMethodCallMessage message = msg as IMethodCallMessage;\n Object response = null;\n ReturnMessage responseMessage = new ReturnMessage(response, null, 0, null, message);\n return responseMessage;\n }\n\n private string ReplaceAddRemovePrefixes(string method) {\n if (method.Contains(\"add_\"))\n return method.Replace(\"add_\",\"\");\n if (method.Contains(\"remove_\"))\n return method.Replace(\"remove_\",\"\");\n return method;\n }\n}\n class Program {\n static void Main(string[] args) {\n EventWatcher<ISomeClassWithEvent> eventWatcher = new EventWatcher<ISomeClassWithEvent>();\n eventWatcher.WatchEvent(x => x.Changed += null);\n eventWatcher.WatchEvent(x => x.Changed -= null);\n Console.ReadLine();\n }\n}\n Event to watch = Changed\nEvent to watch = Changed\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
35,224 |
<p>I have a Flex <code>ComboBox</code> that gets populated by a <code>dataprovider</code> all is well...</p>
<p>I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a <code>dataprovider</code>? I have not seen any examples of such, but I can't imagine this being hard...</p>
|
[
{
"answer_id": 35261,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 1,
"selected": false,
"text": "mx.BindingUtils.ChangeWatcher"
},
{
"answer_id": 35883,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "prompt ComboBox selectedIndex propmt"
},
{
"answer_id": 973049,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "var defaultOption:Object = {MyLabelField: \"Select One\"};\nmyDataProvider.addItemAt(defaultOption, 0);\nmyComboBox.selectedIndex = 0;\n <mx:ComboBox id=\"myComboBox\" dataProvider=\"{myDataProvider}\" labelField=\"MyLabelField\" />\n"
},
{
"answer_id": 19028864,
"author": "Nitin Karale",
"author_id": 2640991,
"author_profile": "https://Stackoverflow.com/users/2640991",
"pm_score": 0,
"selected": false,
"text": "var index:String = \"foo\";\nfor(var objIndex:int = 0; objIndex < comboBox.dataProvider.length; objIndex++) {\n if(comboBox.dataProvider[objIndex].label == index)\n {\n comboBox.selectedIndex = objIndex;\n break;\n }\n}\n<mx:ComboBox id=\"comboBox\" dataProvider=\"{_pageIndexArray}\" />\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
35,240 |
<p>I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.</p>
<p>I've tried poking around in the iframe objects looking for some sort of <code>status_code</code> attribute, but haven't been able to find anything like that.</p>
<hr>
<p>The <code>$.ajax()</code> function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden <code>iframe</code> method.</p>
|
[
{
"answer_id": 1847965,
"author": "Coyod",
"author_id": 223888,
"author_profile": "https://Stackoverflow.com/users/223888",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\n\n var uploadStarted = false;\n function OnUploadStart(){ \n uploadStarted = true;\n }\n\n function OnUploadComplete(state,message){ \n\n if(state == 1)\n alert(\"Success: \"+message); \n else\n if(state == 0 && uploadStarted)\n alert(\"Error:\"+( message ? message : \"unknow\" ));\n } \n\n</script>\n\n\n<iframe id=\"uploader\" name=\"uploader\" onload=\"OnUploadComplete(0)\" style=\"width:0px;height:0px;border:none;\"></iframe>\n\n<form id=\"sender\" action=\"/upload.php\" method=\"post\" target=\"uploader\" enctype=\"multipart/form-data\" onsubmit=\"OnUploadStart()\">\n<input type=\"file\" name=\"files[upload]\"/>\n<input type=\"submit\" value=\"Upload\"/>\n</form>\n /*\n file: upload.php\n*/\n<?php \n\n // do some stuff with file \n\n print '<script type=\"text/javascript\">';\n if(success)\n print 'window.parent.OnUploadComplete(1,\"File uploaded!\");';\n else\n print 'window.parent.OnUploadComplete(0, \"File too large!\");';\n print '</script>';\n?>\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3560/"
] |
35,286 |
<p>I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:</p>
<pre><code>set FILENAME=%~f1
sed 's/Some Pattern/%FILENAME%/' inputfile
</code></pre>
<p>(Note: <code>%~f1</code> - expands <code>%1</code> to a Fully qualified path name - <code>C:\utils\MyFile.txt</code>)</p>
<p>I found that the backslashes in <code>%FILENAME%</code> are just escaping the next letter.</p>
<p>How can I double them up so that they are escaped?</p>
<p>(I have cygwin installed so feel free to use any other *nix commands)</p>
<h1>Solution</h1>
<p>Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have</p>
<pre><code>set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
</code></pre>
|
[
{
"answer_id": 35386,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 3,
"selected": true,
"text": "Some Pattern set FILENAME=%~f1\necho s/Some Pattern/%FILENAME%/ | sed -e \"s/\\\\/\\\\\\\\/g\" >sedcmd.tmp\nsed -f sedcmd.tmp inputfile\ndel /q sedcmd.tmp\n"
},
{
"answer_id": 35389,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 2,
"selected": false,
"text": "> cygpath -m c:\\some\\path\nc:/some/path\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541/"
] |
35,301 |
<p>I have always used <code>||</code> (two pipes) in OR expressions, both in C# and PHP. Occasionally I see a single pipe used: <code>|</code>. What is the difference between those two usages? Are there any caveats when using one over the other or are they interchangeable?</p>
|
[
{
"answer_id": 35313,
"author": "Evan Shaw",
"author_id": 510,
"author_profile": "https://Stackoverflow.com/users/510",
"pm_score": 6,
"selected": false,
"text": "condition1 || condition2\n A = 01010101\nB = 10101010\nA | B = 11111111\n\nA = 00000001\nB = 00010000\nA | B = 00010001\n\nA = 10001011\nB = 00101100\n\nA | B = 10101111\n"
},
{
"answer_id": 35314,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 10,
"selected": true,
"text": "& && if(condition1 || condition2 || condition3)\n if(condition1 | condition2 | condition3)\n if(class != null && class.someVar < 20)\n class != null class.someVar NullReferenceException & | & | | &"
},
{
"answer_id": 35331,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 4,
"selected": false,
"text": "| File.Open(FileAccess.Read | FileAccess.Write); //Gives read/write access to the file\n || if(Name == \"Admin\" || Name == \"Developer\") { //allow access } //checks if name equals Admin OR Name equals Developer\n"
},
{
"answer_id": 9835789,
"author": "vishesh",
"author_id": 1219463,
"author_profile": "https://Stackoverflow.com/users/1219463",
"pm_score": 3,
"selected": false,
"text": "public class Driver {\n\n static int x;\n static int y;\n\npublic static void main(String[] args) \nthrows Exception {\n\nSystem.out.println(\"using double pipe\");\n if(setX() || setY())\n {System.out.println(\"x = \"+x);\n System.out.println(\"y = \"+y);\n }\n\n\n\nSystem.out.println(\"using single pipe\");\nif(setX() | setY())\n {System.out.println(\"x = \"+x);\n System.out.println(\"y = \"+y);\n }\n\n}\n\n static boolean setX(){\n x=5;\n return true;\n }\n static boolean setY(){\n y=5;\n return true;\n }\n}\n using double pipe\nx = 5\ny = 0\nusing single pipe\nx = 5\ny = 5\n"
},
{
"answer_id": 62966167,
"author": "RvSingh3213",
"author_id": 13728648,
"author_profile": "https://Stackoverflow.com/users/13728648",
"pm_score": -1,
"selected": false,
"text": "| || & && if( a>b | a==0) a>b a==0 | || if a>b if(A>0 & B>0) (A>0 && B>0) if(A>0) false return false;"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3238/"
] |
35,317 |
<p>When I log into a remote machine using ssh X11 forwarding, Vista pops up a box complaining about a process that died unexpectedly. Once I dismiss the box, everything is fine. So I really don't care if some process died. How do I get Vista to shut up about it?</p>
<hr>
<p>Specifically, the message reads:</p>
<pre><code>sh.exe has stopped working
</code></pre>
<p>So it's not ssh itself that died, but some sub-process.</p>
<p>The problem details textbox reads:</p>
<pre><code>Problem signature:
Problem Event Name: APPCRASH
Application Name: sh.exe
Application Version: 0.0.0.0
Application Timestamp: 48a031a1
Fault Module Name: comctl32.dll_unloaded
Fault Module Version: 0.0.0.0
Fault Module Timestamp: 4549bcb0
Exception Code: c0000005
Exception Offset: 73dc5b17
OS Version: 6.0.6000.2.0.0.768.3
Locale ID: 1033
Additional Information 1: fc4d
Additional Information 2: d203a7335117760e7b4d2cf9dc2925f9
Additional Information 3: 1bc1
Additional Information 4: 7bc0b00964c4a1bd48f87b2415df3372
Read our privacy statement:
http://go.microsoft.com/fwlink/?linkid=50163&clcid=0x0409
</code></pre>
<p>I notice the problem occurs when I use the <strong>-Y</strong> option to enable X11 forwarding in an X terminal under Vista.</p>
<p>The dialog box that pops up doesn't automatically gain focus, so pressing Enter serves no purpose. I have to wait for the box to appear, grab it with the mouse, and dismiss it. Even forcing the error to receive focus would be a step in the right direction.</p>
<hr>
<p>Per DrPizza I have sent an <a href="http://cygwin.com/ml/cygwin/2008-08/msg00880.html" rel="nofollow noreferrer">email</a> to the Cygwin mailing list. The trimmed down subject line represents my repeated attempts to bypass an over-aggressive spam filter and highlights the need for something like StackOverflow.</p>
|
[
{
"answer_id": 1203513,
"author": "Marsh Ray",
"author_id": 116270,
"author_profile": "https://Stackoverflow.com/users/116270",
"pm_score": 0,
"selected": false,
"text": "http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1438/"
] |
35,320 |
<p>In the code below I am using a recursive CTE(Common Table Expression) in SQL Server 2005 to try and find the top level parent of a basic hierarchical structure. The rule of this hierarchy is that every CustID has a ParentID and if the CustID has no parent then the ParentID = CustID and it is the highest level.</p>
<pre><code>DECLARE @LookupID int
--Our test value
SET @LookupID = 1
WITH cteLevelOne (ParentID, CustID) AS
(
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
WHERE a.CustID = @LookupID
UNION ALL
SELECT a.ParentID, a.CustID
FROM tblCustomer AS a
INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID
WHERE c.CustID <> a.CustomerID
)
</code></pre>
<p>So if tblCustomer looks like this: </p>
<pre><code>ParentID CustID
5 5
1 8
5 4
4 1
</code></pre>
<p>The result I get from the code above is: </p>
<pre><code>ParentID CustID
4 1
5 4
5 5
</code></pre>
<p>What I want is just the last row of that result: </p>
<pre><code>ParentID CustID
5 5
</code></pre>
<p>How do I just return the last record generated in the CTE (which would be highest level CustID)?</p>
<p>Also note that there are multiple unrelated CustID hierarchies in this table so I can't just do a SELECT * FROM tblCustomer WHERE ParentID = CustID. I can't order by ParentID or CustID because the ID number is not related to where it is in the hierarchy.</p>
|
[
{
"answer_id": 35425,
"author": "Trevor Abell",
"author_id": 2916,
"author_profile": "https://Stackoverflow.com/users/2916",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 1 FROM cteLevelOne ORDER BY CustID DESC\n"
},
{
"answer_id": 35557,
"author": "AlexCuse",
"author_id": 794,
"author_profile": "https://Stackoverflow.com/users/794",
"pm_score": 3,
"selected": true,
"text": "DECLARE @LookupID int\n\n--Our test value\nSET @LookupID = 1;\n\nWITH cteLevelOne (ParentID, CustID, Depth) AS\n(\n SELECT a.ParentID, a.CustID, 1\n FROM tblCustomer AS a\n WHERE a.CustID = @LookupID\n UNION ALL\n SELECT a.ParentID, a.CustID, c.Depth + 1\n FROM tblCustomer AS a\n INNER JOIN cteLevelOne AS c ON a.CustID = c.ParentID \n WHERE c.CustID <> a.CustID\n)\nselect * from CTELevelone where Depth = (select max(Depth) from CTELevelone)\n select top 1 * from CTELevelone order by Depth desc\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] |
35,322 |
<p>I'm writing an app using asp.net-mvc deploying to iis6. I'm using forms authentication. Usually when a user tries to access a resource without proper authorization I want them to be redirected to a login page. FormsAuth does this for me easy enough.</p>
<p>Problem: Now I have an action being accessed by a console app. Whats the quickest way to have this action respond w/ status 401 instead of redirecting the request to the login page? </p>
<p>I want the console app to be able to react to this 401 StatusCode instead of it being transparent. I'd also like to keep the default, redirect unauthorized requests to login page behavior.</p>
<p>Note: As a test I added this to my global.asax and it didn't bypass forms auth:</p>
<pre><code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpContext.Current.SkipAuthorization = true;
}
</code></pre>
<hr>
<p>@Dale and Andy</p>
<p>I'm using the AuthorizeAttributeFilter provided in MVC preview 4. This is returning an HttpUnauthorizedResult. This result is correctly setting the statusCode to 401. The problem, as i understand it, is that asp.net is intercepting the response (since its taged as a 401) and redirecting to the login page instead of just letting it go through. I want to bypass this interception for certain urls.</p>
|
[
{
"answer_id": 35341,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": -1,
"selected": false,
"text": "\n HttpContext.Current.Response.StatusCode = 401;\n"
},
{
"answer_id": 35352,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "public class FormsAuth : ActionFilterAttribute\n{\n public override void OnActionExecuting(FilterExecutingContext filterContext)\n {\n filterContext.HttpContext.Response.StatusCode = 401;\n filterContext.Cancel = true;\n }\n}\n"
},
{
"answer_id": 35518,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "Request.QueryString[\"ReturnUrl\"] != null Response.StatusCode = 401"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
35,333 |
<p>I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error </p>
<blockquote>
<p>error C2143: syntax error : missing ';' before 'type'</p>
</blockquote>
<p>on a line that calls for a simple struct </p>
<pre><code> struct foo test;
</code></pre>
<p>same goes for using the typedef of the struct.</p>
<blockquote>
<p>error C2275: 'FOO' : illegal use of this type as an expression</p>
</blockquote>
|
[
{
"answer_id": 35336,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "#include"
},
{
"answer_id": 35362,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "// This will define a typedef for S1, in both C and in C++\ntypedef struct {\n int data;\n int text;\n} S1;\n\n// This will define a typedef for S2 ONLY in C++, will create error in C.\nstruct S2 {\n int data;\n int text; \n};\n"
},
{
"answer_id": 35417,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "foo test;\n struct foo test;\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] |
35,366 |
<p>I'm working on a database for a small web app at my school using <code>SQL Server 2005</code>.<br>
I see a couple of schools of thought on the issue of <code>varchar</code> vs <code>nvarchar</code>:</p>
<ol>
<li>Use <code>varchar</code> unless you deal with a lot of internationalized data, then use <code>nvarchar</code>.</li>
<li>Just use <code>nvarchar</code> for everything.</li>
</ol>
<p>I'm beginning to see the merits of view 2. I know that nvarchar does take up twice as much space, but that isn't necessarily a huge deal since this is only going to store data for a few hundred students. To me it seems like it would be easiest not to worry about it and just allow everything to use nvarchar. Or is there something I'm missing?</p>
|
[
{
"answer_id": 5538424,
"author": "J.A",
"author_id": 691070,
"author_profile": "https://Stackoverflow.com/users/691070",
"pm_score": 3,
"selected": false,
"text": "nvarchar varchar nvarchar"
},
{
"answer_id": 15019201,
"author": "Kjetil Klaussen",
"author_id": 15599,
"author_profile": "https://Stackoverflow.com/users/15599",
"pm_score": 3,
"selected": false,
"text": "nvarchar varchar"
},
{
"answer_id": 32871477,
"author": "Solomon Rutzky",
"author_id": 577765,
"author_profile": "https://Stackoverflow.com/users/577765",
"pm_score": 5,
"selected": false,
"text": "NVARCHAR WHILE NVARCHAR VARCHAR INT TINYINT CHAR(2) CHAR(3) Latin1_General_100_BIN2 VARCHAR VARCHAR Latin1_General_100_BIN2 NVARCHAR NVARCHAR VARCHAR NVARCHAR NCHAR NVARCHAR NCHAR(1 - 4000) NVARCHAR(1 - 4000) NVARCHAR(MAX) XML VARBINARY(MAX) TEXT NTEXT VARCHAR NVARCHAR VARCHAR ...\n URLa VARCHAR(2048) NULL,\n URLu NVARCHAR(2048) NULL,\n URL AS (ISNULL(CONVERT(NVARCHAR([URLa])), [URLu])),\n CONSTRAINT [CK_TableName_OneUrlMax] CHECK (\n ([URLa] IS NOT NULL OR [URLu] IS NOT NULL)\n AND ([URLa] IS NULL OR [URLu] IS NULL))\n );\n [URL] NVARCHAR INSERT INTO TableName (..., URLa, URLu)\n VALUES (...,\n IIF (CONVERT(VARCHAR(2048), @URL) = @URL, @URL, NULL),\n IIF (CONVERT(VARCHAR(2048), @URL) <> @URL, NULL, @URL)\n );\n VARBINARY(MAX) COMPRESS DECOMPRESS VARCHAR CHAR"
},
{
"answer_id": 43376826,
"author": "ajeh",
"author_id": 2721750,
"author_profile": "https://Stackoverflow.com/users/2721750",
"pm_score": 1,
"selected": false,
"text": "NVARCHAR sp_executesql VARCHAR NVARCHAR NVARCHAR"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
35,372 |
<p>I am trying to build an website for my college's magazine. I used the "views" module to show a block of static content I created on the front page.</p>
<p>My question is: how can I edit the theme's css so it changes the way that block of static content is displayed?</p>
<p>For reference, <a href="http://www.historia.uff.br/aroda/" rel="noreferrer">here's the link</a> to the site (in portuguese, and with almost zero content for now).</p>
|
[
{
"answer_id": 36743,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 2,
"selected": false,
"text": "sites/all/ themes mytheme sites/all/themes/mytheme/ mytheme.info name = My Theme\nversion = 0.1\ncore = 6.x\nbase theme = garland\nstylesheets[all][] = mytheme.css\n mytheme.css"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/802/"
] |
35,380 |
<p>I need to to print natural nos. 1,2,...n such that the parent process prints all odd numbers and the child process prints all even numbers, and all of this needs to be done using POSIX signals. How would I go about accomplishing this?</p>
<p>The output should be:</p>
<p>Parent : 1<br>
Child : 2<br>
Parent : 3<br>
...</p>
|
[
{
"answer_id": 171502,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <signal.h>\n#include <stdlib.h>\n\n#define READY_SIGNAL SIGUSR1\n\n/* The ready flag is set when READY_SIGNAL is received.\n * It is needed so that when we wake up from sigsuspend\n * we know whether or not the signal received was READY_SIGNAL. */\nvolatile sig_atomic_t ready;\nvoid make_ready(int i) { ready = 1; }\n\nint\nmain (int argc, char *argv[])\n{\n pid_t cpid, ppid; /* pids of the child and parent */\n /* Signal masks for sigprocmask and sigsuspend */\n sigset_t block_mask, wait_mask;\n unsigned long c = 1; /* The counter */\n unsigned long n = 100; /* The default max count value */\n struct sigaction act;\n\n /* Override the default max count if provided */\n if (argv[1])\n n = strtoul(argv[1], NULL, 10);\n\n /* Prepare signal masks */\n sigemptyset(&wait_mask);\n sigemptyset(&block_mask);\n sigaddset(&block_mask, READY_SIGNAL);\n\n /* Set the signal mask for the parent to ignore READY_SIGNAL until\n * we are ready to receive it, the mask will be inherited by the child,\n * needed to avoid race conditions */\n sigprocmask(SIG_BLOCK, &block_mask, NULL);\n\n /* Register the signal handler, will be inherited by the child */\n act.sa_flags = 0;\n act.sa_handler = make_ready;\n sigemptyset(&act.sa_mask);\n sigaction(READY_SIGNAL, &act, NULL);\n\n /* Get the parent's process id, needed for the child to send signals\n * to the parent process, could alternatively use getppid in the child */\n ppid = getpid();\n\n /* Call fork, storing the child's process id needed for the parent to\n * send signals to the child */\n cpid = fork();\n\n if (cpid < 0) {\n perror(\"Fork failed\");\n exit(EXIT_FAILURE);\n }\n\n if (cpid == 0) {\n /* Child */\n c = 2; /* Child's first number will always be 2 */\n if (c > n) exit(0); /* If c > n we have nothing to do */\n\n do {\n /* Suspend until we receive READY_SIGNAL */\n while (!ready) sigsuspend(&wait_mask);\n\n /* Print out number, flush for proper output sequencing when output\n is not a terminal. */\n printf(\"Child: %lu\\n\", c);\n fflush(stdout);\n\n ready = 0; /* Reset ready flag */\n c += 2; /* Increment counter */\n\n /* Wake up parent process */\n kill(ppid, READY_SIGNAL);\n } while (c <= n); \n } else {\n /* Parent */\n for (;;) {\n /* Print out number, flush for proper output sequencing when output\n is not a terminal. */\n printf(\"Parent: %lu\\n\", c);\n fflush(stdout);\n\n c += 2; /* Increment counter */\n\n kill(cpid, READY_SIGNAL); /* Wake up child process */\n\n if (c > n) break; /* Don't go back to sleep if we are done */\n\n ready = 0; /* Reset ready flag */\n\n /* Suspend until we receive READY_SIGNAL */\n while (!ready) sigsuspend(&wait_mask);\n };\n\n wait4(cpid, NULL, 0); /* Don't exist before child finishes */\n }\n\n return 0;\n}\n ./print_with_signals 100000|sort -n -k 2 -c && echo \"Success\" ./print_with_signals 100001|sort -n -k 2 -c && echo \"Success\""
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2727/"
] |
35,429 |
<p>I was given a C++ project that was compiled using MS Visual Studio .net 2003 C++ compiler, and a .mak file that was used to compile it. I am able to build it from the command line using nmake project.mak, but the compiler complains that afxres.h was not found. I did a little searching around and the afxres.h is in the Visual Studio directory in an includes file. Where am I supposed to specify to nmake where to look for this header file?</p>
|
[
{
"answer_id": 35521,
"author": "Erin Dees",
"author_id": 3462,
"author_profile": "https://Stackoverflow.com/users/3462",
"pm_score": 2,
"selected": false,
"text": "vars C:\\Program Files\\Microsoft Visual Studio .NET 2003\\Common7\\Tools\\vsvars32.bat"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3690/"
] |
35,463 |
<p>Some code that rounds up the division to demonstrate (C-syntax):</p>
<pre><code>#define SINT64 long long int
#define SINT32 long int
SINT64 divRound(SINT64 dividend, SINT64 divisor)
{
SINT32 quotient1 = dividend / divisor;
SINT32 modResult = dividend % divisor;
SINT32 multResult = modResult * 2;
SINT32 quotient2 = multResult / divisor;
SINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. <code>divdi3()</code> for division). Chances are we link with <code>libgcc</code> without even knowing it. The problem is that Kernel-space is different (e.g. no <code>libgcc</code>). What to do?</p>
<p>Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:</p>
<pre><code>#define UINT64 long long int
#define UINT32 long int
UINT64 divRound(UINT64 dividend, UINT64 divisor)
{
UINT32 quotient1 = dividend / divisor;
UINT32 modResult = dividend % divisor;
UINT32 multResult = modResult * 2;
UINT32 quotient2 = multResult / divisor;
UINT64 result = quotient1 + quotient2;
return ( result );
}
</code></pre>
<p>I know how to fix this one: Override <code>udivdi3()</code> and <code>umoddi3()</code> with <code>do_div()</code> from <em>asm/div64.h</em>. Done right? Wrong. Signed is not the same as unsigned, <code>sdivdi3()</code> does not simply call <code>udivdi3()</code>, they are separate functions for a reason.</p>
<p>Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.</p>
<p>Thanks,
Chad</p>
|
[
{
"answer_id": 35468,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 0,
"selected": false,
"text": "ldiv"
},
{
"answer_id": 35472,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "sign(dividend) ^ sign(divisor) * / __divdi3 libgcc2.c"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
35,480 |
<p>I'm currently working on a large implementation of Class::DBI for an existing database structure, and am running into a problem with clearing the cache from Class::DBI. This is a mod_perl implementation, so an instance of a class can be quite old between times that it is accessed.
From the man pages I found two options:</p>
<pre><code>Music::DBI->clear_object_index();
</code></pre>
<p>And:</p>
<pre><code>Music::Artist->purge_object_index_every(2000);
</code></pre>
<p>Now, when I add clear_object_index() to the DESTROY method, it seems to run, but doesn't actually empty the cache. I am able to manually change the database, re-run the request, and it is still the old version.
purge_object_index_every says that it clears the index every n requests. Setting this to "1" or "0", seems to clear the index... sometimes. I'd expect one of those two to work, but for some reason it doesn't do it every time. More like 1 in 5 times.</p>
<p>Any suggestions for clearing this out?</p>
|
[
{
"answer_id": 35529,
"author": "John Siracusa",
"author_id": 164,
"author_profile": "https://Stackoverflow.com/users/164",
"pm_score": 4,
"selected": true,
"text": "$Class::DBI::Weaken_Is_Available = 0;\n"
},
{
"answer_id": 47599,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 2,
"selected": false,
"text": "Music::Artist->purge_object_index_every(2000);\n Music::DBI->clear_object_index();\n"
}
] |
2008/08/29
|
[
"https://Stackoverflow.com/questions/35480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3421/"
] |
35,485 |
<p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will objdump & readelf help?</p>
|
[
{
"answer_id": 35508,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "readelf -S .text .data .rodata"
},
{
"answer_id": 35738,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "$ size /bin/sh\n text data bss dec hex filename\n 712739 37524 21832 772095 bc7ff /bin/sh\n"
},
{
"answer_id": 47033,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "$ nm --size-sort /usr/bin/fld | tail -10\n000000ae T FontLoadFontx\n000000b0 T CodingByRegistry\n000000b1 t ShmFont\n000000ec t FontLoadw\n000000ef T LoadFontFile\n000000f6 T FontLoadDFontx\n00000108 D fSRegs\n00000170 T FontLoadMinix\n000001e7 T main\n00000508 T FontLoadBdf\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] |
35,486 |
<p>What is the best way to create fluid width/height rounded corners with jQuery?</p>
<hr>
<p>That plugin doesn't keep the height the same. I have a 10px high div that I want to round the corners on, when I use that script it adds about 10px onto whats there.</p>
|
[
{
"answer_id": 35510,
"author": "Martin Clarke",
"author_id": 2422,
"author_profile": "https://Stackoverflow.com/users/2422",
"pm_score": 4,
"selected": false,
"text": "$(this).corner();\n"
},
{
"answer_id": 676396,
"author": "Keyslinger",
"author_id": 80857,
"author_profile": "https://Stackoverflow.com/users/80857",
"pm_score": 3,
"selected": false,
"text": "/* Corner radius */\n.ui-corner-tl { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; }\n.ui-corner-tr { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }\n.ui-corner-bl { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }\n.ui-corner-br { -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }\n.ui-corner-top { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; }\n.ui-corner-bottom { -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }\n.ui-corner-right { -moz-border-radius-topright: 4px; -webkit-border-top-right-radius: 4px; -moz-border-radius-bottomright: 4px; -webkit-border-bottom-right-radius: 4px; }\n.ui-corner-left { -moz-border-radius-topleft: 4px; -webkit-border-top-left-radius: 4px; -moz-border-radius-bottomleft: 4px; -webkit-border-bottom-left-radius: 4px; }\n.ui-corner-all { -moz-border-radius: 4px; -webkit-border-radius: 4px; }\n $('#SomeElementID').addClass(\"ui-corner-all\");\n"
},
{
"answer_id": 1385095,
"author": "Thomas Maierhofer",
"author_id": 165958,
"author_profile": "https://Stackoverflow.com/users/165958",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function(){\n $(\".Test\").backgroundCanvas();\n});\n\nfunction DrawBackground() {\n $(\".Test\").backgroundCanvasPaint(TestBackgroundPaintFkt);\n}\n// Draw the background on load and resize\n$(window).load(function () { DrawBackground(); });\n$(window).resize(function() { DrawBackground(); });\n\nfunction TestBackgroundPaintFkt(context, width, height, elementInfo){\n var options = {x:0, height: height, width: width, radius:14, border: 0 };\n // Draw the red border rectangle\n context.fillStyle = \"#FF0000\";\n $.canvasPaint.roundedRect(context,options);\n // Draw the gradient filled inner rectangle\n var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 10);\n backgroundGradient.addColorStop(0 ,'#AAAAFF');\n backgroundGradient.addColorStop(1, '#AAFFAA');\n options.border = 5;\n context.fillStyle = backgroundGradient;\n $.canvasPaint.roundedRect(context,options);\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] |
35,491 |
<p>I want to be able to get an estimate of how much code & static data is used by my C++ program?</p>
<p>Is there a way to find this out by looking at the executable or object files? Or perhaps something I can do at runtime?</p>
<p>Will otool help?</p>
|
[
{
"answer_id": 35583,
"author": "Mike Haboustak",
"author_id": 2146,
"author_profile": "https://Stackoverflow.com/users/2146",
"pm_score": 2,
"selected": false,
"text": "otool -s __DATA __data MyApp.bundle/Contents/MacOS/MyApp\notool -s __TEXT __text MyApp.bundle/Contents/MacOS/MyApp\n"
},
{
"answer_id": 35694,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 4,
"selected": true,
"text": "$ size python\n__TEXT __DATA __OBJC others dec hex\n860160 159744 0 2453504 3473408 350000\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] |
35,494 |
<p>I'm looking to run Redmine, a Ruby on Rails app, on a VPS windows box. The only thing I can really think of is running a virtual Linux machine and hosting it from there. If that is my only option, am I going to run into problems running a virtual machine inside of a virtual machine?</p>
<p>Also, this will be an internal app, so performance isn't my number once concern.</p>
|
[
{
"answer_id": 35596,
"author": "cpm",
"author_id": 3674,
"author_profile": "https://Stackoverflow.com/users/3674",
"pm_score": 4,
"selected": true,
"text": "mongrel_rails service::install -h"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] |
35,499 |
<p>In the project I am currently working on, we have the need to develop a web chat application, not a very complex chat, just a way to connect two people to talk about a very specific topic, we don't need any kind of authentication for one of the two users, we don't have to support emoticons, avatars, or stuff like that.</p>
<p>Some project members suggested that we could use XMPP through BOSH, I said that is like trying to catch a fish with a boat's net, and proposed a simpler method, like a simple Ajax/MySQL web chat, but we're worried about the performance hit in the server because of the constant polling of many chats open at the same time.</p>
<p>Has anyone done something like this before? What would you recommend? </p>
|
[
{
"answer_id": 35587,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "function Comet(key) {\n\n var random = key;\n var title = 'Comet';\n var connection = false;\n var iframediv = false;\n var browserIsIE = /*@cc_on!@*/false;\n var blurStatus = false;\n var tmpframe = document.createElement('iframe');\n var nl = '\\r\\n';\n\n this.initialize = function() {\n if (browserIsIE) {\n connection = new ActiveXObject(\"htmlfile\");\n connection.open();\n connection.write(\"<html>\");\n connection.write(\"<script>document.domain = '\"+document.domain+\"'\");\n connection.write(\"</html>\");\n connection.close();\n iframediv = connection.createElement(\"div\");\n connection.appendChild(iframediv);\n connection.parentWindow.comet = comet;\n iframediv.innerHTML = \"<iframe id='comet_iframe' src='./comet.aspx?key=\"+random+\"'></iframe>\";\n } else {\n connection = document.createElement('iframe');\n connection.setAttribute('id', 'comet_iframe');\n iframediv = document.createElement('iframe');\n iframediv.setAttribute('src', './comet.aspx?key='+random);\n connection.appendChild(iframediv);\n document.body.appendChild(connection);\n }\n }\n\n // this function is called from the server to keep the connection alive\n this.keepAlive = function () {\n if (!browserIsIE) {\n mozillaHack();\n }\n }\n\n // this function is called from the server to update the client\n this.updateClient = function (value) {\n var outputDiv = document.getElementById('output');\n outputDiv.value = value + nl + outputDiv.value;\n if (blurStatus == true) {\n document.title = value;\n }\n if (!browserIsIE) {\n mozillaHack();\n }\n }\n\n this.onUnload = function() {\n if (connection) {\n // this will release the iframe to prevent problems with IE when reloading the page\n connection = false;\n }\n }\n\n this.toggleBlurStatus = function(bool) {\n blurStatus = bool;\n }\n\n this.resetTitle = function() {\n document.title = title;\n }\n\n function mozillaHack() {\n // this hack will fix the hour glass and loading status for Mozilla browsers\n document.body.appendChild(tmpframe);\n document.body.removeChild(tmpframe);\n }\n}\n"
},
{
"answer_id": 12430556,
"author": "Alain Tiemblo",
"author_id": 731138,
"author_profile": "https://Stackoverflow.com/users/731138",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n // For this demo\n if (file_exists('poll.txt') == false) {\n file_put_contents('poll.txt', '');\n }\n\n if (isset($_GET['poll'])) {\n\n // Don't forget to change the default time limit\n set_time_limit(120);\n\n date_default_timezone_set('Europe/Paris');\n $time = time();\n\n // We loop until you click on the \"release\" button...\n $poll = true;\n $number_of_tries = 1;\n while ($poll)\n {\n // Here we simulate a request (last mtime of file could be a creation/update_date field on a base)\n clearstatcache();\n $mtime = filemtime('poll.txt');\n\n if ($mtime > $time) {\n $result = htmlentities(file_get_contents('poll.txt'));\n $poll = false;\n }\n\n // Of course, else your polling will kill your resources!\n $number_of_tries++;\n sleep(1);\n }\n\n // Outputs result\n echo \"Number of tries : {$number_of_tries}<br/>{$result}\";\n die();\n }\n\n // Here we catch the release form\n if (isset($_GET['release']))\n {\n $data = '';\n if (isset($_GET['data'])) {\n $data = $_GET['data'];\n }\n file_put_contents('poll.txt', $data);\n die();\n }\n\n?>\n\n<!-- click this button to begin long-polling -->\n<input id=\"poll\" type=\"button\" value=\"Click me to start polling\" />\n\n<br/><br/>\n\nGive me some text here :\n<br/>\n<input id=\"data\" type=\"text\" />\n<br/>\n\n<!-- click this button to release long-polling -->\n<input id=\"release\" type=\"button\" value=\"Click me to release polling\" disabled=\"disabled\" />\n\n<br/><br/>\n\nResult after releasing polling :\n<div id=\"result\"></div>\n\n<script type=\"text/javascript\" src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js\"></script>\n<script type=\"text/javascript\">\n\n// Script to launch polling\n$('#poll').click(function() {\n $('#poll').attr('disabled', 'disabled');\n $('#release').removeAttr('disabled');\n $.ajax({\n url: 'poll.php',\n data: {\n poll: 'yes' // sets our $_GET['poll']\n },\n success: function(data) {\n $('#result').html(data);\n $('#poll').removeAttr('disabled');\n $('#release').attr('disabled', 'disabled');\n }\n });\n});\n\n// Script to release polling\n$('#release').click(function() {\n $.ajax({\n url: 'poll.php',\n data: {\n release: 'yes', // sets our $_GET['release']\n data: $('#data').val() // sets our $_GET['data']\n }\n });\n});\n\n</script>\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3695/"
] |
35,507 |
<p>I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.</p>
<p>I have all in default structure like: </p>
<pre>
application
|-- <i><b>META-INF</b></i> -- Some configs are here
|-- <i><b>WEB-INF</b></i> -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- <i><b>tpl</b></i> -- Template dir to be relocated
</pre>
<p>And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.</p>
<p>I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).</p>
<p>So, any lights on how to configure it ? </p>
<p>Thanks</p>
<hr>
<p>Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ?</p>
|
[
{
"answer_id": 197980,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "velocity.properties file.resource.loader.path"
},
{
"answer_id": 234746,
"author": "RayOK",
"author_id": 31246,
"author_profile": "https://Stackoverflow.com/users/31246",
"pm_score": 2,
"selected": true,
"text": "<servlet>\n <servlet-name>action</servlet-name>\n <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>\n <init-param>\n <param-name>config</param-name>\n <param-value>\n WEB-INF/config/struts-config.xml,\n WEB-INF/config/struts-config-stuff.xml,\n WEB-INF/config/struts-config-good.xml,\n WEB-INF/config/struts-config-bad.xml,\n WEB-INF/config/struts-config-ugly.xml\n </param-value>\n </init-param>\n ...\n</servlet>\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2274/"
] |
35,530 |
<p>Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter". Exactly what do these do, and what are the algorithms for implementing them?</p>
|
[
{
"answer_id": 82372,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 5,
"selected": false,
"text": "double[] signal = (some 1d signal);\ndouble[] filter = [0.25 0.25 0.25 0.25]; // box-car filter\ndouble[] result = new double[signal.Length + filter.Length + 1];\n\n// Set result to zero:\nfor (int i=0; i < result.Length; i++) result[i] = 0;\n\n// Do convolution:\nfor (int i=0; i < signal.Length; i++) \n for (int j=0; j < filter.Length; j++)\n result[i+j] = result[i+j] + signal[i] * filter[j];\n double[] signal = (some 1d signal);\n// Do FFT:\ndouble[] real;\ndouble[] imag;\n[real, imag] = fft(signal)\n\n// Set the first quarter of the real part to zero to attenuate the low frequencies\nfor (int i=0; i < real.Length / 4; i++) \n real[i] = 0;\n\n// Do inverse FFT:\ndouble[] highfrequencysignal = inversefft(real, imag);\n"
},
{
"answer_id": 4548775,
"author": "Eric Brotto",
"author_id": 385559,
"author_profile": "https://Stackoverflow.com/users/385559",
"pm_score": 3,
"selected": false,
"text": "float lopass(float input, float cutoff) {\n lo_pass_output= outputs[0]+ (cutoff*(input-outputs[0])); \noutputs[0]= lo_pass_output;\nreturn(lo_pass_output);\n}\n float hipass(float input, float cutoff) {\n hi_pass_output=input-(outputs[0] + cutoff*(input-outputs[0]));\n outputs[0]=hi_pass_output;\n return(hi_pass_output);\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
35,537 |
<p>Is there an easy way to set the zoom level for a windows form in C#? In VBA there was a zoom property of the form.</p>
|
[
{
"answer_id": 296054,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "float scaleX = ((float)Screen.PrimaryScreen.WorkingArea.Width / 1024);\nfloat scaleY = ((float)Screen.PrimaryScreen.WorkingArea.Height / 768);\nSizeF aSf = new SizeF(scaleX, scaleY);\nthis.Scale(aSf);\n AutoscaleMode = Font\nAutoSize = False\n"
},
{
"answer_id": 17108319,
"author": "Yuriy Grinevich",
"author_id": 2485960,
"author_profile": "https://Stackoverflow.com/users/2485960",
"pm_score": 2,
"selected": false,
"text": "public Form1()\n{\n InitializeComponent();\n\n AutoSize = false;\n AutoScaleMode = AutoScaleMode.Font;\n Font = new Font(\"Trebuchet MS\", \n 10.0f, \n FontStyle.Regular, \n GraphicsUnit.Point, \n ((byte)(204))\n );\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3270/"
] |
35,538 |
<p>What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.</p>
|
[
{
"answer_id": 35543,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "from lxml import etree\nfrom StringIO import StringIO\netree.parse(StringIO(html), etree.HTMLParser(recover=False))\n"
},
{
"answer_id": 35572,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 3,
"selected": false,
"text": ">>> import _elementtidy\n>>> xhtml, log = _elementtidy.fixup(\"<html></html>\")\n>>> print log\nline 1 column 1 - Warning: missing <!DOCTYPE> declaration\nline 1 column 7 - Warning: discarding unexpected </html>\nline 1 column 14 - Warning: inserting missing 'title' element\n"
},
{
"answer_id": 646877,
"author": "karlcow",
"author_id": 62262,
"author_profile": "https://Stackoverflow.com/users/62262",
"pm_score": 4,
"selected": false,
"text": "import httplib2\nimport time\n\nh = httplib2.Http(\".cache\")\n\nf = open(\"urllistfile.txt\", \"r\")\nurllist = f.readlines()\nf.close()\n\nfor url in urllist:\n # wait 10 seconds before the next request - be nice with the validator\n time.sleep(10)\n resp= {}\n url = url.strip()\n urlrequest = \"http://qa-dev.w3.org/wmvs/HEAD/check?doctype=HTML5&uri=\"+url\n try:\n resp, content = h.request(urlrequest, \"HEAD\")\n if resp['x-w3c-validator-status'] == \"Abort\":\n print url, \"FAIL\"\n else:\n print url, resp['x-w3c-validator-status'], resp['x-w3c-validator-errors'], resp['x-w3c-validator-warnings']\n except:\n pass\n"
},
{
"answer_id": 1279293,
"author": "Dave Brondsema",
"author_id": 79697,
"author_profile": "https://Stackoverflow.com/users/79697",
"pm_score": 5,
"selected": false,
"text": "from tidylib import tidy_document\ndocument, errors = tidy_document('''<p>fõo <img src=\"bar.jpg\">''',\n options={'numeric-entities':1})\nprint document\nprint errors\n"
},
{
"answer_id": 10519634,
"author": "Martin Hepp",
"author_id": 516699,
"author_profile": "https://Stackoverflow.com/users/516699",
"pm_score": 4,
"selected": false,
"text": "http://validator.w3.org/\n X-W3C-Validator-Recursion: 1\nX-W3C-Validator-Status: Invalid (or Valid)\nX-W3C-Validator-Errors: 6\nX-W3C-Validator-Warnings: 0\n curl -I \"http://validator.w3.org/check?uri=http%3A%2F%2Fwww.stalsoft.com\"\n HTTP/1.1 200 OK\nDate: Wed, 09 May 2012 15:23:58 GMT\nServer: Apache/2.2.9 (Debian) mod_python/3.3.1 Python/2.5.2\nContent-Language: en\nX-W3C-Validator-Recursion: 1\nX-W3C-Validator-Status: Invalid\nX-W3C-Validator-Errors: 6\nX-W3C-Validator-Warnings: 0\nContent-Type: text/html; charset=UTF-8\nVary: Accept-Encoding\nConnection: close\n # Programmatic XHTML Validations in Python\n# Martin Hepp and Alex Stolz\n# [email protected] / [email protected]\n\nimport urllib\nimport urllib2\n\nURL = \"http://validator.w3.org/check?uri=%s\"\nSITE_URL = \"http://www.heppnetz.de\"\n\n# pattern for HEAD request taken from \n# http://stackoverflow.com/questions/4421170/python-head-request-with-urllib2\n\nrequest = urllib2.Request(URL % urllib.quote(SITE_URL))\nrequest.get_method = lambda : 'HEAD'\nresponse = urllib2.urlopen(request)\n\nvalid = response.info().getheader('X-W3C-Validator-Status')\nif valid == \"Valid\":\n valid = True\nelse:\n valid = False\nerrors = int(response.info().getheader('X-W3C-Validator-Errors'))\nwarnings = int(response.info().getheader('X-W3C-Validator-Warnings'))\n\nprint \"Valid markup: %s (Errors: %i, Warnings: %i) \" % (valid, errors, warnings)\n"
},
{
"answer_id": 39336630,
"author": "user9869932",
"author_id": 1183098,
"author_profile": "https://Stackoverflow.com/users/1183098",
"pm_score": 2,
"selected": false,
"text": "requests r = requests.post('https://validator.w3.org/nu/', \n data=open('FILE.html','rb').read(), params={'out': 'json'}, \n headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', \n 'Content-Type': 'text/html; charset=UTF-8'})\n\nprint r.json()\n $ echo '<!doctype html><html lang=en><head><title>blah</title></head><body></body></html>' | tee FILE.html \n$ pip install requests\n\n$ python\nPython 2.7.12 (default, Jun 29 2016, 12:46:54)\n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\n>>> import requests\n\n>>> r = requests.post('https://validator.w3.org/nu/', \n... data=open('FILE.html', 'rb').read(), \n... params={'out': 'json'}, \n... headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36', \n... 'Content-Type': 'text/html; charset=UTF-8'})\n\n>>> r.text\n>>> u'{\"messages\":[]}\\n'\n\n>>> r.json()\n>>> {u'messages': []}\n"
},
{
"answer_id": 40229004,
"author": "speedplane",
"author_id": 234270,
"author_profile": "https://Stackoverflow.com/users/234270",
"pm_score": 2,
"selected": false,
"text": "_html_parser = None\ndef validate_html(html):\n global _html_parser\n from lxml import etree\n from StringIO import StringIO\n if not _html_parser:\n _html_parser = etree.HTMLParser(recover = False)\n return etree.parse(StringIO(html), _html_parser)\n validate_html(\"<a href='example.com'>foo\")\n> <lxml.etree._ElementTree at 0xb2fd888>\n validate_html(\"<a href='example.com'>foo</a\")\n> XMLSyntaxError: End tag : expected '>', line 1, column 29\n"
},
{
"answer_id": 60886392,
"author": "Changaco",
"author_id": 2729778,
"author_profile": "https://Stackoverflow.com/users/2729778",
"pm_score": 3,
"selected": false,
"text": ">>> import html5lib\n>>> html5parser = html5lib.HTMLParser(strict=True)\n>>> html5parser.parse('<html></html>')\nTraceback (most recent call last):\n ...\nhtml5lib.html5parser.ParseError: Unexpected start tag (html). Expected DOCTYPE.\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
35,541 |
<p>Doug McCune had created something that was exactly what I needed (<a href="http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/" rel="nofollow noreferrer">http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/</a>) but alas - it was for AIR beta 2. I just would like some tool that I can run that would provide some decent metrics...any idea's?</p>
|
[
{
"answer_id": 35552,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 0,
"selected": false,
"text": "find . -type f -exec cat {} \\; | wc -l"
},
{
"answer_id": 35787,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "find . -name '*.as' -or -name '*.mxml' | xargs wc -l\n wc -l **/*.{as,mxml}\n"
},
{
"answer_id": 38575,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/python\n\nimport sys, os, re\n\n# might want to improve on the regexes used here\ncodeElements = {\n'package':{\n 'regex':re.compile('^\\s*[(private|public|static)\\s]*package\\s+([A-Za-z0-9_.]+)\\s*', re.MULTILINE),\n 'numFound':0\n },\n'class':{\n 'regex':re.compile('^\\s*[(private|public|static|dynamic|final|internal|(\\[Bindable\\]))\\s]*class\\s', re.MULTILINE),\n 'numFound':0\n },\n'interface':{\n 'regex':re.compile('^\\s*[(private|public|static|dynamic|final|internal)\\s]*interface\\s', re.MULTILINE),\n 'numFound':0\n },\n'function':{\n 'regex':re.compile('^\\s*[(private|public|static|protected|internal|final|override)\\s]*function\\s', re.MULTILINE),\n 'numFound':0\n },\n'member variable':{\n 'regex':re.compile('^\\s*[(private|public|static|protected|internal|(\\[Bindable\\]))\\s]*var\\s+([A-Za-z0-9_]+)(\\s*\\\\:\\s*([A-Za-z0-9_]+))*\\s*', re.MULTILINE),\n 'numFound':0\n },\n'todo note':{\n 'regex':re.compile('[*\\s/][Tt][Oo]\\s?[Dd][Oo][\\s\\-:_/]', re.MULTILINE),\n 'numFound':0\n }\n}\ntotalLinesOfCode = 0\n\nfilePaths = []\nfor i in range(1,len(sys.argv)):\n if os.path.exists(sys.argv[i]):\n filePaths.append(sys.argv[i])\n\nfor filePath in filePaths:\n thisFile = open(filePath,'r')\n thisFileContents = thisFile.read()\n thisFile.close()\n totalLinesOfCode = totalLinesOfCode + len(thisFileContents.splitlines())\n for codeElementName in codeElements:\n matchSubStrList = codeElements[codeElementName]['regex'].findall(thisFileContents)\n codeElements[codeElementName]['numFound'] = codeElements[codeElementName]['numFound'] + len(matchSubStrList)\n\nfor codeElementName in codeElements:\n print str(codeElements[codeElementName]['numFound']) + ' instances of element \"'+codeElementName+'\" found'\nprint '---'\nprint str(totalLinesOfCode) + ' total lines of code'\nprint ''\n find /path/to/project/root/ -name \"*.as\" -or -name \"*.mxml\" | xargs /path/to/script\n 1589 instances of element \"function\" found\n147 instances of element \"package\" found\n58 instances of element \"todo note\" found\n13 instances of element \"interface\" found\n2033 instances of element \"member variable\" found\n156 instances of element \"class\" found\n---\n40822 total lines of code\n"
},
{
"answer_id": 2723668,
"author": "Delfeld",
"author_id": 327120,
"author_profile": "https://Stackoverflow.com/users/327120",
"pm_score": 1,
"selected": false,
"text": "REM =====================\n\necho off\n\ncls\n\nREM set variables\n\nset ASDir=C:\\root\\directory\\of\\your\\AS3\\code\\\n\nREM run the program\n\nREM See docs for different output formats.\n\ncloc-1.09.exe --by-file-by-lang --force-lang=\"ActionScript\",as --exclude_dir=.svn --ignored=ignoredFiles.txt --report-file=totalLOC.txt %ASDir% \n\nREM show the output\n\ntotalLOC.txt\n\nREM end\n\npause\n\nREM =====================\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
35,548 |
<p>I use this tool called <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a> which breaks a single C++ .lzz file into a .h and .cpp file. I want <a href="http://makepp.sourceforge.net/" rel="nofollow noreferrer">Makepp</a> to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line.</p>
|
[
{
"answer_id": 35592,
"author": "Tynan",
"author_id": 3548,
"author_profile": "https://Stackoverflow.com/users/3548",
"pm_score": 3,
"selected": true,
"text": "build: foo.h foo.cpp\n g++ $(CFLAGS) foo.cpp -o $(LFLAGS) foo\n\nfoo.h foo.cpp: foo.lzz\n lzz foo.lzz\n"
},
{
"answer_id": 2717514,
"author": "Daniel",
"author_id": 326407,
"author_profile": "https://Stackoverflow.com/users/326407",
"pm_score": 2,
"selected": false,
"text": "%.cpp %.h: %.lzz\n lzz $(input)\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
35,563 |
<p>Using Terminal.app on OS X 10.5, often you see the commands get garbled when you do a reverse-search with Bash. Is there some kind of termcap or perhaps a bash shopt command that can fix this? It is very annoying. </p>
<p>Steps to reproduce: Open Terminal.app, reverse-search to a longish command. Hit <ctrl>-E once you've found the command. The cursor goes to the end of the line, but the display doesn't update. </p>
<p>I'm guessing this is some kind of problem with the readline library on OS X. It's more of a problem with updating the cursor position after a search than anything else. Basically, ctrl-a and ctrl-e tend to break the search output. </p>
<p><a href="http://involution.com/images/osxterminal.png">os x terminal failure image http://involution.com/images/osxterminal.png</a></p>
<p>In the above, the first part of the command should be displayed, and the cursor should be at the end of the line, but it isn't. You literally can't see what you're editing when this happens. </p>
|
[
{
"answer_id": 35588,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "<down><up>"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] |
35,599 |
<p>I'll admit that I don't know the inner workings of the unix operating system, so I was hoping someone could shed some light on this topic.</p>
<p>Why is the Unix file system better than the windows file system?</p>
<p>Would grep work just as well on Windows, or is there something fundamentally different that makes it more powerful on a Unix box?</p>
<p>e.g. I have heard that in a Unix system, the number of files in a given directory will not slow file access, while on Windows direct file access will degrade as the # of files increase in the given folder, true?</p>
<p>Updates:
Brad, no such thing as the <a href="http://en.wikipedia.org/wiki/Unix_File_System" rel="noreferrer">unix file system</a>?</p>
|
[
{
"answer_id": 35616,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "unlink grep"
},
{
"answer_id": 10664449,
"author": "mtk",
"author_id": 1135954,
"author_profile": "https://Stackoverflow.com/users/1135954",
"pm_score": 1,
"selected": false,
"text": "Windows unix/linux"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1368/"
] |
35,634 |
<p>Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).</p>
|
[
{
"answer_id": 35635,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": true,
"text": "a.equal? b"
},
{
"answer_id": 39062,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 2,
"selected": false,
"text": "__id__ a.__id__ = b.__id__ group_by"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
35,670 |
<p>I am ready to start using SVN, but I have NO (as in the money required for free beer) experience with source control. I have installed subversion on my server (that was easy, 'apt-get install subversion') but now I don't know what to do, how to configure it, or how to use it.<br /><br />What suggestions do you have, and where can I find good resources to learn to start using it?<br /><br />
Update:<br />
O.K. So the feedback has been great and I have read through a bit of it but I want to clarify my question by saying that I am looking for more information on how to actually go about setting my up my repositories, clients, server, etc. I know that I could do a quick Google search and find dozens (or more) resources but I'm hoping that someone whom has experience with subversion and a client(I have installed tortoise) could suggest a good reference that will be reliable, and have quality content.</p>
|
[
{
"answer_id": 35676,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "svnserve mod_dav_svn"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
35,699 |
<p>I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one. My right div typically has a lot of content. </p>
<p>Here's a paired down example of my template to illustrate the problem.</p>
<pre><code><div style="float:left; width: 150px; border: 1px solid;">
<ul>
<li>nav1</li>
<li>nav2</li>
<li>nav3</li>
<li>nav4</li>
</ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>
</code></pre>
|
[
{
"answer_id": 35711,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 3,
"selected": false,
"text": "<div style=\"border-left:solid 1px black;border-bottom:solid 1px black;\">\n <div style=\"float:left; width: 150px; border-top: 1px solid;\">\n <ul>\n <li>nav1</li>\n <li>nav2</li>\n <li>nav3</li>\n <li>nav4</li>\n </ul>\n </div>\n <div style=\"float:left; width: 250px; border:solid 1px black;border-bottom:0;\">\n Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n sed do eiusmod tempor incididunt ut labore et dolore magna\n Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n ...\n </div>\n <div style=\"clear:both;\" ></div>\n</div>\n"
},
{
"answer_id": 53010,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 3,
"selected": false,
"text": "overflow: hidden <div id=\"wrapper\">\n <div id=\"col1\">Content</div>\n <div id=\"col2\">Longer Content</div>\n</div>\n\n#wrapper {\n overflow: hidden;\n}\n\n#col1, #col2 {\n padding-bottom: 9999px;\n margin-bottom: -9999px;\n}\n"
},
{
"answer_id": 396336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n<title>Untitled Document</title>\n<style type=\"text/css\">\n* {\n margin: 0;\n padding: 0;\n}\nbody {\n font-family: Arial, Helvetica, sans-serif;\n background: #87ceeb;\n font-size: 1.2em;\n}\n#container {\n width:100%; /* any width including 100% will work */\n color: inherit;\n margin:0 auto; /* remove if 100% width */\n background:#FFF;\n}\n#header {\n width: 100%;\n height: 160px;\n background: #1e90ff;\n}\n#content {/* use for left sidebar, menu etc. */\n background: #99C;\n color: #000;\n float: right;/* float left for right sidebar */\n margin: 0 0 0 -200px; /* adjust margin if borders added */\n width: 100%;\n }\n#content .wrapper {\n background: #FFF;\n margin: 0 0 0 200px;\n overflow: hidden;\n padding: 10px; /* optional, feel free to remove */\n}\n#sidebar {\n background: #99C;\n color: inherit;\n float: left;\n width: 180px;\n padding: 10px;\n}\n.clearer {\n height: 1px;\n font-size: -1px;\n clear: both;\n}\n\n/* content styles */\n#header h1 {\n padding: 0 0 0 5px;\n}\n#menu p {\n font-size: 1em;\n font-weight: bold;\n padding: 5px 0 5px 5px;\n}\n#footer {\n clear: both;\n border-top: 1px solid #1e90ff; \n border-bottom: 10px solid #1e90ff;\n text-align: center;\n font-size: 50%;\n font-weight: bold;\n}\n#footer p {\n padding: 10px 0;\n} \n</style>\n</head>\n\n<body>\n\n\n<div id=\"container\">\n<!--header and menu content goes here -->\n\n<div id=\"header\">\n<h1>Header Goes Here</h1>\n</div>\n<div id=\"content\">\n<div class=\"wrapper\">\n<!--main page content goes here -->\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus. Vivamus ut sem. Fusce aliquam nunc \n\nvitae purus. Aenean viverra malesuada libero. </p>\n</div>\n</div>\n\n<div id=\"sidebar\">\n<!--sidebar content, menu goes here -->\n<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis ligula lorem, consequat eget, tristique nec, auctor quis, purus.</p>\n</div>\n\n<div class=\"clearer\"></div><!--clears footer from content-->\n<!--footer content goes here -->\n<div id=\"footer\">\n<p>Footer Info Here</p>\n</div>\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 396350,
"author": "Burak Erdem",
"author_id": 49380,
"author_profile": "https://Stackoverflow.com/users/49380",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n// plugin\njQuery.fn.equalHeights=function() {\n var maxHeight=0;\n\n this.each(function(){\n if (this.offsetHeight>maxHeight) {maxHeight=this.offsetHeight;}\n });\n\n this.each(function(){\n $(this).height(maxHeight + \"px\");\n if (this.offsetHeight>maxHeight) {\n $(this).height((maxHeight-(this.offsetHeight-maxHeight))+\"px\");\n }\n });\n};\n\n// usage\n$(function() {\n $('.column1, .column2, .column3').equalHeights();\n});\n</script>\n"
},
{
"answer_id": 594021,
"author": "Stiropor",
"author_id": 67325,
"author_profile": "https://Stackoverflow.com/users/67325",
"pm_score": 0,
"selected": false,
"text": "var c = $(\"#center\");\nvar cp = parseInt(c.css(\"padding-top\"), 10) + parseInt(c.css(\"padding-bottom\"), 10) + parseInt(c.css(\"borderTopWidth\"), 10) + parseInt(c.css(\"borderBottomWidth\"), 10);\nvar r = $(\"#right\");\nvar rp = parseInt(r.css(\"padding-top\"), 10) + parseInt(r.css(\"padding-bottom\"), 10) + parseInt(r.css(\"borderTopWidth\"), 10) + parseInt(r.css(\"borderBottomWidth\"), 10);\n\nif (c.outerHeight() < r.outerHeight()) {\n c.height(r.height () + rp - cp);\n} else {\n r.height(c.height () + cp - rp);\n}\n"
},
{
"answer_id": 1842279,
"author": "cutcliffe",
"author_id": 224182,
"author_profile": "https://Stackoverflow.com/users/224182",
"pm_score": 3,
"selected": true,
"text": "function setHeight(){\n var height = $(document).height(); //optionally, subtract some from the height\n $(\"#leftDiv\").css(\"height\", height + \"px\");\n}\n"
},
{
"answer_id": 22628960,
"author": "Chandrakant Manekar",
"author_id": 3454979,
"author_profile": "https://Stackoverflow.com/users/3454979",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title>Untitled Document</title>\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\">\n</script>\n<script>\n $(document).ready(function () {\n var height = $(document).height(); //optionally, subtract some from the height\n $(\"#menu\").css(\"height\", (height) + \"px\");\n $(\"#content\").css(\"height\", (height) + \"px\");\n });\n</script>\n<style type=\"text/css\">\n <!--\n\n html, body {\n font-family: Arial;\n font-size: 12px;\n }\n\n\n #header {\n background-color: #F9C;\n height: 200px;\n width: 100%;\n float: left;\n position: relative;\n }\n\n #menu {\n background-color: #6CF;\n float: left;\n min-height: 100%;\n height: auto;\n width: 10%;\n position: relative;\n }\n\n #content {\n background-color: #6f6;\n float: right;\n height: auto;\n width: 90%;\n position: relative;\n }\n\n #footer {\n background-color: #996;\n float: left;\n height: 100px;\n width: 100%;\n position: relative;\n }\n -->\n</style>\n</head>\n\n\n<body>\n<div id=\"header\">\n i am a header\n</div>\n<div id=\"menu\">\n i am a menu\n</div>\n<div id=\"content\">\n I am an example of how to do layout with css rules and divs.\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n <p> I am an example of how to do layout with css rules and divs. </p>\n\n</div>\n<div id=\"footer\">\n footer\n</div>\n\n\n</body>\n</html>\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.