qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
14,464 |
<p>I have a structure which I need to populate and write to disk (several actually).</p>
<p>An example is:</p>
<pre><code>byte-6
bit0 - original_or_copy
bit1 - copyright
bit2 - data_alignment_indicator
bit3 - PES_priority
bit4-bit5 - PES_scrambling control.
bit6-bit7 - reserved
</code></pre>
<p>In C I might do something like the following:</p>
<pre><code>struct PESHeader {
unsigned reserved:2;
unsigned scrambling_control:2;
unsigned priority:1;
unsigned data_alignment_indicator:1;
unsigned copyright:1;
unsigned original_or_copy:1;
};
</code></pre>
<p>Is there any way to do this in C# that would enable me to access the bits using the struct dereferencing dot operator? </p>
<p>For a couple of structures, I can just do bit shifting wrapped in an accessor function.</p>
<p>I have loads of structures to handle in this way, so I'm looking for something that's easier to read and quicker to write.</p>
|
[
{
"answer_id": 14475,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "[StructLayout(LayoutKind.Explicit, Size=1, CharSet=CharSet.Ansi)]\npublic struct Foo \n{ [FieldOffset(0)]public byte original_or_copy; \n [FieldOffset(0)]public byte copyright;\n [FieldOffset(0)]public byte data_alignment_indicator; \n [FieldOffset(0)]public byte PES_priority; \n [FieldOffset(0)]public byte PES_scrambling_control; \n [FieldOffset(0)]public byte reserved; \n}\n const byte _original_or_copy = 1;\nconst byte _copyright = 2;\n\n//bool ooo = foo.original_or_copy();\nstatic bool original_or_copy(this Foo foo) \n{ return (foo.original_or_copy & _original_or_copy) == original_or_copy;\n} \n"
},
{
"answer_id": 14517,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "[Flags]\npublic enum PESHeaderFlags\n{\n IsCopy = 1, // implied that if not present, then it is an original\n IsCopyrighted = 2,\n IsDataAligned = 4,\n Priority = 8,\n ScramblingControlType1 = 0,\n ScramblingControlType2 = 16,\n ScramblingControlType3 = 32,\n ScramblingControlType4 = 16+32,\n ScramblingControlFlags = ScramblingControlType1 | ScramblingControlType2 | ... ype4\n etc.\n}\n"
},
{
"answer_id": 14540,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "[Flags] enum PesHeaders : byte { /* ... */ }\n"
},
{
"answer_id": 14591,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 7,
"selected": true,
"text": "using System;\n\nnamespace BitfieldTest\n{\n [global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\n sealed class BitfieldLengthAttribute : Attribute\n {\n uint length;\n\n public BitfieldLengthAttribute(uint length)\n {\n this.length = length;\n }\n\n public uint Length { get { return length; } }\n }\n\n static class PrimitiveConversion\n {\n public static long ToLong<T>(T t) where T : struct\n {\n long r = 0;\n int offset = 0;\n\n // For every field suitably attributed with a BitfieldLength\n foreach (System.Reflection.FieldInfo f in t.GetType().GetFields())\n {\n object[] attrs = f.GetCustomAttributes(typeof(BitfieldLengthAttribute), false);\n if (attrs.Length == 1)\n {\n uint fieldLength = ((BitfieldLengthAttribute)attrs[0]).Length;\n\n // Calculate a bitmask of the desired length\n long mask = 0;\n for (int i = 0; i < fieldLength; i++)\n mask |= 1 << i;\n\n r |= ((UInt32)f.GetValue(t) & mask) << offset;\n\n offset += (int)fieldLength;\n }\n }\n\n return r;\n }\n }\n\n struct PESHeader\n {\n [BitfieldLength(2)]\n public uint reserved;\n [BitfieldLength(2)]\n public uint scrambling_control;\n [BitfieldLength(1)]\n public uint priority;\n [BitfieldLength(1)]\n public uint data_alignment_indicator;\n [BitfieldLength(1)]\n public uint copyright;\n [BitfieldLength(1)]\n public uint original_or_copy;\n };\n\n public class MainClass\n {\n public static void Main(string[] args)\n {\n PESHeader p = new PESHeader();\n\n p.reserved = 3;\n p.scrambling_control = 2;\n p.data_alignment_indicator = 1;\n\n long l = PrimitiveConversion.ToLong(p);\n\n\n for (int i = 63; i >= 0; i--)\n {\n Console.Write( ((l & (1l << i)) > 0) ? \"1\" : \"0\");\n }\n\n Console.WriteLine();\n\n return;\n }\n }\n}\n"
},
{
"answer_id": 5420979,
"author": "Conrad",
"author_id": 610090,
"author_profile": "https://Stackoverflow.com/users/610090",
"pm_score": 3,
"selected": false,
"text": "BitArray []"
},
{
"answer_id": 7636680,
"author": "Christophe Lambrechts",
"author_id": 976896,
"author_profile": "https://Stackoverflow.com/users/976896",
"pm_score": 3,
"selected": false,
"text": "BitVector32 Section struct"
},
{
"answer_id": 11145067,
"author": "Zbyl",
"author_id": 407758,
"author_profile": "https://Stackoverflow.com/users/407758",
"pm_score": 4,
"selected": false,
"text": "public struct rcSpan\n{\n //C# Spec 10.4.5.1: The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration.\n internal static readonly BitVector32.Section sminSection = BitVector32.CreateSection(0x1FFF);\n internal static readonly BitVector32.Section smaxSection = BitVector32.CreateSection(0x1FFF, sminSection);\n internal static readonly BitVector32.Section areaSection = BitVector32.CreateSection(0x3F, smaxSection);\n\n internal BitVector32 data;\n\n //public uint smin : 13; \n public uint smin\n {\n get { return (uint)data[sminSection]; }\n set { data[sminSection] = (int)value; }\n }\n\n //public uint smax : 13; \n public uint smax\n {\n get { return (uint)data[smaxSection]; }\n set { data[smaxSection] = (int)value; }\n }\n\n //public uint area : 6; \n public uint area\n {\n get { return (uint)data[areaSection]; }\n set { data[areaSection] = (int)value; }\n }\n}\n public struct rcSpan2\n{\n internal uint data;\n\n //public uint smin : 13; \n public uint smin\n {\n get { return data & 0x1FFF; }\n set { data = (data & ~0x1FFFu ) | (value & 0x1FFF); }\n }\n\n //public uint smax : 13; \n public uint smax\n {\n get { return (data >> 13) & 0x1FFF; }\n set { data = (data & ~(0x1FFFu << 13)) | (value & 0x1FFF) << 13; }\n }\n\n //public uint area : 6; \n public uint area\n {\n get { return (data >> 26) & 0x3F; }\n set { data = (data & ~(0x3F << 26)) | (value & 0x3F) << 26; }\n }\n}\n"
},
{
"answer_id": 29326393,
"author": "SunsetQuest",
"author_id": 2352507,
"author_profile": "https://Stackoverflow.com/users/2352507",
"pm_score": 4,
"selected": false,
"text": "public struct MyStruct\n{\n internal uint raw;\n\n const int sz0 = 4, loc0 = 0, mask0 = ((1 << sz0) - 1) << loc0;\n const int sz1 = 4, loc1 = loc0 + sz0, mask1 = ((1 << sz1) - 1) << loc1;\n const int sz2 = 4, loc2 = loc1 + sz1, mask2 = ((1 << sz2) - 1) << loc2;\n const int sz3 = 4, loc3 = loc2 + sz2, mask3 = ((1 << sz3) - 1) << loc3;\n\n public uint Item0\n {\n get { return (uint)(raw & mask0) >> loc0; }\n set { raw = (uint)(raw & ~mask0 | (value << loc0) & mask0); }\n }\n\n public uint Item1\n {\n get { return (uint)(raw & mask1) >> loc1; }\n set { raw = (uint)(raw & ~mask1 | (value << loc1) & mask1); }\n }\n\n public uint Item2\n {\n get { return (uint)(raw & mask2) >> loc2; }\n set { raw = (uint)(raw & ~mask2 | (value << loc2) & mask2); }\n }\n\n public uint Item3\n {\n get { return (uint)((raw & mask3) >> loc3); }\n set { raw = (uint)(raw & ~mask3 | (value << loc3) & mask3); }\n }\n}\n"
},
{
"answer_id": 38189258,
"author": "stalendp",
"author_id": 6053477,
"author_profile": "https://Stackoverflow.com/users/6053477",
"pm_score": 2,
"selected": false,
"text": "[global::System.AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]\npublic sealed class BitInfoAttribute : Attribute {\n byte length;\n public BitInfoAttribute(byte length) {\n this.length = length;\n }\n public byte Length { get { return length; } }\n}\n\npublic abstract class BitField {\n\n public void parse<T>(T[] vals) {\n analysis().parse(this, ArrayConverter.convert<T, uint>(vals));\n }\n\n public byte[] toArray() {\n return ArrayConverter.convert<uint, byte>(analysis().toArray(this));\n }\n\n public T[] toArray<T>() {\n return ArrayConverter.convert<uint, T>(analysis().toArray(this));\n }\n\n static Dictionary<Type, BitTypeInfo> bitInfoMap = new Dictionary<Type, BitTypeInfo>();\n private BitTypeInfo analysis() {\n Type type = this.GetType();\n if (!bitInfoMap.ContainsKey(type)) {\n List<BitInfo> infos = new List<BitInfo>();\n\n byte dataIdx = 0, offset = 0;\n foreach (System.Reflection.FieldInfo f in type.GetFields()) {\n object[] attrs = f.GetCustomAttributes(typeof(BitInfoAttribute), false);\n if (attrs.Length == 1) {\n byte bitLen = ((BitInfoAttribute)attrs[0]).Length;\n if (offset + bitLen > 32) {\n dataIdx++;\n offset = 0;\n }\n infos.Add(new BitInfo(f, bitLen, dataIdx, offset));\n offset += bitLen;\n }\n }\n bitInfoMap.Add(type, new BitTypeInfo(dataIdx + 1, infos.ToArray()));\n }\n return bitInfoMap[type];\n }\n}\n\nclass BitTypeInfo {\n public int dataLen { get; private set; }\n public BitInfo[] bitInfos { get; private set; }\n\n public BitTypeInfo(int _dataLen, BitInfo[] _bitInfos) {\n dataLen = _dataLen;\n bitInfos = _bitInfos;\n }\n\n public uint[] toArray<T>(T obj) {\n uint[] datas = new uint[dataLen];\n foreach (BitInfo bif in bitInfos) {\n bif.encode(obj, datas);\n }\n return datas;\n }\n\n public void parse<T>(T obj, uint[] vals) {\n foreach (BitInfo bif in bitInfos) {\n bif.decode(obj, vals);\n }\n }\n}\n\nclass BitInfo {\n\n private System.Reflection.FieldInfo field;\n private uint mask;\n private byte idx, offset, shiftA, shiftB;\n private bool isUnsigned = false;\n\n public BitInfo(System.Reflection.FieldInfo _field, byte _bitLen, byte _idx, byte _offset) {\n field = _field;\n mask = (uint)(((1 << _bitLen) - 1) << _offset);\n idx = _idx;\n offset = _offset;\n shiftA = (byte)(32 - _offset - _bitLen);\n shiftB = (byte)(32 - _bitLen);\n\n if (_field.FieldType == typeof(bool)\n || _field.FieldType == typeof(byte)\n || _field.FieldType == typeof(char)\n || _field.FieldType == typeof(uint)\n || _field.FieldType == typeof(ulong)\n || _field.FieldType == typeof(ushort)) {\n isUnsigned = true;\n }\n }\n\n public void encode(Object obj, uint[] datas) {\n if (isUnsigned) {\n uint val = (uint)Convert.ChangeType(field.GetValue(obj), typeof(uint));\n datas[idx] |= ((uint)(val << offset) & mask);\n } else {\n int val = (int)Convert.ChangeType(field.GetValue(obj), typeof(int));\n datas[idx] |= ((uint)(val << offset) & mask);\n }\n }\n\n public void decode(Object obj, uint[] datas) {\n if (isUnsigned) {\n field.SetValue(obj, Convert.ChangeType((((uint)(datas[idx] & mask)) << shiftA) >> shiftB, field.FieldType));\n } else {\n field.SetValue(obj, Convert.ChangeType((((int)(datas[idx] & mask)) << shiftA) >> shiftB, field.FieldType));\n }\n }\n}\n\npublic class ArrayConverter {\n public static T[] convert<T>(uint[] val) {\n return convert<uint, T>(val);\n }\n\n public static T1[] convert<T0, T1>(T0[] val) {\n T1[] rt = null;\n // type is same or length is same\n // refer to http://stackoverflow.com/questions/25759878/convert-byte-to-sbyte\n if (typeof(T0) == typeof(T1)) { \n rt = (T1[])(Array)val;\n } else {\n int len = Buffer.ByteLength(val);\n int w = typeWidth<T1>();\n if (w == 1) { // bool\n rt = new T1[len * 8];\n } else if (w == 8) {\n rt = new T1[len];\n } else { // w > 8\n int nn = w / 8;\n int len2 = (len / nn) + ((len % nn) > 0 ? 1 : 0);\n rt = new T1[len2];\n }\n\n Buffer.BlockCopy(val, 0, rt, 0, len);\n }\n return rt;\n }\n\n public static string toBinary<T>(T[] vals) {\n StringBuilder sb = new StringBuilder();\n int width = typeWidth<T>();\n int len = Buffer.ByteLength(vals);\n for (int i = len-1; i >=0; i--) {\n sb.Append(Convert.ToString(Buffer.GetByte(vals, i), 2).PadLeft(8, '0')).Append(\" \");\n }\n return sb.ToString();\n }\n\n private static int typeWidth<T>() {\n int rt = 0;\n if (typeof(T) == typeof(bool)) { // x\n rt = 1;\n } else if (typeof(T) == typeof(byte)) { // x\n rt = 8;\n } else if (typeof(T) == typeof(sbyte)) {\n rt = 8;\n } else if (typeof(T) == typeof(ushort)) { // x\n rt = 16;\n } else if (typeof(T) == typeof(short)) {\n rt = 16;\n } else if (typeof(T) == typeof(char)) {\n rt = 16;\n } else if (typeof(T) == typeof(uint)) { // x\n rt = 32;\n } else if (typeof(T) == typeof(int)) {\n rt = 32;\n } else if (typeof(T) == typeof(float)) {\n rt = 32;\n } else if (typeof(T) == typeof(ulong)) { // x\n rt = 64;\n } else if (typeof(T) == typeof(long)) {\n rt = 64;\n } else if (typeof(T) == typeof(double)) {\n rt = 64;\n } else {\n throw new Exception(\"Unsupport type : \" + typeof(T).Name);\n }\n return rt;\n }\n}\n class MyTest01 : BitField {\n [BitInfo(3)]\n public bool d0;\n [BitInfo(3)]\n public short d1;\n [BitInfo(3)]\n public int d2;\n [BitInfo(3)]\n public int d3;\n [BitInfo(3)]\n public int d4;\n [BitInfo(3)]\n public int d5;\n\n public MyTest01(bool _d0, short _d1, int _d2, int _d3, int _d4, int _d5) {\n d0 = _d0;\n d1 = _d1;\n d2 = _d2;\n d3 = _d3;\n d4 = _d4;\n d5 = _d5;\n }\n\n public MyTest01(byte[] datas) {\n parse(datas);\n }\n\n public new string ToString() {\n return string.Format(\"d0: {0}, d1: {1}, d2: {2}, d3: {3}, d4: {4}, d5: {5} \\r\\nbinary => {6}\",\n d0, d1, d2, d3, d4, d5, ArrayConverter.toBinary(toArray()));\n }\n};\n\nclass MyTest02 : BitField {\n [BitInfo(5)]\n public bool val0;\n [BitInfo(5)]\n public byte val1;\n [BitInfo(15)]\n public uint val2;\n [BitInfo(15)]\n public float val3;\n [BitInfo(15)]\n public int val4;\n [BitInfo(15)]\n public int val5;\n [BitInfo(15)]\n public int val6;\n\n public MyTest02(bool v0, byte v1, uint v2, float v3, int v4, int v5, int v6) {\n val0 = v0;\n val1 = v1;\n val2 = v2;\n val3 = v3;\n val4 = v4;\n val5 = v5;\n val6 = v6;\n }\n\n public MyTest02(byte[] datas) {\n parse(datas);\n }\n\n public new string ToString() {\n return string.Format(\"val0: {0}, val1: {1}, val2: {2}, val3: {3}, val4: {4}, val5: {5}, val6: {6}\\r\\nbinary => {7}\",\n val0, val1, val2, val3, val4, val5, val6, ArrayConverter.toBinary(toArray()));\n }\n}\n\npublic class MainClass {\n\n public static void Main(string[] args) {\n MyTest01 p = new MyTest01(false, 1, 2, 3, -1, -2);\n Debug.Log(\"P:: \" + p.ToString());\n MyTest01 p2 = new MyTest01(p.toArray());\n Debug.Log(\"P2:: \" + p2.ToString());\n\n MyTest02 t = new MyTest02(true, 1, 12, -1.3f, 4, -5, 100);\n Debug.Log(\"t:: \" + t.ToString());\n MyTest02 t2 = new MyTest02(t.toArray());\n Debug.Log(\"t:: \" + t.ToString());\n\n Console.Read();\n return;\n }\n}\n"
},
{
"answer_id": 55834344,
"author": "Vito Marolda",
"author_id": 6681740,
"author_profile": "https://Stackoverflow.com/users/6681740",
"pm_score": 3,
"selected": false,
"text": "uint SetBits(uint word, uint value, int pos, int size)\n{\n uint mask = ((((uint)1) << size) - 1) << pos;\n word &= ~mask; //resettiamo le posizioni\n word |= (value << pos) & mask;\n return word;\n}\n\nuint ReadBits(uint word, int pos, int size)\n{\n uint mask = ((((uint)1) << size) - 1) << pos;\n return (word & mask) >> pos;\n}\n uint the_word;\n\npublic uint Itemx\n{\n get { return ReadBits(the_word, 5, 2); }\n set { the_word = SetBits(the_word, value, 5, 2) }\n}\n"
},
{
"answer_id": 68870859,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 0,
"selected": false,
"text": "=== BitFields.tt ===\n\n<#@ template language=\"C#\" #>\n<#@ assembly name=\"System.Core\" #>\n<#@ import namespace=\"System.Linq\" #>\n\n<#\nvar bitFields = new[]\n{\n new\n {\n Name = \"rcSpan2\", Fields = new[] { (\"smin\", 13), (\"smax\", 13), (\"area\", 6) },\n }, \n};\n\nforeach (var bitField in bitFields)\n{\n static string getType(int size) =>\n size switch\n {\n > 32 => \"ulong\",\n > 16 => \"uint\",\n > 8 => \"ushort\",\n _ => \"byte\",\n };\n\n var bitFieldType = getType(bitField.Fields.Sum(f => f.Item2)); \n#>\npublic struct <#=bitField.Name#>\n{\n <#=bitFieldType#> _bitfield;\n\n<#\nvar offset = 0;\nforeach (var (fieldName, fieldSize) in bitField.Fields)\n{\n var fieldType = getType(fieldSize);\n var fieldMask = $\"0x{((1UL<<fieldSize)-1):X}U\";\n#>\n public <#=fieldType#> <#=fieldName#> // : <#=fieldSize#>\n {\n get => (<#=fieldType#>)(<#=offset > 0 ? $\"(_bitfield >> {offset})\" : \"_bitfield\"#> & <#=fieldMask#>);\n set => _bitfield = (<#=bitFieldType#>)((_bitfield & ~((<#=bitFieldType#>)<#=fieldMask#> << <#=offset#>)) | ((<#=bitFieldType#>)(value & <#=fieldMask#>) << <#=offset#>));\n } \n<#\n offset += fieldSize;\n}\n#>\n}\n\n<#}#>\n\n=== BitFields.cs === (generated)\n\npublic struct rcSpan2\n{\n uint _bitfield;\n\n public ushort smin // : 13\n {\n get => (ushort)(_bitfield & 0x1FFFU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x1FFFU << 0)) | ((uint)(value & 0x1FFFU) << 0));\n } \n public ushort smax // : 13\n {\n get => (ushort)((_bitfield >> 13) & 0x1FFFU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x1FFFU << 13)) | ((uint)(value & 0x1FFFU) << 13));\n } \n public byte area // : 6\n {\n get => (byte)((_bitfield >> 26) & 0x3FU);\n set => _bitfield = (uint)((_bitfield & ~((uint)0x3FU << 26)) | ((uint)(value & 0x3FU) << 26));\n } \n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1006/"
] |
14,491 |
<p>What is the proper way for an MFC application to cleanly close itself?</p>
|
[
{
"answer_id": 14492,
"author": "Mike",
"author_id": 1743,
"author_profile": "https://Stackoverflow.com/users/1743",
"pm_score": 4,
"selected": false,
"text": "AfxGetMainWnd()->PostMessage(WM_CLOSE);\n"
},
{
"answer_id": 14841,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "PostQuitMessage( [exit code] );\n"
},
{
"answer_id": 8768957,
"author": "Bruno Schwarzkorpf",
"author_id": 1115458,
"author_profile": "https://Stackoverflow.com/users/1115458",
"pm_score": 5,
"selected": true,
"text": " void ExitMFCApp()\n {\n // same as double-clicking on main window close box\n ASSERT(AfxGetMainWnd() != NULL);\n AfxGetMainWnd()->SendMessage(WM_CLOSE);\n }\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743/"
] |
14,504 |
<p>I would really like to see a proportional font IDE, even if I have to build it myself (perhaps as an extension to Visual Studio). What I basically mean is MS Word style editing of code that sort of looks like the typographical style in <a href="http://www.research.att.com/~bs/3rd.html" rel="nofollow noreferrer">The C++ Programming Language book</a>.</p>
<p>I want to set tab stops for my indents and lining up function signatures and rows of assignment statements, which could be specified in points instead of fixed character positions. I would also like bold and italics. Various font sizes and even style sheets would be cool.</p>
<p>Has anyone seen anything like this out there or know the best way to start building one?</p>
|
[
{
"answer_id": 14583,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 1,
"selected": false,
"text": "int var1 = 1 //Comment\nint longerVar = 2 //Comment\nint anotherVar = 4 //Command\n int var2 = 1 //Comment\nint longerVar = 2 //Comment\nint anotherVar = 4 //Comment\n"
},
{
"answer_id": 14755,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 2,
"selected": false,
"text": "for (size-type i = 0; i<v.size(); i++) { // rehash:\n size-type ii = has(v[i].key)%b.size9); // hash\n v[i].next = b[ii]; // link\n b[ii] = &v[i];\n}\n\nfor (size-type i = 0; i<v.size(); i++) { // rehash:\n size-type ii = has(v[i].key)%b.size9); // hash\n v[i].next = b[ii]; // link\n b[ii] = &v[i];\n}\n"
},
{
"answer_id": 217736,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": -1,
"selected": false,
"text": "a1 = a111;\nB2 = aaaa;\nc3 = AAAA;\nw4 = wwWW;\nW4 = WWWW;\n a1 = a1 1 1;\nB2 = aaaa;\nc3 = A A A A;\nw4 = w w W W;\nW4 = W W W W;\n"
},
{
"answer_id": 25633473,
"author": "realbart",
"author_id": 1677285,
"author_profile": "https://Stackoverflow.com/users/1677285",
"pm_score": 0,
"selected": false,
"text": "var x = GetResults(\"Main\");\nforeach(var y in x)\n{\n WriteResult(x);\n}\n var electionResults = GetRegionalElactionResults(\"Main\");\nforeach(var result in electionResults)\n{\n Write(result); // you can see what you're writing!!\n}\n int var2 = 1; //The number of days since startup, including the first\nint longerVar = 2; //The number of free days per week\nint anotherVar = 38; //The number of working hours per week\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] |
14,505 |
<p>In the Full .NET framework you can use the Color.FromArgb() method to create a new color with alpha blending, like this:</p>
<pre><code>Color blended = Color.FromArgb(alpha, color);
</code></pre>
<p>or</p>
<pre><code>Color blended = Color.FromArgb(alpha, red, green , blue);
</code></pre>
<p>However in the Compact Framework (2.0 specifically), neither of those methods are available, you only get:</p>
<pre><code>Color.FromArgb(int red, int green, int blue);
</code></pre>
<p>and</p>
<pre><code>Color.FromArgb(int val);
</code></pre>
<p>The first one, obviously, doesn't even let you enter an alpha value, but the documentation for the latter shows that "val" is a 32bit ARGB value (as 0xAARRGGBB as opposed to the standard 24bit 0xRRGGBB), so it would make sense that you could just build the ARGB value and pass it to the function. I tried this with the following:</p>
<pre><code>private Color FromARGB(byte alpha, byte red, byte green, byte blue)
{
int val = (alpha << 24) | (red << 16) | (green << 8) | blue;
return Color.FromArgb(val);
}
</code></pre>
<p>But no matter what I do, the alpha blending never works, the resulting color always as full opacity, even when setting the alpha value to 0.</p>
<p>Has anyone gotten this to work on the Compact Framework?</p>
|
[
{
"answer_id": 2870347,
"author": "fede",
"author_id": 345622,
"author_profile": "https://Stackoverflow.com/users/345622",
"pm_score": 0,
"selected": false,
"text": "device.RenderState.AlphaBlendEnable = true;\ndevice.RenderState.AlphaFunction = Compare.Greater;\ndevice.RenderState.AlphaTestEnable = true;\ndevice.RenderState.DestinationBlend = Blend.InvSourceAlpha;\ndevice.RenderState.SourceBlend = Blend.SourceAlpha;\ndevice.RenderState.DiffuseMaterialSource = ColorSource.Material;\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14505",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
14,527 |
<p>I need to be able to find the last occurrence of a character within an element.</p>
<p>For example:</p>
<pre><code><mediaurl>http://www.blah.com/path/to/file/media.jpg</mediaurl>
</code></pre>
<p>If I try to locate it through using <code>substring-before(mediaurl, '.')</code> and <code>substring-after(mediaurl, '.')</code> then it will, of course, match on the first dot. </p>
<p>How would I get the file extension? Essentially, I need to get the file name and the extension from a path like this, but I am quite stumped as to how to do it using XSLT.</p>
|
[
{
"answer_id": 14547,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "Example: tokenize(\"XPath is fun\", \"\\s+\")\nResult: (\"XPath\", \"is\", \"fun\")\n"
},
{
"answer_id": 14686,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 2,
"selected": false,
"text": " <xsl:variable name=\"extension\" select=\"tokenize($filename, '\\.')[last()]\"/>\n"
},
{
"answer_id": 16414,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 5,
"selected": true,
"text": "<xsl:template name=\"getExtension\">\n<xsl:param name=\"filename\"/>\n\n <xsl:choose>\n <xsl:when test=\"contains($filename, '.')\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"substring-after($filename, '.')\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$filename\"/>\n </xsl:otherwise>\n </xsl:choose>\n</xsl:template>\n\n<xsl:template match=\"/\">\n <xsl:call-template name=\"getExtension\">\n <xsl:with-param name=\"filename\" select=\"'http://www.blah.com/path/to/file/media.jpg'\"/>\n </xsl:call-template>\n</xsl:template>\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
14,530 |
<p>I took a look at the "Beginner's Guide to LINQ" post here on StackOverflow (<a href="https://stackoverflow.com/questions/8050/beginners-guide-to-linq">Beginners Guide to LINQ</a>), but had a follow-up question:</p>
<p>We're about to ramp up a new project where nearly all of our database op's will be fairly simple data retrievals (there's another segment of the project which already writes the data). Most of our other projects up to this point make use of stored procedures for such things. However, I'd like to leverage LINQ-to-SQL if it makes more sense.</p>
<p>So, the question is this: For simple data retrievals, which approach is better, LINQ-to-SQL or stored procs? Any specific pro's or con's?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 32688,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 5,
"selected": false,
"text": "var p = \n from n in x.AddressTypes \n where n.Name == \"Billing\" \n select n;\n\nvar p = \n from n in x.AddressTypes \n where n.Name == \"Main Office\" \n select n;\n"
},
{
"answer_id": 336310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "foreach(Customer c in query)\n{\n c.Country = \"Wonder Land\";\n}\nctx.SubmitChanges();\n"
},
{
"answer_id": 7839840,
"author": "totaldonet",
"author_id": 1005740,
"author_profile": "https://Stackoverflow.com/users/1005740",
"pm_score": 1,
"selected": false,
"text": "Create PROCEDURE userInfoProcedure\n -- Add the parameters for the stored procedure here\n @FirstName varchar,\n @LastName varchar\nAS\nBEGIN\n\n SET NOCOUNT ON;\n\n -- Insert statements for procedure here\n SELECT FirstName , LastName,Age from UserInfo where FirstName=@FirstName\n and LastName=@FirstName\nEND\nGO\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
] |
14,545 |
<p>What I mean by autolinking is the process by which wiki links inlined in page content are generated into either a hyperlink to the page (if it does exist) or a create link (if the page doesn't exist).</p>
<p>With the parser I am using, this is a two step process - first, the page content is parsed and all of the links to wiki pages from the source markup are extracted. Then, I feed an array of the existing pages back to the parser, before the final HTML markup is generated.</p>
<p>What is the best way to handle this process? It seems as if I need to keep a cached list of every single page on the site, rather than having to extract the index of page titles each time. Or is it better to check each link separately to see if it exists? This might result in a lot of database lookups if the list wasn't cached. Would this still be viable for a larger wiki site with thousands of pages?</p>
|
[
{
"answer_id": 31864,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 0,
"selected": false,
"text": "SELECT title FROM articles"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14446/"
] |
14,577 |
<p>Imagine the scene, you're updating some legacy Sybase code and come across a cursor. The stored procedure builds up a result set in a #temporary table which is all ready to be returned except that one of columns isn't terribly human readable, it's an alphanumeric code.</p>
<p>What we need to do, is figure out the possible distinct values of this code, call another stored procedure to cross reference these discrete values and then update the result set with the newly deciphered values:</p>
<pre><code>declare c_lookup_codes for
select distinct lookup_code
from #workinprogress
while(1=1)
begin
fetch c_lookup_codes into @lookup_code
if @@sqlstatus<>0
begin
break
end
exec proc_code_xref @lookup_code @xref_code OUTPUT
update #workinprogress
set xref = @xref_code
where lookup_code = @lookup_code
end
</code></pre>
<p>Now then, whilst this may give some folks palpitations, it does work. My question is, how best would one avoid this kind of thing?</p>
<p>_NB: for the purposes of this example you can also imagine that the result set is in the region of 500k rows and that there are 100 distinct values of look_up_code and finally, that it is not possible to have a table with the xref values in as the logic in proc_code_xref is too arcane._</p>
|
[
{
"answer_id": 988077,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 0,
"selected": false,
"text": "declare @lookup_code char(8)\n\nselect distinct lookup_code\ninto #lookup_codes\nfrom #workinprogress\n\nwhile 1=1\nbegin\n select @lookup_code = lookup_code from #lookup_codes\n\n if @@rowcount = 0 break\n\n exec proc_code_xref @lookup_code @xref_code OUTPUT\n\n delete #lookup_codes\n where lookup_code = @lookup_code\nend\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
14,582 |
<p>I've been using Subversion for code control with TortoiseSVN to interface with the server for the past few months, and in general it's been going great! However, occasionally my FoxPro IDE will change the case of a file extension without warning where "<em>program.prg</em>" becomes "<em>program.<strong>PRG</em></strong>") TortoiseSVN apparently takes this to mean the first file was removed, becoming flagged as "missing" and the second name comes up as "non-versioned", wreaking havoc on my ability to track changes to the file. I understand that Subversion has it origins in the case-sensitive world of *nix but, is there any way to control this behavior in either Subversion or TortoiseSVN to be file name case-insensitive when used with Windows?</p>
|
[
{
"answer_id": 51399368,
"author": "Hugo González Castro",
"author_id": 10098670,
"author_profile": "https://Stackoverflow.com/users/10098670",
"pm_score": 0,
"selected": false,
"text": "FixCaseSensitiveFileNames.bat call FixCaseSensitiveFileNames.bat C:\\MyRepo -n @echo off\nREM *** This BAT uses TortoiseSVN to fix the case-sensitive names of the files in Subversion\nREM *** Call it before an automated commit. The Tortoise commit fixes this issue for manual commits,\nREM *** so the trick is opening the commit window and close it automatically after a pause (with ping).\nREM *** %1 = path to be fixed\n\nstart TortoiseProc.exe /command:commit /path:\"%1\"\nping localhost -n 10 >nul\ntaskkill /im TortoiseProc.exe\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] |
14,614 |
<p>First off, I understand the reasons why an interface or abstract class (in the .NET/C# terminology) cannot have abstract static methods. My question is then more focused on the best design solution.</p>
<p>What I want is a set of "helper" classes that all have their own static methods such that if I get objects A, B, and C from a third party vendor, I can have helper classes with methods such as</p>
<pre>
AHelper.RetrieveByID(string id);
AHelper.RetrieveByName(string name);
AHelper.DumpToDatabase();
</pre>
<p>Since my AHelper, BHelper, and CHelper classes will all basically have the same methods, it seems to makes sense to move these methods to an interface that these classes then derive from. However, wanting these methods to be static precludes me from having a generic interface or abstract class for all of them to derive from.</p>
<p>I could always make these methods non-static and then instantiate the objects first such as</p>
<pre>
AHelper a = new AHelper();
a.DumpToDatabase();
</pre>
<p>However, this code doesn't seem as intuitive to me. What are your suggestions? Should I abandon using an interface or abstract class altogether (the situation I'm in now) or can this possibly be refactored to accomplish the design I'm looking for?</p>
|
[
{
"answer_id": 14622,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "static class HelperMethods\n { //IHelper h = new HeleperA();\n //h.DumpToDatabase() \n public static void DumpToDatabase(this IHelper helper) { /* ... */ }\n\n //IHelper h = a.RetrieveByID(5)\n public static IHelper RetrieveByID(this ObjectA a, int id) \n { \n return new HelperA(a.GetByID(id));\n }\n\n //Ihelper h = b.RetrieveByID(5) \n public static IHelper RetrieveByID(this ObjectB b, int id)\n { \n return new HelperB(b.GetById(id.ToString())); \n }\n }\n"
},
{
"answer_id": 14633,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 2,
"selected": false,
"text": "ClassHelper.RetrieveByID(string id) ClassHelper<ClassA>.RetrieveByID(string id)"
},
{
"answer_id": 14641,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "AHelper.RetrieveByID() BHelper.RetrieveByID() static [return type] Helper.RetrieveByID(ObjectX x) \n"
},
{
"answer_id": 14672,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "static AObject GetAObject(string id);\nstatic BObject GetBObject(string id);\n class AOrBObject\n{ \n string id;\n AOrBObject(string id) {this.id = id;}\n\n static public AOrBObject RetrieveByID(string id)\n {\n return new AOrBObject(id);\n }\n\n public static AObject explicit operator(AOrBObject ab) \n { \n return AObjectQuery(ab.id);\n }\n\n public static BObject explicit operator(AOrBObject ab)\n { \n return BObjectQuery(ab.id);\n } \n}\n var a = (AObject) AOrBObject.RetrieveByID(5);\n var b = (BObject) AOrBObject.RetrieveByID(5); \n"
},
{
"answer_id": 14692,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "public static T RetrieveByID<T>(string ID)\n{\n var fieldNames = getFieldNamesBasedOnType(typeof(T));\n QueryResult qr = webservice.query(\"SELECT \"+fieldNames + \" FROM \"\n + tyepof(T).Name\n +\" WHERE Id = '\" + ID + \"'\");\n return (T) qr.records[0];\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
14,617 |
<p>I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>
|
[
{
"answer_id": 14629,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 5,
"selected": false,
"text": "SshClient ssh = new SshClient();\nssh.connect(host, port);\n//Authenticate\nPasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();\npasswordAuthenticationClient.setUsername(userName);\npasswordAuthenticationClient.setPassword(password);\nint result = ssh.authenticate(passwordAuthenticationClient);\nif(result != AuthenticationProtocolState.COMPLETE){\n throw new SFTPException(\"Login to \" + host + \":\" + port + \" \" + userName + \"/\" + password + \" failed\");\n}\n//Open the SFTP channel\nSftpClient client = ssh.openSftpClient();\n//Send the file\nclient.put(filePath);\n//disconnect\nclient.quit();\nssh.disconnect();\n"
},
{
"answer_id": 15937,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 9,
"selected": true,
"text": "JSch jsch = new JSch();\n\nString knownHostsFilename = \"/home/username/.ssh/known_hosts\";\njsch.setKnownHosts( knownHostsFilename );\n\nSession session = jsch.getSession( \"remote-username\", \"remote-host\" ); \n{\n // \"interactive\" version\n // can selectively update specified known_hosts file \n // need to implement UserInfo interface\n // MyUserInfo is a swing implementation provided in \n // examples/Sftp.java in the JSch dist\n UserInfo ui = new MyUserInfo();\n session.setUserInfo(ui);\n\n // OR non-interactive version. Relies in host key being in known-hosts file\n session.setPassword( \"remote-password\" );\n}\n\nsession.connect();\n\nChannel channel = session.openChannel( \"sftp\" );\nchannel.connect();\n\nChannelSftp sftpChannel = (ChannelSftp) channel;\n\nsftpChannel.get(\"remote-file\", \"local-file\" );\n// OR\nInputStream in = sftpChannel.get( \"remote-file\" );\n // process inputstream as needed\n\nsftpChannel.exit();\nsession.disconnect();\n"
},
{
"answer_id": 2404783,
"author": "shikhar",
"author_id": 126346,
"author_profile": "https://Stackoverflow.com/users/126346",
"pm_score": 3,
"selected": false,
"text": "package net.schmizz.sshj.examples;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.sftp.SFTPClient;\nimport net.schmizz.sshj.xfer.FileSystemFile;\n\nimport java.io.File;\nimport java.io.IOException;\n\n/** This example demonstrates uploading of a file over SFTP to the SSH server. */\npublic class SFTPUpload {\n\n public static void main(String[] args)\n throws IOException {\n final SSHClient ssh = new SSHClient();\n ssh.loadKnownHosts();\n ssh.connect(\"localhost\");\n try {\n ssh.authPublickey(System.getProperty(\"user.name\"));\n final String src = System.getProperty(\"user.home\") + File.separator + \"test_file\";\n final SFTPClient sftp = ssh.newSFTPClient();\n try {\n sftp.put(new FileSystemFile(src), \"/tmp\");\n } finally {\n sftp.close();\n }\n } finally {\n ssh.disconnect();\n }\n }\n\n}\n"
},
{
"answer_id": 2548590,
"author": "Chris J",
"author_id": 165119,
"author_profile": "https://Stackoverflow.com/users/165119",
"pm_score": 6,
"selected": false,
"text": "FileSystemOptions fsOptions = new FileSystemOptions();\nSftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, \"no\");\nFileSystemManager fsManager = VFS.getManager();\nString uri = \"sftp://user:password@host:port/absolute-path\";\nFileObject fo = fsManager.resolveFile(uri, fsOptions);\n"
},
{
"answer_id": 2690861,
"author": "Iraklis",
"author_id": 172467,
"author_profile": "https://Stackoverflow.com/users/172467",
"pm_score": 7,
"selected": false,
"text": "import com.jcraft.jsch.*;\n\npublic class TestJSch {\n public static void main(String args[]) {\n JSch jsch = new JSch();\n Session session = null;\n try {\n session = jsch.getSession(\"username\", \"127.0.0.1\", 22);\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.setPassword(\"password\");\n session.connect();\n\n Channel channel = session.openChannel(\"sftp\");\n channel.connect();\n ChannelSftp sftpChannel = (ChannelSftp) channel;\n sftpChannel.get(\"remotefile.txt\", \"localfile.txt\");\n sftpChannel.exit();\n session.disconnect();\n } catch (JSchException e) {\n e.printStackTrace(); \n } catch (SftpException e) {\n e.printStackTrace();\n }\n }\n}\n"
},
{
"answer_id": 5229795,
"author": "Pushpinder Rattan",
"author_id": 480686,
"author_profile": "https://Stackoverflow.com/users/480686",
"pm_score": 2,
"selected": false,
"text": "(channelExec)"
},
{
"answer_id": 18005722,
"author": "Zon",
"author_id": 1112963,
"author_profile": "https://Stackoverflow.com/users/1112963",
"pm_score": 2,
"selected": false,
"text": "SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png\", /path/to/destinationfile.png\");\n SFTPFileCopy download = new SFTPFileCopy(false, \"/path/to/sourcefile.png\", \"/path/to/destinationfile.png\");\n import com.jcraft.jsch.Channel;\nimport com.jcraft.jsch.ChannelSftp;\nimport com.jcraft.jsch.JSch;\nimport com.jcraft.jsch.Session;\nimport com.jcraft.jsch.UIKeyboardInteractive;\nimport com.jcraft.jsch.UserInfo;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport javax.swing.JOptionPane;\nimport menue.Menue;\n\npublic class SFTPFileCopy1 {\n\n public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {\n Session session = null;\n Channel channel = null;\n ChannelSftp sftpChannel = null;\n try {\n JSch jsch = new JSch();\n //jsch.setKnownHosts(\"/home/user/.putty/sshhostkeys\");\n session = jsch.getSession(\"login\", \"mysite.com\", 22);\n session.setPassword(\"password\");\n\n UserInfo ui = new MyUserInfo() {\n public void showMessage(String message) {\n\n JOptionPane.showMessageDialog(null, message);\n\n }\n\n public boolean promptYesNo(String message) {\n\n Object[] options = {\"yes\", \"no\"};\n\n int foo = JOptionPane.showOptionDialog(null,\n message,\n \"Warning\",\n JOptionPane.DEFAULT_OPTION,\n JOptionPane.WARNING_MESSAGE,\n null, options, options[0]);\n\n return foo == 0;\n\n }\n };\n session.setUserInfo(ui);\n\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.connect();\n channel = session.openChannel(\"sftp\");\n channel.setInputStream(System.in);\n channel.setOutputStream(System.out);\n channel.connect();\n sftpChannel = (ChannelSftp) channel;\n\n if (upload) { // File upload.\n byte[] bufr = new byte[(int) new File(sourcePath).length()];\n FileInputStream fis = new FileInputStream(new File(sourcePath));\n fis.read(bufr);\n ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);\n sftpChannel.put(fileStream, destPath);\n fileStream.close();\n } else { // File download.\n byte[] buffer = new byte[1024];\n BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));\n OutputStream os = new FileOutputStream(new File(destPath));\n BufferedOutputStream bos = new BufferedOutputStream(os);\n int readCount;\n while ((readCount = bis.read(buffer)) > 0) {\n bos.write(buffer, 0, readCount);\n }\n bis.close();\n bos.close();\n }\n } catch (Exception e) {\n System.out.println(e);\n } finally {\n if (sftpChannel != null) {\n sftpChannel.exit();\n }\n if (channel != null) {\n channel.disconnect();\n }\n if (session != null) {\n session.disconnect();\n }\n }\n }\n\n public static abstract class MyUserInfo\n implements UserInfo, UIKeyboardInteractive {\n\n public String getPassword() {\n return null;\n }\n\n public boolean promptYesNo(String str) {\n return false;\n }\n\n public String getPassphrase() {\n return null;\n }\n\n public boolean promptPassphrase(String message) {\n return false;\n }\n\n public boolean promptPassword(String message) {\n return false;\n }\n\n public void showMessage(String message) {\n }\n\n public String[] promptKeyboardInteractive(String destination,\n String name,\n String instruction,\n String[] prompt,\n boolean[] echo) {\n\n return null;\n }\n }\n}\n"
},
{
"answer_id": 18975867,
"author": "AZ_",
"author_id": 185022,
"author_profile": "https://Stackoverflow.com/users/185022",
"pm_score": 4,
"selected": false,
"text": "import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class SendMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n SendMyFiles sendMyFiles = new SendMyFiles();\n if (args.length < 1)\n {\n System.err.println(\"Usage: java \" + sendMyFiles.getClass().getName()+\n \" Properties_file File_To_FTP \");\n System.exit(1);\n }\n \n String propertiesFile = args[0].trim();\n String fileToFTP = args[1].trim();\n sendMyFiles.startFTP(propertiesFile, fileToFTP);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToFTP){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream(\"properties/\" + propertiesFilename));\n String serverAddress = props.getProperty(\"serverAddress\").trim();\n String userId = props.getProperty(\"userId\").trim();\n String password = props.getProperty(\"password\").trim();\n String remoteDirectory = props.getProperty(\"remoteDirectory\").trim();\n String localDirectory = props.getProperty(\"localDirectory\").trim();\n \n //check if the file exists\n String filepath = localDirectory + fileToFTP;\n File file = new File(filepath);\n if (!file.exists())\n throw new RuntimeException(\"Error. Local file not found\");\n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, \"no\");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = \"sftp://\" + userId + \":\" + password + \"@\" + serverAddress + \"/\" + \n remoteDirectory + fileToFTP;\n \n // Create local file object\n FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n // Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n // Copy local file to sftp server\n remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);\n System.out.println(\"File upload successful\");\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n \n}\n import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class GetMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n GetMyFiles getMyFiles = new GetMyFiles();\n if (args.length < 1)\n {\n System.err.println(\"Usage: java \" + getMyFiles.getClass().getName()+\n \" Properties_filename File_To_Download \");\n System.exit(1);\n }\n \n String propertiesFilename = args[0].trim();\n String fileToDownload = args[1].trim();\n getMyFiles.startFTP(propertiesFilename, fileToDownload);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream(\"properties/\" + propertiesFilename));\n String serverAddress = props.getProperty(\"serverAddress\").trim();\n String userId = props.getProperty(\"userId\").trim();\n String password = props.getProperty(\"password\").trim();\n String remoteDirectory = props.getProperty(\"remoteDirectory\").trim();\n String localDirectory = props.getProperty(\"localDirectory\").trim();\n \n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, \"no\");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = \"sftp://\" + userId + \":\" + password + \"@\" + serverAddress + \"/\" + \n remoteDirectory + fileToDownload;\n \n // Create local file object\n String filepath = localDirectory + fileToDownload;\n File file = new File(filepath);\n FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n // Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n // Copy local file to sftp server\n localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);\n System.out.println(\"File download successful\");\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n}\n import java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class DeleteRemoteFile {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n DeleteRemoteFile getMyFiles = new DeleteRemoteFile();\n if (args.length < 1)\n {\n System.err.println(\"Usage: java \" + getMyFiles.getClass().getName()+\n \" Properties_filename File_To_Delete \");\n System.exit(1);\n }\n \n String propertiesFilename = args[0].trim();\n String fileToDownload = args[1].trim();\n getMyFiles.startFTP(propertiesFilename, fileToDownload);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n props = new Properties();\n StandardFileSystemManager manager = new StandardFileSystemManager();\n \n try {\n \n props.load(new FileInputStream(\"properties/\" + propertiesFilename));\n String serverAddress = props.getProperty(\"serverAddress\").trim();\n String userId = props.getProperty(\"userId\").trim();\n String password = props.getProperty(\"password\").trim();\n String remoteDirectory = props.getProperty(\"remoteDirectory\").trim();\n \n \n //Initializes the file manager\n manager.init();\n \n //Setup our SFTP configuration\n FileSystemOptions opts = new FileSystemOptions();\n SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n opts, \"no\");\n SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n \n //Create the SFTP URI using the host name, userid, password, remote path and file name\n String sftpUri = \"sftp://\" + userId + \":\" + password + \"@\" + serverAddress + \"/\" + \n remoteDirectory + fileToDownload;\n \n //Create remote file object\n FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n //Check if the file exists\n if(remoteFile.exists()){\n remoteFile.delete();\n System.out.println(\"File delete successful\");\n }\n \n }\n catch (Exception ex) {\n ex.printStackTrace();\n return false;\n }\n finally {\n manager.close();\n }\n \n return true;\n }\n \n}\n"
},
{
"answer_id": 36422906,
"author": "Sasha",
"author_id": 91495,
"author_profile": "https://Stackoverflow.com/users/91495",
"pm_score": 5,
"selected": false,
"text": "final SSHClient ssh = new SSHClient();\nssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())\nssh.connect(\"localhost\");\ntry {\n ssh.authPassword(\"user\", \"password\"); // or ssh.authPublickey(System.getProperty(\"user.name\"))\n final SFTPClient sftp = ssh.newSFTPClient();\n try {\n sftp.get(\"test_file\", \"/tmp/test.tmp\");\n } finally {\n sftp.close();\n }\n} finally {\n ssh.disconnect();\n}\n"
},
{
"answer_id": 46559783,
"author": "Ankur jain",
"author_id": 641001,
"author_profile": "https://Stackoverflow.com/users/641001",
"pm_score": 3,
"selected": false,
"text": "JSch jsch = new JSch();\n Session session = null;\n try {\n session = jsch.getSession(\"user\", \"127.0.0.1\", 22);\n session.setConfig(\"StrictHostKeyChecking\", \"no\");\n session.setPassword(\"password\");\n session.connect();\n\n Channel channel = session.openChannel(\"sftp\");\n channel.connect();\n ChannelSftp sftpChannel = (ChannelSftp) channel;\n\n InputStream stream = sftpChannel.get(\"/usr/home/testfile.txt\");\n try {\n BufferedReader br = new BufferedReader(new InputStreamReader(stream));\n String line;\n while ((line = br.readLine()) != null) {\n System.out.println(line);\n }\n\n } catch (IOException io) {\n System.out.println(\"Exception occurred during reading file from SFTP server due to \" + io.getMessage());\n io.getMessage();\n\n } catch (Exception e) {\n System.out.println(\"Exception occurred during reading file from SFTP server due to \" + e.getMessage());\n e.getMessage();\n\n }\n\n sftpChannel.exit();\n session.disconnect();\n } catch (JSchException e) {\n e.printStackTrace();\n } catch (SftpException e) {\n e.printStackTrace();\n }\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1769/"
] |
14,618 |
<p>What's the best way of implementing a multiple choice option in Windows Forms? I want to enforce a single selection from a list, starting with a default value.</p>
<p>It seems like a ComboBox would be a good choice, but is there a way to specify a non-blank default value?<br>
I could just set it in the code at some appropriate initialisation point, but I feel like I'm missing something.</p>
|
[
{
"answer_id": 14710,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 1,
"selected": false,
"text": "private sub populateList( items as List(of UserChoices))\n dim choices as UserChoices\n dim defaultChoice as UserChoices \n\n for each choice in items\n cboList.items.add(choice)\n '-- you could do user specific check or base it on some other \n '---- setting to find the default choice here\n if choice.state = _user.State or choice.state = _settings.defaultState then \n defaultChoice = choice\n end if \n next \n '-- you chould select the first one\n if cboList.items.count > 0 then\n cboList.SelectedItem = cboList.item(0)\n end if \n\n '-- continuation of hte default choice\n cboList.SelectedItem = defaultChoice\n\nend sub\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1077/"
] |
14,634 |
<p>Let's take a web development environment, where developers checkout a project onto their local machines, work on it, and check in changes to development.<br>
These changes are further tested on development and moved live on a regular schedule (eg weekly, monthly, etc.).<br>
Is it possible to have an auto-moveup of the latest tagged version (and not the latest checkin, as that might not be 100% stable), for example 8AM on Monday mornings, either using a script or a built-in feature of the VCS?</p>
|
[
{
"answer_id": 14680,
"author": "icco",
"author_id": 1063,
"author_profile": "https://Stackoverflow.com/users/1063",
"pm_score": 1,
"selected": false,
"text": "hg update\n svn co http://host/repository/branchname/\n svn up\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
14,656 |
<p>Can a (||any) proxy server cache content that is requested by a client over https? As the proxy server can't see the querystring, or the http headers, I reckon they can't.</p>
<p>I'm considering a desktop application, run by a number of people behind their companies proxy. This application may access services across the internet and I'd like to take advantage of the in-built internet caching infrastructure for 'reads'. If the caching proxy servers can't cache SSL delivered content, would simply encrypting the content of a response be a viable option?</p>
<p>I am considering all GET requests that we wish to be cachable be requested over http with the body encrypted using asymmetric encryption, where each client has the decryption key. Anytime we wish to perform a GET that is not cachable, or a POST operation, it will be performed over SSL.</p>
|
[
{
"answer_id": 2861265,
"author": "Jesse Hallett",
"author_id": 103017,
"author_profile": "https://Stackoverflow.com/users/103017",
"pm_score": 0,
"selected": false,
"text": "application server <---> Squid or Varnish (cache) <---> Apache (performs SSL encryption)\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
14,697 |
<p>I've looked at several URL rewriters for ASP.Net and IIS and was wondering what everyone else uses, and why. </p>
<p>Here are the ones that I have used or looked at:</p>
<ul>
<li><a href="http://www.codeproject.com/KB/aspnet/urlrewriter.aspx" rel="nofollow noreferrer">ThunderMain URLRewriter</a>: used in a previous project, didn't quite have the flexibility/performance we were looking for</li>
<li><a href="http://web.archive.org/web/20070202012119/blog.ewal.net/2004/04/14/a-url-redirecting-url-rewriting-httpmodule/" rel="nofollow noreferrer">Ewal UrlMapper</a>: used in a current project, but source seems to be abandoned</li>
<li><a href="http://www.urlrewriting.net/149/en/home.html" rel="nofollow noreferrer">UrlRewritingNet.UrlRewrite</a>: seems like a decent library but documentation's poor grammar leaves me feeling uneasy</li>
<li><a href="http://urlrewriter.net/" rel="nofollow noreferrer">UrlRewriter.NET</a>: this is my current fav, has great flexibility, although the extra functions pumped into the replacement regexs changes the standard .Net regex syntax a bit</li>
<li><a href="http://www.managedfusion.com/products/url-rewriter/" rel="nofollow noreferrer">Managed Fusion URL Rewriter</a>: I found this one in a <a href="https://stackoverflow.com/questions/2262/aspnet-url-rewriting#2268">previous question</a> on stack overflow, but haven't tried it out yet, from the example syntax, it doesn't seem to be editable via web.config</li>
</ul>
|
[
{
"answer_id": 12120464,
"author": "Paras",
"author_id": 615798,
"author_profile": "https://Stackoverflow.com/users/615798",
"pm_score": 0,
"selected": false,
"text": " protected void Application_Start(object sender, EventArgs e)\n {\n\n RegisterRoutes(RouteTable.Routes);\n\n\n }\n private static void RegisterRoutes(RouteCollection routes)\n { \n\n routes.Add(\"Routing1\", new Route(\"/Blog/id/2\",\"/Blog.aspx\"));\n\n }\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
14,698 |
<p>When I try to precompile a *.pc file that contains a #warning directive I recieve the following error:</p>
<blockquote>
<p>PCC-S-02014, Encountered the symbol "warning" when expecting one of the following: (bla bla bla).</p>
</blockquote>
<p>Can I somehow convince Pro*C to ignore the thing if it doesn't know what to do with it? I can't remove the <code>#warning</code> directive as it's used in a header file that I can't change and must include.</p>
|
[
{
"answer_id": 14999,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 0,
"selected": false,
"text": "grep -v -E '^#(warning|pragma|define)' unchangeable.h >unchangeable.pc.h\n"
},
{
"answer_id": 23585,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 4,
"selected": true,
"text": "#ifndef ORA_PROC\n#include <irrelevant.h>\n#endif\n"
},
{
"answer_id": 3911475,
"author": "Ludwig",
"author_id": 472884,
"author_profile": "https://Stackoverflow.com/users/472884",
"pm_score": 2,
"selected": false,
"text": "parse=none"
},
{
"answer_id": 4734773,
"author": "yijy",
"author_id": 581350,
"author_profile": "https://Stackoverflow.com/users/581350",
"pm_score": -1,
"selected": false,
"text": "/usr/include/standards.h #warning The -qdfp option is required to process DFP code in headers. #warning #else #if"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733/"
] |
14,708 |
<p>What's the DOS FINDSTR equivalent for <a href="http://en.wikipedia.org/wiki/Windows_PowerShell" rel="noreferrer">PowerShell</a>? I need to search a bunch of log files for "ERROR".</p>
|
[
{
"answer_id": 14724,
"author": "Monroecheeseman",
"author_id": 1351,
"author_profile": "https://Stackoverflow.com/users/1351",
"pm_score": 5,
"selected": false,
"text": "Get-ChildItem -Recurse -Include *.log | select-string ERROR \n"
},
{
"answer_id": 14725,
"author": "slipsec",
"author_id": 1635,
"author_profile": "https://Stackoverflow.com/users/1635",
"pm_score": 0,
"selected": false,
"text": "if ($entry.EntryType -eq \"Error\")\n man Get-EventLog\nGet-EventLog -newest 5 -logname System -EntryType Error\n"
},
{
"answer_id": 14737,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "gci -r -i *.c | select-string \"#include\"\n"
},
{
"answer_id": 12324320,
"author": "Chris Rudd",
"author_id": 1229736,
"author_profile": "https://Stackoverflow.com/users/1229736",
"pm_score": 0,
"selected": false,
"text": "# Search in Files Script\n# ---- Set these before you begin ---- \n$FolderToSearch=\"C:\\\" # UNC paths are ok, but remember you're mass reading file contents over the network\n$Search=\"Looking For This\" # accepts regex format\n$IncludeSubfolders=$True #BUG: if this is set $False then $FileIncludeFilter must be \"*\" or you will always get 0 results\n$AllMatches=$False\n$FileIncludeFilter=\"*\".split(\",\") # Restricting to specific file types is faster than excluding everything else\n$FileExcludeFilter=\"*.exe,*.dll,*.wav,*.mp3,*.gif,*.jpg,*.png,*.ghs,*.rar,*.iso,*.zip,*.vmdk,*.dat,*.pst,*.gho\".split(\",\")\n\n# ---- Initialize ----\nif ($AllMatches -eq $True) {$SelectParam=@{AllMatches=$True}}\nelse {$SelectParam=@{List=$True}}\nif ($IncludeSubfolders -eq $True) {$RecurseParam=@{Recurse=$True}}\nelse {$RecurseParam=@{Recurse=$False}}\n\n# ---- Build File List ---- \n#$Files=Get-Content -Path=\"$env:userprofile\\Desktop\\FileList.txt\" # For searching a manual list of files\nWrite-Host \"Building file list...\" -NoNewline\n$Files=Get-ChildItem -Include $FileIncludeFilter -Exclude $FileExcludeFilter -Path $FolderToSearch -ErrorAction silentlycontinue @RecurseParam|Where-Object{-not $_.psIsContainer} # @RecurseParam is basically -Recurse=[$True|$False]\n#$Files=$Files|Out-GridView -PassThru -Title 'Select the Files to Search' # Manually choose files to search, requires powershell 3.0\nWrite-Host \"Done\"\n\n# ---- Begin Search ---- \nWrite-Host \"Searching Files...\"\n$Files|\n Select-String $Search @SelectParam| #The @ instead of $ lets me pass the hastable as a list of parameters. @SelectParam is either -List or -AllMatches\n Tee-Object -Variable Results|\n Select-Object Path\nWrite-Host \"Search Complete\"\n#$Results|Group-Object path|ForEach-Object{$path=$_.name; $matches=$_.group|%{[string]::join(\"`t\", $_.Matches)}; \"$path`t$matches\"} # Show results including the matches separated by tabs (useful if using regex search)\n\n<# Other Stuff\n #-- Saving and restoring results\n $Results|Export-Csv \"$env:appdata\\SearchResults.txt\" # $env:appdata can be replaced with any UNC path, this just seemed like a logical place to default to\n $Results=Import-Csv \"$env:appdata\\SearchResults.txt\"\n\n #-- alternate search patterns\n $Search=\"(\\d[-|]{0,}){15,19}\" #Rough CC Match\n#>\n"
},
{
"answer_id": 21749061,
"author": "deostroll",
"author_id": 145682,
"author_profile": "https://Stackoverflow.com/users/145682",
"pm_score": 0,
"selected": false,
"text": "gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains(\"|\") -eq $true }\n |"
},
{
"answer_id": 35832654,
"author": "skataben",
"author_id": 873131,
"author_profile": "https://Stackoverflow.com/users/873131",
"pm_score": 0,
"selected": false,
"text": "-Verbose function Find-String\n{\n [CmdletBinding(DefaultParameterSetName='Path')]\n param\n (\n [Parameter(Mandatory=$true, Position=0)]\n [string]\n $Pattern,\n\n [Parameter(ParameterSetName='Path', Mandatory=$false, Position=1, ValueFromPipeline=$true)]\n [string[]]\n $Path,\n\n [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]\n [Alias('PSPath')]\n [string[]]\n $LiteralPath,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $IgnoreCase,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $UseLiteral,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $Recurse,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $Force,\n\n [Parameter(Mandatory=$false)]\n [switch]\n $AsCustomObject\n )\n\n begin\n {\n $value = $Pattern.Replace('\\', '\\\\\\\\').Replace('\"', '\\\"')\n\n $findStrArgs = @(\n '/N'\n '/O'\n @('/R', '/L')[[bool]$UseLiteral]\n \"/c:$value\"\n )\n\n if ($IgnoreCase)\n {\n $findStrArgs += '/I'\n }\n\n function GetCmdLine([array]$argList)\n {\n ($argList | foreach { @($_, \"`\"$_`\"\")[($_.Trim() -match '\\s')] }) -join ' '\n }\n }\n\n process\n {\n $PSBoundParameters[$PSCmdlet.ParameterSetName] | foreach {\n try\n {\n $_ | Get-ChildItem -Recurse:$Recurse -Force:$Force -ErrorAction Stop | foreach {\n try\n {\n $file = $_\n $argList = $findStrArgs + $file.FullName\n\n Write-Verbose \"findstr.exe $(GetCmdLine $argList)\"\n\n findstr.exe $argList | foreach {\n if (-not $AsCustomObject)\n {\n return \"${file}:$_\"\n }\n\n $split = $_.Split(':', 3)\n\n [pscustomobject] @{\n File = $file\n Line = $split[0]\n Column = $split[1]\n Value = $split[2]\n }\n }\n }\n catch\n {\n Write-Error -ErrorRecord $_\n }\n }\n }\n catch\n {\n Write-Error -ErrorRecord $_\n }\n }\n }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1351/"
] |
14,712 |
<p>does anyone have a clue why the TortoiseSVN windows client (in Win32 XP and Vista)
is so incredible slow when used with Putty and PAM? It seems it connects for each request
since datatransfers (checkout) are not slow at all?</p>
<p>Any ideas how to change it?</p>
<p>Update: I had no problems with SSH before. But I have to use key based authentification. </p>
|
[
{
"answer_id": 22714832,
"author": "bebbo",
"author_id": 1412279,
"author_profile": "https://Stackoverflow.com/users/1412279",
"pm_score": 0,
"selected": false,
"text": "svn+ssh://xxx.yy/path/to/svn/trunk/foobar\n xxx.yy\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
14,717 |
<p>We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?</p>
<p>Does anyone have some good methods for tracking down expensive queries/processes in this environment?</p>
|
[
{
"answer_id": 14766,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 5,
"selected": true,
"text": "SELECT TOP 50\n qs.total_worker_time/qs.execution_count as [Avg CPU Time],\n SUBSTRING(qt.text,qs.statement_start_offset/2, \n (case when qs.statement_end_offset = -1 \n then len(convert(nvarchar(max), qt.text)) * 2 \n else qs.statement_end_offset end -qs.statement_start_offset)/2) \n as query_text,\n qt.dbid, dbname=db_name(qt.dbid),\n qt.objectid \nFROM sys.dm_exec_query_stats qs\ncross apply sys.dm_exec_sql_text(qs.sql_handle) as qt\nORDER BY \n [Avg CPU Time] DESC\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212/"
] |
14,731 |
<p>Normally I would just use:</p>
<pre><code>HttpContext.Current.Server.UrlEncode("url");
</code></pre>
<p>But since this is a console application, <code>HttpContext.Current</code> is always going to be <code>null</code>.</p>
<p>Is there another method that does the same thing that I could use?</p>
|
[
{
"answer_id": 14736,
"author": "Andrew Taylor",
"author_id": 1776,
"author_profile": "https://Stackoverflow.com/users/1776",
"pm_score": 6,
"selected": false,
"text": "HttpUtility.UrlEncode Method (String)\n"
},
{
"answer_id": 14745,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": false,
"text": "System.Web.HttpUtility.urlencode(\"url\")\n"
},
{
"answer_id": 390650,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "''' <summary>\n''' URL encoding class. Note: use at your own risk.\n''' Written by: Ian Hopkins (http://www.lucidhelix.com)\n''' Date: 2008-Dec-23\n''' </summary>\nPublic Class UrlHelper\n Public Shared Function Encode(ByVal str As String) As String\n Dim charClass = String.Format(\"0-9a-zA-Z{0}\", Regex.Escape(\"-_.!~*'()\"))\n Dim pattern = String.Format(\"[^{0}]\", charClass)\n Dim evaluator As New MatchEvaluator(AddressOf EncodeEvaluator)\n\n ' replace the encoded characters\n Return Regex.Replace(str, pattern, evaluator)\n End Function\n\n Private Shared Function EncodeEvaluator(ByVal match As Match) As String\n ' Replace the \" \"s with \"+\"s\n If (match.Value = \" \") Then\n Return \"+\"\n End If\n Return String.Format(\"%{0:X2}\", Convert.ToInt32(match.Value.Chars(0)))\n End Function\n\n Public Shared Function Decode(ByVal str As String) As String\n Dim evaluator As New MatchEvaluator(AddressOf DecodeEvaluator)\n\n ' Replace the \"+\"s with \" \"s\n str = str.Replace(\"+\"c, \" \"c)\n\n ' Replace the encoded characters\n Return Regex.Replace(str, \"%[0-9a-zA-Z][0-9a-zA-Z]\", evaluator)\n End Function\n\n Private Shared Function DecodeEvaluator(ByVal match As Match) As String\n Return \"\" + Convert.ToChar(Integer.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber))\n End Function\nEnd Class\n"
},
{
"answer_id": 4006817,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// URL encoding class. Note: use at your own risk.\n/// Written by: Ian Hopkins (http://www.lucidhelix.com)\n/// Date: 2008-Dec-23\n/// (Ported to C# by t3rse (http://www.t3rse.com))\n/// </summary>\npublic class UrlHelper\n{\n public static string Encode(string str) {\n var charClass = String.Format(\"0-9a-zA-Z{0}\", Regex.Escape(\"-_.!~*'()\"));\n return Regex.Replace(str, \n String.Format(\"[^{0}]\", charClass),\n new MatchEvaluator(EncodeEvaluator));\n }\n\n public static string EncodeEvaluator(Match match)\n {\n return (match.Value == \" \")?\"+\" : String.Format(\"%{0:X2}\", Convert.ToInt32(match.Value[0]));\n }\n\n public static string DecodeEvaluator(Match match) {\n return Convert.ToChar(int.Parse(match.Value.Substring(1), System.Globalization.NumberStyles.HexNumber)).ToString();\n }\n\n public static string Decode(string str) \n {\n return Regex.Replace(str.Replace('+', ' '), \"%[0-9a-zA-Z][0-9a-zA-Z]\", new MatchEvaluator(DecodeEvaluator));\n }\n}\n"
},
{
"answer_id": 8931490,
"author": "Ostati",
"author_id": 2654100,
"author_profile": "https://Stackoverflow.com/users/2654100",
"pm_score": 7,
"selected": true,
"text": "Uri.EscapeUriString(url);\n Uri.EscapeDataString(data)\n"
},
{
"answer_id": 35093168,
"author": "Devson Technologies",
"author_id": 1232988,
"author_profile": "https://Stackoverflow.com/users/1232988",
"pm_score": 3,
"selected": false,
"text": "using System.Net; WebUtility.UrlDecode(string) System.Net.WebUtility.UrlDecode(string) WebUtility System"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1469/"
] |
14,760 |
<p>In the Visual Studio toolbar, you can enter commands into the search box by prefixing them with a > symbol. Is there any way to disable this? I've never used the feature, and it's slightly annoying when trying to actually search for something that you know is prefixed by greater-than in the code. It's particularly annoying when you accidentally search for "> exit" and the IDE quits (I knew there was a line in the code that was something like <code>if(counter > exitCount)</code> so entered that search without thinking).</p>
<p>At the very least, can you escape the > symbol so that you can search for it? Prefixing with ^ doesn't seem to work.</p>
|
[
{
"answer_id": 15301,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 0,
"selected": false,
"text": "alias"
},
{
"answer_id": 15335,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 3,
"selected": true,
"text": ">exit >Edit.Find >exit"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739/"
] |
14,770 |
<p>In .NET there are two version numbers available when building a project, File Version and Assembly Version. How are you using these numbers? Keeping them the same? Auto-incrementing one, but manually changing the other?</p>
<p>Also what about the <code>AssemblyInformationalVersion</code> attribute?</p>
<p>I'd found this support Microsoft Knowledge Base (KB) article that provided some help: <a href="http://support.microsoft.com/kb/556041" rel="noreferrer">How to use Assembly Version and Assembly File Version</a>.</p>
|
[
{
"answer_id": 14835,
"author": "Jon Dewees",
"author_id": 1365,
"author_profile": "https://Stackoverflow.com/users/1365",
"pm_score": 6,
"selected": false,
"text": "[assembly: AssemblyVersion(Foo.StaticVersion.Bar)]\n namespace Foo\n{\n public static class StaticVersion\n {\n public const string Bar= \"3.0.216.0\"; // 08/01/2008 17:28:35\n }\n}\n"
},
{
"answer_id": 1723652,
"author": "Philip Wallace",
"author_id": 190145,
"author_profile": "https://Stackoverflow.com/users/190145",
"pm_score": 4,
"selected": false,
"text": "[assembly: AssemblyVersion(\"1.0.*\")]\n[assembly: AssemblyCompany(\"Acme Corporationy\")]\n[assembly: AssemblyCopyright(\"Copyright © 2009 Acme Corporation\")]\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752/"
] |
14,775 |
<p>I have been a VB.net developer for a few years now but I am currently applying to a few companies that use C#. I have even been told that at least one of the companies doesn't want VB.net developers. </p>
<p>I have been looking online trying to find real differences between the two and have asked on crackoverflow. The only major differences are a few syntax difference which are trivial to me because I am also a Java developer. </p>
<p>What would be a good response to an interviewer when they tell me they are looking for a C# developer - or similar questions? </p>
|
[
{
"answer_id": 14814,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "Function(x) x.ToString()\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
14,791 |
<p>We have a website that uses <code>#include file</code> command to roll info into some web pages. The authors can access the text files to update things like the occasional class or contact information for the department.</p>
<p>My question is this, I don't <em>see</em> anyone using this method and wonder if it is a good idea to keep using it. If not, what method should I transition to instead?</p>
|
[
{
"answer_id": 14814,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "Function(x) x.ToString()\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
14,801 |
<p>Suppose you have the following EJB 3 interfaces/classes:</p>
<pre><code>public interface Repository<E>
{
public void delete(E entity);
}
public abstract class AbstractRepository<E> implements Repository<E>
{
public void delete(E entity){
//...
}
}
public interface FooRepository<Foo>
{
//other methods
}
@Local(FooRepository.class)
@Stateless
public class FooRepositoryImpl extends
AbstractRepository<Foo> implements FooRepository
{
@Override
public void delete(Foo entity){
//do something before deleting the entity
super.delete(entity);
}
//other methods
}
</code></pre>
<p>And then another bean that accesses the <code>FooRepository</code> bean :</p>
<pre><code>//...
@EJB
private FooRepository fooRepository;
public void someMethod(Foo foo)
{
fooRepository.delete(foo);
}
//...
</code></pre>
<p>However, the overriding method is never executed when the delete method of the <code>FooRepository</code> bean is called. Instead, only the implementation of the delete method that is defined in <code>AbstractRepository</code> is executed. </p>
<p>What am I doing wrong or is it simply a limitation of Java/EJB 3 that generics and inheritance don't play well together yet ?</p>
|
[
{
"answer_id": 15279,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 3,
"selected": true,
"text": "public static void main(String[] args){\n FooRepository fooRepository = new FooRepositoryImpl();\n fooRepository.delete(new Foo(\"Bar\"));\n}\n\npublic class Foo\n{\n private String value;\n\n public Foo(String inValue){\n super();\n value = inValue;\n }\n public String toString(){\n return value;\n }\n}\n\npublic interface Repository<E>\n{\n public void delete(E entity);\n}\n\npublic interface FooRepository extends Repository<Foo>\n{\n //other methods\n}\n\npublic class AbstractRespository<E> implements Repository<E>\n{\n public void delete(E entity){\n System.out.println(\"Delete-\" + entity.toString());\n }\n}\n\npublic class FooRepositoryImpl extends AbstractRespository<Foo> implements FooRepository\n{\n @Override\n public void delete(Foo entity){\n //do something before deleting the entity\n System.out.println(\"something before\");\n super.delete(entity);\n }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1793/"
] |
14,828 |
<p>I work on quite a few DotNetNuke sites, and occasionally (I haven't figured out the common factor yet), when I use the Database Publishing Wizard from Microsoft to create scripts for the site I've created on my Dev server, after running the scripts at the host (usually GoDaddy.com), and uploading the site files, I get an error... I'm 99.9% sure that it's not file related, so not sure where to begin in the DB. Unfortunately with DotNetNuke you don't get the YSOD, but a generic error, with no real way to find the actual exception that has occured.</p>
<p>I'm just curious if anyone has had similar deployment issues using the Database Publishing Wizard, and if so, how they overcame them? I own the RedGate toolset, but some hosts like GoDaddy don't allow you to direct connect to their servers...</p>
|
[
{
"answer_id": 16369,
"author": "Ian Robinson",
"author_id": 326,
"author_profile": "https://Stackoverflow.com/users/326",
"pm_score": 0,
"selected": false,
"text": "customErrors mode=\"Off\"\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1795/"
] |
14,857 |
<p><strong>Bounty:</strong> I will send $5 via paypal for an answer that fixes this problem for me.</p>
<p>I'm not sure what VS setting I've changed or if it's a web.config setting or what, but I keep getting this error in the error list and yet all solutions build fine. Here are some examples:</p>
<pre>
Error 5 'CompilerGlobalScopeAttribute' is ambiguous in the namespace 'System.Runtime.CompilerServices'. C:\projects\MyProject\Web\Controls\EmailStory.ascx 609 184 C:\...\Web\
Error 6 'ArrayList' is ambiguous in the namespace 'System.Collections'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 13 28 C:\...\Web\
Error 7 'Exception' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 37 21 C:\...\Web\
Error 8 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 47 64 C:\...\Web\
Error 9 'EventArgs' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 140 72 C:\...\Web\
Error 10 'Array' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\Controls\EmailStory.ascx.vb 147 35 C:\...\Web\
[...etc...]
Error 90 'DateTime' is ambiguous in the namespace 'System'. C:\projects\MyProject\Web\App_Code\XsltHelperFunctions.vb 13 8 C:\...\Web\
</pre>
<p>As you can imagine, it's really annoying since there are blue squiggly underlines everywhere in the code, and filtering out relevant errors in the Error List pane is near impossible. I've checked the default ASP.Net web.config and machine.config but nothing seemed to stand out there.</p>
<hr>
<p><em>Edit:</em> Here's some of the source where the errors are occurring:</p>
<pre><code>'Error #5: whole line is blue underlined'
<%= addEmailToList.ToolTip %>
'Error #6: ArrayList is blue underlined'
Private _emails As New ArrayList()
'Error #7: Exception is blue underlined'
Catch ex As Exception
'Error #8: System.EventArgs is blue underlined'
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Error #9: System.EventArgs is blue underlined'
Protected Sub sendMessage_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles sendMessage.Click
'Error #10: Array is blue underlined'
Me.emailSentTo.Text = Array.Join(";", mailToAddresses)
'Error #90: DateTime is blue underlined'
If DateTime.TryParse(data, dateValue) Then
</code></pre>
<hr>
<p><em>Edit</em>: GacUtil results</p>
<pre>
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\gacutil -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 1.1.4318.0
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
The Global Assembly Cache contains the following assemblies:
The cache of ngen files contains the following entries:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d003700430039004
40037004500430036000000
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c5619
34e089, Custom=5a00410050002d004e0035002e0031002d0038004600440053002d00370043003
900450036003100370035000000
Number of items = 2
</pre>
<pre>
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -l mscorlib
Microsoft (R) .NET Global Assembly Cache Utility. Version 2.0.50727.42
Copyright (c) Microsoft Corporation. All rights reserved.
The Global Assembly Cache contains the following assemblies:
Number of items = 0
</pre>
<hr>
<p><em>Edit</em>: interesting results from ngen:</p>
<pre><code>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 2.0.50727.832
Copyright (C) Microsoft Corporation 1998-2002. All rights reserved.
NGEN Roots:
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
ScenarioDefault
mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, Custom=5a00410050002d004e0035002e0031002d003800460053002d00330037004200430043003300430035000000
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
ScenarioNoDependencies
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
DisplayName = mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Native image = {7681CE0F-F0E7-F03A-2B56-96345589D82B}
Hard Dependencies:
Soft Dependencies:
NGEN Roots that depend on "mscorlib":
[...a bunch of stuff...]
Native Images:
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Source MVID: {D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Source HASH: bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
NGen GUID sign: {7681CE0F-F0E7-F03A-2B56-96345589D82B}
OS: WinNT
Processor: x86(Pentium 4) (features: 00008001)
Runtime: 2.0.50727.832
mscorwks.dll: TimeStamp=461F2E2A, CheckSum=00566DC9
Flags:
Scenarios: <no debug info> <no debugger> <no profiler> <no instrumentation>
Granted set: <PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true"/>
File:
C:\WINDOWS\assembly\NativeImages_v2.0.50727_32\mscorlib\0fce8176e7f03af02b5696345589d82b\mscorlib.ni.dll
Dependencies:
mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
Guid:{D34102CF-2ABF-4004-8B42-2859D8FF27F3}
Sign:bbf5cfc19bea4e13889e39eb1fb72479a45ad0ec
</code></pre>
<p>There should only be one mscorlib in the native images, correct? How can I get rid of the others?</p>
|
[
{
"answer_id": 592331,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "gacutil mscorlib"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
14,872 |
<blockquote>
<p>CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file
C:\Documents and Settings\..\App_Data\HelloWorld.mdf failed.
A database with the same name exists, or specified file cannot be
opened, or it is located on UNC share.</p>
</blockquote>
<p>I've found these links:</p>
<ul>
<li><a href="http://blog.benhall.me.uk/2008/03/sql-server-and-vista-create-database.html" rel="nofollow noreferrer">http://blog.benhall.me.uk/2008/03/sql-server-and-vista-create-database.html</a></li>
<li><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=702726&SiteID=1" rel="nofollow noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=702726&SiteID=1</a></li>
</ul>
|
[
{
"answer_id": 1412028,
"author": "zanona",
"author_id": 165750,
"author_profile": "https://Stackoverflow.com/users/165750",
"pm_score": 2,
"selected": false,
"text": "<system.web>\n <identity impersonate=\"true\" userName=\"admin_user\" password=\"admin_password\" />\n...\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1659/"
] |
14,873 |
<p>I've noticed that a few Wordpress blogs have query statistics present in their footer that simply state the number of queries and the total time required to process them for the particular page, reading something like:</p>
<blockquote>
<p>23 queries. 0.448 seconds</p>
</blockquote>
<p>I was wondering how this is accomplished. Is it through the use of a particular Wordpress plug-in or perhaps from using some particular php function in the page's code?</p>
|
[
{
"answer_id": 14972,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 5,
"selected": true,
"text": "<?php echo $wpdb->num_queries; ?> <?php _e('queries'); ?>. <?php timer_stop(1); ?> <?php _e('seconds'); ?>\n"
},
{
"answer_id": 15386,
"author": "Carl Russmann",
"author_id": 1347,
"author_profile": "https://Stackoverflow.com/users/1347",
"pm_score": 3,
"selected": false,
"text": "$wpdb->num_queries _e timer_stop()"
},
{
"answer_id": 23636709,
"author": "Manoj H L",
"author_id": 2095317,
"author_profile": "https://Stackoverflow.com/users/2095317",
"pm_score": 1,
"selected": false,
"text": "get_num_queries() timer_stop() <?php echo get_num_queries(); _e(' queries'); ?> in <?php timer_stop(1); _e(' seconds'); ?></p>\n get_num_queries()"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] |
14,874 |
<p>For part of my application I have a need to create an image of a certain view and all of its subviews.</p>
<p>To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.</p>
<p>I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.</p>
|
[
{
"answer_id": 14947,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "-[NSView dataWithPDFInsideRect:] NSData"
},
{
"answer_id": 15489,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 1,
"selected": false,
"text": "-[NSBitmapImageRep initWithFocusedViewRect:]"
},
{
"answer_id": 66556,
"author": "charles",
"author_id": 9900,
"author_profile": "https://Stackoverflow.com/users/9900",
"pm_score": 3,
"selected": true,
"text": "[self drawRect:[self bounds]] imageWithSubviews - (void)drawSubviews\n{\n BOOL flipped = [self isFlipped];\n\n for ( NSView *subview in [self subviews] ) {\n\n // changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)\n // the transform assumes bounds and frame have the same size, and bounds origin is (0,0)\n // handling of 'isFlipped' also probably unreliable\n NSAffineTransform *transform = [NSAffineTransform transform];\n if ( flipped ) {\n [transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];\n [transform scaleXBy:+1.0 yBy:-1.0];\n } else\n [transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];\n [transform concat];\n\n // recursively draw the subview and sub-subviews\n [subview drawRect:[subview bounds]];\n [subview drawSubviews];\n\n // reset the transform to get back a clean graphic contexts for the rest of the drawing\n [transform invert];\n [transform concat];\n }\n}\n\n- (NSImage *)imageWithSubviews\n{\n NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];\n [image lockFocus];\n // it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)\n // Use instead an NSAffineTransform\n if ( [self isFlipped] ) {\n NSAffineTransform *transform = [NSAffineTransform transform];\n [transform translateXBy:0 yBy:NSMaxY(self.bounds)];\n [transform scaleXBy:+1.0 yBy:-1.0];\n [transform concat];\n }\n [self drawSubviews];\n [image unlockFocus];\n return image;\n}\n"
},
{
"answer_id": 71696,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "NSGraphicsContext *bitmapGraphicsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:cacheBitmapImageRep];\n[NSGraphicsContext saveGraphicsState];\n[NSGraphicsContext setCurrentContext:bitmapGraphicsContext];\n[[NSColor clearColor] set];\nNSRectFill(NSMakeRect(0, 0, [cacheBitmapImageRep size].width, [cacheBitmapImageRep size].height));\n[NSGraphicsContext restoreGraphicsState];\n -[NSView cacheDisplayInRect:toBitmapImageRep:]\n -[NSView displayRectIgnoringOpacity:inContext:]\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043/"
] |
14,893 |
<p>Or, actually establishing a build process when there isn't much of one in place to begin with.</p>
<p>Currently, that's pretty much the situation my group faces. We do web-app development primarily (but no desktop development at this time). Software deployments are ugly and unwieldy even with our modest apps, and we've had far too many issues crop up in the two years I have been a part of this team (and company). It's past time to do something about that, and the upshot is that we'll be able to kill two Joel Test birds with one stone (daily builds and one-step builds, neither of which exists in any form whatsoever).</p>
<p>What I'm after here is some general insight on the kinds of things I need to be doing or thinking about, from people who have been in software development for longer than I have and also have bigger brains. I'm confident that will be most of the people currently posting in the beta.</p>
<p>Relevant Tools:
Visual Build
Source Safe 6.0 (I know, but I can't do anything about whether or not we use Source Safe at this time. That might be the next battle I fight.)</p>
<p>Tentatively, I've got a Visual Build project that does this:</p>
<ol>
<li>Get source and place in local directory, including necessary DLLs needed for project.</li>
<li>Get config files and rename as needed (we're storing them in a special sub directory that isn't part of the actual application, and they are named according to use).</li>
<li>Build using Visual Studio</li>
<li>Precompile using command line, copying into what will be a "build" directory</li>
<li>Copy to destination.</li>
<li>Get any necessary additional resources - mostly things like documents, images, and reports that are associated with the project (and put into directory from step 5). There's a lot of this stuff, and I didn't want to include it previously. However, I'm going to only copy changed items, so maybe it's irrelevant. I wasn't sure whether I really wanted to include this stuff in earlier steps.</li>
</ol>
<p>I still need to coax some logging out of Visual Build for all of this, but I'm not at a point where I need to do that yet.</p>
<p>Does anyone have any advice or suggestions to make? We're not currently using a Deployment Project, I'll note. It would remove some of the steps necessary in this build I presume (like web.config swapping).</p>
|
[
{
"answer_id": 14903,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<appSettings file=\"Local.config\">\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1734/"
] |
14,923 |
<p>I'm thinking of learning the <code>ASP.NET MVC</code> framework for an upcoming project. Can I use the advanced routing to create long URLs based on the sitemap hierarchy?</p>
<p>Example navigation path:</p>
<p><strong>Home > Shop > Products > Household > Kitchen > Cookware > Cooksets > Nonstick</strong></p>
<p>Typical (I think) MVC URL:<br/>
<a href="http://example.com/products/category/NonstickCooksets" rel="nofollow noreferrer">http://example.com/products/category/NonstickCooksets</a></p>
<p>Desired URL:<br/>
<a href="http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick" rel="nofollow noreferrer">http://example.com/shop/products/household/kitchen/cookware/cooksets/nonstick</a></p>
<p>Can I do this?</p>
|
[
{
"answer_id": 36833,
"author": "Andrei Rînea",
"author_id": 1796,
"author_profile": "https://Stackoverflow.com/users/1796",
"pm_score": 4,
"selected": true,
"text": "public class ShopController : Controller\n{\n...\n public ActionResult Products(string categoryPath)\n {\n // the categoryPath value would be\n // \"household/kitchen/cookware/cooksets/nonstick\". Process it (for ex. split it)\n // and then decide what you do..\n return View();\n }\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
14,934 |
<p>.NET, Java and other high level database API's in various language often provide techniques known as prepared statements and parameter binding as opposed to sending plain text commands to the Database server. What I would like to know is what happens when you execute a statement like this:</p>
<pre><code>SqlCommand cmd = new SqlCommand("GetMemberByID");
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = new SqlParameter("@ID", memberID);
para.DbType = DbType.Integer;
cmd.Parameters.Add(param);
</code></pre>
<p>I know this is a best practice. SQL injection attacks are minimized this way. But what exactly happens under the hood when you execute these statements? Is the end result still a SQL safe string? If not, what is the end result? And is this enough to prevent SQL injection attacks?</p>
|
[
{
"answer_id": 14986,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "string sql = \"SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did\";\nDatabase db = DatabaseFactory.CreateDatabase();\nusing(DbCommand cmd = db.GetSqlStringCommand(sql))\n{\n db.AddInParameter(cmd, \"DomName\", DbType.String, \"xxxxx.net\");\n db.AddInParameter(cmd, \"Did\", DbType.Int32, 500204);\n\n DataSet ds = db.ExecuteDataSet(cmd);\n}\n exec sp[underscore]executesql N'SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did',\n N'@DomName nvarchar(9),\n @Did int',\n @DomName=N'xxxxx.net',\n @Did=500204\n db.AddInParameter(cmd, \"DomName\", DbType.String, \"'xxxxx.net\");\n\nexec sp[underscore]executesql N'SELECT * FROM tblDomains WHERE DomainName = @DomName AND DomainID = @Did',\n N'@DomName nvarchar(10),\n @Did int',\n @DomName=N'''xxxxx.net',\n @Did=500204\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
14,943 |
<p>What is the best way to disable <kbd>Alt</kbd> + <kbd>F4</kbd> in a c# win form to prevent the user from closing the form?</p>
<p>I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.</p>
|
[
{
"answer_id": 14949,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 4,
"selected": false,
"text": "FormClosing FormClosingEventArgs.Cancel true"
},
{
"answer_id": 14960,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 8,
"selected": true,
"text": "private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n e.Cancel = true;\n}\n this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);\nthis.Close();\n"
},
{
"answer_id": 49349,
"author": "Matt Warren",
"author_id": 4500,
"author_profile": "https://Stackoverflow.com/users/4500",
"pm_score": 6,
"selected": false,
"text": "FormClosingEventArgs e.CloseReason"
},
{
"answer_id": 428005,
"author": "antsyawn",
"author_id": 53324,
"author_profile": "https://Stackoverflow.com/users/53324",
"pm_score": 5,
"selected": false,
"text": "protected override void OnFormClosing(FormClosingEventArgs e)\n{\n switch (e.CloseReason)\n {\n case CloseReason.UserClosing:\n e.Cancel = true;\n break;\n }\n\n base.OnFormClosing(e);\n}\n"
},
{
"answer_id": 15216009,
"author": "linquize",
"author_id": 1031218,
"author_profile": "https://Stackoverflow.com/users/1031218",
"pm_score": 2,
"selected": false,
"text": "private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n e.Cancel = e.CloseReason == CloseReason.UserClosing;\n}\n"
},
{
"answer_id": 37909195,
"author": "Bharath theorare",
"author_id": 2700841,
"author_profile": "https://Stackoverflow.com/users/2700841",
"pm_score": -1,
"selected": false,
"text": "this.ControlBox = false;\n"
},
{
"answer_id": 47331474,
"author": "Brahim Bourass",
"author_id": 8947184,
"author_profile": "https://Stackoverflow.com/users/8947184",
"pm_score": 3,
"selected": false,
"text": "private void test_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4) \n { \n e.Cancel = true; \n } \n}\n"
},
{
"answer_id": 50615223,
"author": "Condorkunka",
"author_id": 5999286,
"author_profile": "https://Stackoverflow.com/users/5999286",
"pm_score": 2,
"selected": false,
"text": "bool myButtonWasClicked = false;\nprivate void Exit_Click(object sender, EventArgs e)\n{\n myButtonWasClicked = true;\n Application.Exit();\n}\nprivate void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n if (myButtonWasClicked)\n {\n e.Cancel = false;\n }\n else\n {\n e.Cancel = true;\n }\n\n\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1375/"
] |
14,967 |
<p>I'm a recent AI graduate (circa 2 years) working for a modest operation. It has fallen to me (primarily as I'm the first 'adopter' in the department) to create a basic (read useful?) C# coding standards document. </p>
<p>I think I should explain that I'm probably the most junior software engineer going, but I'm looking forward to this task as hopefully I might actually be able to produce something half usable. I've done a pretty extensive search of the Internet and read articles on what a coding standards document should / should not contain. This seems like a good as place as any to ask for some suggestions.</p>
<p>I realise that I am potentially opening a door to a whole world of disagreement about 'the best way to do things'. I both understand and respect the undeniable fact that each programmer has a preferred method of solving each individual task, as a result I'm not looking to write anything so draconianly proscriptive as to stifle personal flair but to try and get a general methodology and agreed standards (e.g. naming conventions) to help make individuals code more readable.</p>
<p>So here goes .... any suggestions? Any at all?</p>
|
[
{
"answer_id": 6120801,
"author": "Dan Abramov",
"author_id": 458193,
"author_profile": "https://Stackoverflow.com/users/458193",
"pm_score": 0,
"selected": false,
"text": "try\n{\n if (condition)\n {\n Something(new delegate\n {\n SomeCall(a, b);\n });\n }\n else\n {\n SomethingElse();\n Foobar(foo, bar);\n }\n}\ncatch (Exception ex)\n{\n Console.WriteLine(\"Okay, you got me\");\n}\n try {\n if (condition) {\n Something (new delegate {\n SomeCall (a, b);\n });\n } else {\n SomethingElse ();\n Foobar (foo, bar);\n }\n} catch (Exception ex) {\n Console.WriteLine (\"Okay, you got me\");\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/14967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
] |
15,023 |
<p>In WindowsForms world you can get a list of available image encoders/decoders with</p>
<pre><code>System.Drawing.ImageCodecInfo.GetImageDecoders() / GetImageEncoders()
</code></pre>
<p>My question is, is there a way to do something analogous for the WPF world that would allow me to get a list of available </p>
<pre><code>System.Windows.Media.Imaging.BitmapDecoder / BitmapEncoder
</code></pre>
|
[
{
"answer_id": 17448,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "Bitmap Encoders:\nSystem.Windows.Media.Imaging.BmpBitmapEncoder\nSystem.Windows.Media.Imaging.GifBitmapEncoder\nSystem.Windows.Media.Imaging.JpegBitmapEncoder\nSystem.Windows.Media.Imaging.PngBitmapEncoder\nSystem.Windows.Media.Imaging.TiffBitmapEncoder\nSystem.Windows.Media.Imaging.WmpBitmapEncoder\n\nBitmap Decoders:\nSystem.Windows.Media.Imaging.BmpBitmapDecoder\nSystem.Windows.Media.Imaging.GifBitmapDecoder\nSystem.Windows.Media.Imaging.IconBitmapDecoder\nSystem.Windows.Media.Imaging.LateBoundBitmapDecoder\nSystem.Windows.Media.Imaging.JpegBitmapDecoder\nSystem.Windows.Media.Imaging.PngBitmapDecoder\nSystem.Windows.Media.Imaging.TiffBitmapDecoder\nSystem.Windows.Media.Imaging.WmpBitmapDecoder\n System.Windows.Media.Imaging.LateBoundBitmapDecoder\n CodecInfo using System;\nusing System.Linq;\nusing System.Collections.Generic;\nusing System.Reflection;\nusing System.Windows.Media.Imaging;\n\nnamespace Codecs {\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(\"Bitmap Encoders:\");\n AllEncoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));\n Console.WriteLine(\"\\nBitmap Decoders:\");\n AllDecoderTypes.ToList().ForEach(t => Console.WriteLine(t.FullName));\n Console.ReadKey();\n }\n\n static IEnumerable<Type> AllEncoderTypes {\n get {\n return AllSubclassesOf(typeof(BitmapEncoder));\n }\n }\n\n static IEnumerable<Type> AllDecoderTypes {\n get {\n return AllSubclassesOf(typeof(BitmapDecoder));\n }\n }\n\n static IEnumerable<Type> AllSubclassesOf(Type type) {\n var r = new Reflector();\n // Add additional assemblies here\n return r.AllSubclassesOf(type);\n }\n }\n\n class Reflector {\n List<Assembly> assemblies = new List<Assembly> { \n typeof(BitmapDecoder).Assembly\n };\n public IEnumerable<Type> AllSubclassesOf(Type super) {\n foreach (var a in assemblies) {\n foreach (var t in a.GetExportedTypes()) {\n if (t.IsSubclassOf(super)) {\n yield return t;\n }\n }\n }\n }\n }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
15,024 |
<p>Questions #1 through #4 on the <a href="http://www.joelonsoftware.com/articles/fog0000000043.html" rel="nofollow noreferrer">Joel Test</a> in my opinion are all about the development tools being used and the support system in place for developers:</p>
<ol>
<li>Do you use source control? </li>
<li>Can you make a build in one step? </li>
<li>Do you make daily builds? </li>
<li>Do you have a bug database? </li>
</ol>
<p>I'm just curious what free/cheap (but good) tools exist for the small development shops that don't have large bank accounts to use to achieve a positive answer on these questions.</p>
<p>For source control I know Subversion is a great solution, and if you are a one man shop you could even use SourceGear's <a href="http://www.sourcegear.com/vault/index.html" rel="nofollow noreferrer">Vault</a>.</p>
<p>I use NAnt for my larger projects, but have yet to set up a script to build my installers as well as running the obfusication tools all as a single step. Any other suggestions?</p>
<p>If you can answer yes to the building in a single step, I think creating daily builds would be easy, but what tools would you recommend for automating those daily builds?</p>
<p>For a one or two man team, it's already been discussed on SO that you can use FogBugz On Demand, but what other bug tracking solutions exist for small teams?</p>
|
[
{
"answer_id": 904897,
"author": "Jonas Kölker",
"author_id": 58668,
"author_profile": "https://Stackoverflow.com/users/58668",
"pm_score": 2,
"selected": false,
"text": "$(apt-cache search bug tracking)"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1795/"
] |
15,034 |
<p>When building a VS 2008 solution with 19 projects I sometimes get:</p>
<pre><code>The "GenerateResource" task failed unexpectedly.
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.WriteByte(Byte value)
at System.IO.BinaryWriter.Write(Byte value)
at System.Resources.ResourceWriter.Write7BitEncodedInt(BinaryWriter store, Int32 value)
at System.Resources.ResourceWriter.Generate()
at System.Resources.ResourceWriter.Dispose(Boolean disposing)
at System.Resources.ResourceWriter.Close()
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile, String outFile)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log, ITaskItem[] assemblyFilesList, ArrayList inputs, ArrayList outputs, Boolean sourcePath, String language, String namespacename, String resourcesNamespace, String filename, String classname, Boolean publicClass)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BuildEngine.TaskEngine.ExecuteInstantiatedTask(EngineProxy engineProxy, ItemBucket bucket, TaskExecutionMode howToExecuteTask, ITask task, Boolean& taskResult) C:\Windows\Microsoft.NET\Framework\v3.5
</code></pre>
<p>Usually happens after VS has been running for about 4 hours; the only way to get VS to compile properly is to close out VS, and start it again.</p>
<p>I'm on a machine with 3GB Ram. TaskManager shows the devenv.exe working set to be 578060K, and the entire memory allocation for the machine is 1.78GB. It should have more than enough ram to generate the resources.</p>
|
[
{
"answer_id": 8679710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<GenerateResourceNeverLockTypeAssemblies>true</GenerateResourceNeverLockTypeAssemblies>\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1365/"
] |
15,040 |
<p>I am using xampp on Windows, but I would like to use something closer to my server setup.</p>
<p><a href="http://phpimpact.wordpress.com/2008/05/24/virtual-appliances-lamp-development-made-easy/" rel="nofollow noreferrer">Federico Cargnelutti tutorial</a> explains how to setup LAMP VMWARE appliance; it is a great introduction to VMware appliances, but one of the commands was not working and it doesn't describe how to change the keyboard layout and the timezone.</p>
<p>ps: the commands are easy to find but I don't want to look for them each time I reinstall the server. I am using this question as a reminder.</p>
|
[
{
"answer_id": 15683,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 4,
"selected": true,
"text": "apt-get -yq update\napt-get -yq upgrade\napt-get -yq install sudo\napt-get -yq install gcc\napt-get -yq install g++\napt-get -yq install make\napt-get -yq install apache2\napt-get -yq install php5\napt-get -yq install php5-curl\napt-get -yq install php5-mysql\napt-get -yq install php5-gd\napt-get -yq install mysql-common\napt-get -yq install mysql-client\napt-get -yq install mysql-server\napt-get -yq install phpmyadmin\napt-get -yq install samba\necho '[global]\n workgroup = workgroup\n server string = %h server\n dns proxy = no\n log file = /var/log/samba/log.%m\n max log size = 1000\n syslog = 0\n panic action = /usr/share/samba/panic-action %d\n encrypt passwords = true\n passdb backend = tdbsam\n obey pam restrictions = yes\n ;invalid users = root\n unix password sync = no\n passwd program = /usr/bin/passwd %u\n passwd chat = *Enter\\snew\\sUNIX\\spassword:* %n\\n *Retype\\snew\\sUNIX\\spassword:* %n\\n *password\\supdated\\ssuccessfully* .\n socket options = TCP_NODELAY\n[homes]\n comment = Home Directories\n browseable = no\n writable = no\n create mask = 0700\n directory mask = 0700\n valid users = %S\n[www]\n comment = WWW\n writable = yes\n locking = no\n path = /var/www\n public = yes' > /etc/samba/smb.conf\n(echo SAMBAPASSWORD; echo SAMBAPASSWORD) | smbpasswd -sa root\necho 'NameVirtualHost *\n<VirtualHost *>\n ServerAdmin webmaster@localhost\n DocumentRoot /var/www/\n <Directory />\n Options FollowSymLinks\n AllowOverride None\n </Directory>\n <Directory /var/www/>\n Options Indexes FollowSymLinks MultiViews\n AllowOverride None\n Order allow,deny\n allow from all\n </Directory>\n ErrorLog /var/log/apache2/error.log\n LogLevel warn\n CustomLog /var/log/apache2/access.log combined\n ServerSignature On\n</VirtualHost>' > /etc/apache2/sites-enabled/000-default\n/etc/init.d/apache2 stop\n/etc/init.d/samba stop\n/etc/init.d/apache2 start\n/etc/init.d/samba start\n /etc/init.d/mysql stop\necho \"UPDATE mysql.user SET Password=PASSWORD('MySQLPasswrod') WHERE User='root'; FLUSH PRIVILEGES;\" > /root/MySQLPassword\nmysqld_safe --init-file=/root/MySQLPassword &\nsleep 1\n/etc/init.d/mysql stop\nsleep 1\n/etc/init.d/mysql start\n chmod +x install\n./install\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1771/"
] |
15,047 |
<p>I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.</p>
<p>From what I've read this type of action could be handled by the <a href="http://www.dofactory.com/Patterns/PatternCommand.aspx" rel="noreferrer">Command design pattern</a> with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.</p>
<p>I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared?</p>
|
[
{
"answer_id": 15207,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 5,
"selected": true,
"text": "public interface ICommand\n{\n void Execute();\n}\n public class CutCommand : ICommand\n{\n public void Execute()\n {\n // Put code you like to execute when the CutCommand.Execute method is called.\n }\n}\n public class TextOperations\n{\n public void Invoke(ICommand command)\n {\n command.Execute();\n }\n}\n public class Client\n{\n static void Main()\n {\n TextOperations textOperations = new TextOperations();\n textOperation.Invoke(new CutCommand());\n }\n}\n"
},
{
"answer_id": 34513005,
"author": "Dzianis Yafimau",
"author_id": 3877717,
"author_profile": "https://Stackoverflow.com/users/3877717",
"pm_score": 0,
"selected": false,
"text": "public interface ICommand {\n void Do();\n void Undo();\n}\n public abstract class WinFormCommand : ICommand {\n\n}\n public interface ICommandInvoker {\n void Invoke(ICommand command);\n void ReDo();\n void UnDo();\n}\n\npublic interface ICommandDirector {\n void Enable(ICommand);\n void Disable(ICommand);\n}\n\npublic class WinFormsCommandInvoker : ICommandInvoker, ICommandDirector {\n\n private readonly Dictionary<ICommand, bool> _commands;\n private readonly Queue<ICommand> _commandsQueue; \n private readonly IButtonDirector _buttonDirector;\n\n // you can define additional queue for support of ReDo operation\n\n public WinFormsCommandInvoker(ICommandsBuilder builder, IButtonDirector buttonDirector) {\n _commands = builder.Build();\n _buttonDirector = buttonDirector;\n _commandsQueue = new Queue<ICommand>();\n } \n\n public void Invoke(ICommand command) {\n command.Do();\n __commandsQueue.Enqueue(command);\n }\n\n public void ReDo() {\n //you can implement this using additional queue\n }\n\n public void UnDo() {\n var command = __commandsQueue.Dequeue();\n command.Undo();\n }\n\n public void Enable(ICommand command) {\n _commands.[command] = true;\n _buttonDirector.Enable(command);\n }\n\n public void Disable(ICommand command) {\n _commands.[command] = false;\n _buttonDirector.Disable(command); \n }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1752/"
] |
15,056 |
<p>What are some macros that you have found useful in Visual Studio for code manipulation and automation? </p>
|
[
{
"answer_id": 15113,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "''''replaceunicodechars.vb\nOption Strict Off\nOption Explicit Off\nImports EnvDTE\nImports System.Diagnostics\n\nPublic Module ReplaceUnicodeChars\n\n Sub ReplaceUnicodeChars()\n DTE.ExecuteCommand(\"Edit.Find\")\n ReplaceAllChar(ChrW(8230), \"…\") ' ellipses\n ReplaceAllChar(ChrW(8220), \"“\") ' left double quote\n ReplaceAllChar(ChrW(8221), \"”\") ' right double quote\n ReplaceAllChar(ChrW(8216), \"‘\") ' left single quote\n ReplaceAllChar(ChrW(8217), \"’\") ' right single quote\n ReplaceAllChar(ChrW(8211), \"–\") ' en dash\n ReplaceAllChar(ChrW(8212), \"—\") ' em dash\n ReplaceAllChar(ChrW(176), \"°\") ' °\n ReplaceAllChar(ChrW(188), \"¼\") ' ¼\n ReplaceAllChar(ChrW(189), \"½\") ' ½\n ReplaceAllChar(ChrW(169), \"©\") ' ©\n ReplaceAllChar(ChrW(174), \"®\") ' ®\n ReplaceAllChar(ChrW(8224), \"†\") ' dagger\n ReplaceAllChar(ChrW(8225), \"‡\") ' double-dagger\n ReplaceAllChar(ChrW(185), \"¹\") ' ¹\n ReplaceAllChar(ChrW(178), \"²\") ' ²\n ReplaceAllChar(ChrW(179), \"³\") ' ³\n ReplaceAllChar(ChrW(153), \"™\") ' ™\n ''ReplaceAllChar(ChrW(0), \"�\")\n\n DTE.Windows.Item(Constants.vsWindowKindFindReplace).Close()\n End Sub\n\n Sub ReplaceAllChar(ByVal findWhat, ByVal replaceWith)\n DTE.Find.FindWhat = findWhat\n DTE.Find.ReplaceWith = replaceWith\n DTE.Find.Target = vsFindTarget.vsFindTargetCurrentDocument\n DTE.Find.MatchCase = False\n DTE.Find.MatchWholeWord = False\n DTE.Find.MatchInHiddenText = True\n DTE.Find.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral\n DTE.Find.ResultsLocation = vsFindResultsLocation.vsFindResultsNone\n DTE.Find.Action = vsFindAction.vsFindActionReplaceAll\n DTE.Find.Execute()\n End Sub\n\nEnd Module\n"
},
{
"answer_id": 32884,
"author": "John Richardson",
"author_id": 887,
"author_profile": "https://Stackoverflow.com/users/887",
"pm_score": 3,
"selected": false,
"text": "Sub UpdateIntellisense()\n Dim solution As Solution = DTE.Solution\n Dim filename As String = solution.FullName\n Dim ncbFile As System.Text.StringBuilder = New System.Text.StringBuilder\n ncbFile.Append(System.IO.Path.GetDirectoryName(filename) + \"\\\")\n ncbFile.Append(System.IO.Path.GetFileNameWithoutExtension(filename))\n ncbFile.Append(\".ncb\")\n solution.Close(True)\n System.IO.File.Delete(ncbFile.ToString())\n solution.Open(filename)\nEnd Sub\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] |
15,062 |
<p>How do I convert function input parameters to the right type?</p>
<p>I want to return a string that has part of the URL passed into it removed.</p>
<p><strong>This works, but it uses a hard-coded string:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = "http://google.com".Replace("http://", "")
return $x
}
$SiteName = CleanUrl($HostHeader)
echo $SiteName
</code></pre>
<p><strong>This fails:</strong></p>
<pre><code>function CleanUrl($input)
{
$x = $input.Replace("http://", "")
return $x
}
Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'.
At M:\PowerShell\test.ps1:13 char:21
+ $x = $input.Replace( <<<< "http://", "")
</code></pre>
|
[
{
"answer_id": 15068,
"author": "ESV",
"author_id": 150,
"author_profile": "https://Stackoverflow.com/users/150",
"pm_score": 3,
"selected": false,
"text": "function CleanUrl([string] $url)\n{\n return $url.Replace(\"http://\", \"\")\n}\n"
},
{
"answer_id": 15094,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": -1,
"selected": false,
"text": "function CleanUrl($input)\n{\n return $input.Replace(\"http://\", \"\")\n}\n"
},
{
"answer_id": 15136,
"author": "Steven Murawski",
"author_id": 1233,
"author_profile": "https://Stackoverflow.com/users/1233",
"pm_score": 5,
"selected": true,
"text": "function CleanUrl($url)\n{\n return $url -replace 'http://'\n}\n"
},
{
"answer_id": 68811,
"author": "Jaykul",
"author_id": 8718,
"author_profile": "https://Stackoverflow.com/users/8718",
"pm_score": 4,
"selected": false,
"text": "$input function CleanUrl([string]$url)\n{\n $url.Replace(\"http://\",\"\")\n}\n function CleanUrl([string]$url)\n{\n $url -replace \"http://\",\"\"\n}\n $HostHeader = \"http://google.com\"\n$SiteName = CleanUrl $HostHeader\nWrite-Host $SiteName\n function CleanUrls\n{\n $input -replace \"http://\",\"\"\n}\n\n# Notice these are arrays ...\n$HostHeaders = @(\"http://google.com\",\"http://stackoverflow.com\")\n$SiteNames = $HostHeader | CleanUrls\nWrite-Output $SiteNames\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] |
15,066 |
<p>I have a form in C# that has a button that, when clicked, I want the background image to cycle through a set of images (which I have as resources to the project). The images are named '_1', '_2', etc. and each time I click the button I want its background image to increment to the next one and go back to "_1" when it gets to the highest. Is there a way to do this?</p>
<p>I tried getting <code>button1.BackgroundImage.ToString()</code> but that yields <code>System.Drawing.Bitmap</code> instead of <code>Resources._1</code> like I was thinking it would (in which case I could just get the last character and switch on that to change the background to the appropriate new image).</p>
<p>Thanks for your help.</p>
|
[
{
"answer_id": 12660196,
"author": "zahir",
"author_id": 311618,
"author_profile": "https://Stackoverflow.com/users/311618",
"pm_score": 0,
"selected": false,
"text": "class YourClass\n{\n private IEnumerator<Image> enumerator;\n\n YourClass(IEnumerable<Image> images)\n {\n enumerator = (from i in Enumerable.Range(0, int.Max)\n from image in images\n select image).GetEnumerator();\n enumerator.MoveNext();\n }\n\n public Image CurrentImage { get { return enumerator.Current; } }\n\n public void OnButtonClick() { enumerator.MoveNext(); }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271/"
] |
15,087 |
<p>The company I work for has an old Access 2000 application that was using a SQL Server 2000 back-end. We were tasked with moving the back-end to a SQL Server 2005 database on a new server. Unfortunately, the application was not functioning correctly while trying to do any inserts or updates. My research has found many forum posts that Access 2000 -> SQL 2005 is not supported by Microsoft, but I cannot find any Microsoft documentation to verify that. </p>
<p>Can anyone either link me to some official documentation, or has anyone used this setup and can confirm that this should be working and our problems lie somewhere else?</p>
<p>Not sure if it matters, but the app is an ADP compiled into an ADE. </p>
|
[
{
"answer_id": 15101,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 0,
"selected": false,
"text": "EXEC sp_dbcmptlevel Name_of_your_database, 80;\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1749/"
] |
15,109 |
<p>I have a setup project created by Visual Studio 2005, and consists of both a C# .NET 2.0 project and C++ MFC project, and the C++ run time. It works properly when run from the main console, but when run over a Terminal Server session on a Windows XP target, the install fails in the following way -
When the Setup.exe is invoked, it immediately crashes before the first welcome screen is displayed. When invoked over a physical console, the setup runs normally.</p>
<p>I figured I could go back to a lab machine to debug, but it runs fine on a lab machine over Terminal Server.</p>
<p>I see other descriptions of setup problems over Terminal Server sessions, but I don't see a definite solution. Both machines have a nearly identical configuration except that the one that is failing also has the GoToMyPC Host installed.</p>
<p>Has anyone else seen these problems, and how can I troubleshoot this?</p>
<p>Thanks,</p>
|
[
{
"answer_id": 15286,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": true,
"text": "%TEMP% %TEMP% 1 2"
},
{
"answer_id": 289025,
"author": "saschabeaumont",
"author_id": 592,
"author_profile": "https://Stackoverflow.com/users/592",
"pm_score": 1,
"selected": false,
"text": "CHANGE USER /INSTALL\n CHANGE USER /EXECUTE\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743/"
] |
15,142 |
<p>What are the advantages/disadvantages of keeping SQL in your C# source code or in Stored Procs? I've been discussing this with a friend on an open source project that we're working on (C# ASP.NET Forum). At the moment, most of the database access is done by building the SQL inline in C# and calling to the SQL Server DB. So I'm trying to establish which, for this particular project, would be best.</p>
<p>So far I have:</p>
<p>Advantages for in Code:</p>
<ul>
<li>Easier to maintain - don't need to run a SQL script to update queries</li>
<li>Easier to port to another DB - no procs to port</li>
</ul>
<p>Advantages for Stored Procs:</p>
<ul>
<li>Performance</li>
<li>Security</li>
</ul>
|
[
{
"answer_id": 229708,
"author": "huo73",
"author_id": 15657,
"author_profile": "https://Stackoverflow.com/users/15657",
"pm_score": 6,
"selected": false,
"text": "(Pseudocode)\n\nFunction createOrder(Order yourOrder) \nBegin\n Call SP_createOrder(yourOrder)\nEnd\n"
},
{
"answer_id": 966585,
"author": "Justin",
"author_id": 113141,
"author_profile": "https://Stackoverflow.com/users/113141",
"pm_score": -1,
"selected": false,
"text": "SELECT MyColumn FROM MyTable WHERE id = @id\nselect MyColumn from MyTable WHERE id = @id\nSELECT MyColumn FROM MyTable WHERE id = @id\nSELECT MyColumn FROM MyTable WHERE id = @id -- \"some comment\"\nSELECT MyColumn FROM MyTable WHERE id = @id -- \"some other comment\"\n"
},
{
"answer_id": 2996041,
"author": "SiN",
"author_id": 339423,
"author_profile": "https://Stackoverflow.com/users/339423",
"pm_score": 2,
"selected": false,
"text": "\"EXEC SPNAME\""
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
15,163 |
<p>In some VB6 code, I have a handler for a TreeView's Collapse event:</p>
<pre><code>Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)
</code></pre>
<p>This is called whenever a node in the tree is collapsed, whether by the user or programmatically. As it turns out, through some roundabout execution, it may happen that this handler will wind up telling a node to collapse, leading to infinite recursion.</p>
<p>I can think of multiple ways to skin this cat, but what seems simplest to me is to tell the TreeView not to raise events for some period of time. I can't find a simple call to let me do this, though. Has anyone successfully done this, or do I need to keep track of state in some other manner so I can respond appropriately when recursive events come along?</p>
|
[
{
"answer_id": 16629,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "MyTree_Collapse m_bHandlingCallback Private Sub MyTree_Collapse(ByVal Node as MSComCtlLib.Node)\n If m_bHandlingCallback Then Exit Sub\n\n m_bHandlingCallback = True\n DoSomeStuff\n m_bHandlingCallback = False\nEnd Sub\n"
},
{
"answer_id": 1813531,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "WithEvents Private WithEvents alt as TreeView\n Form_Load Private Sub Form_Load()\nSet alt = MyTree\nEnd Sub\n alt Private Sub alt_Collapse(ByVal Node as MSComCtlLib.Node)\nSet alt = Nothing\n'DoSomeStuff'\nSet alt = MyTree\nEnd Sub\n DoSomeStuff Sub alt"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863/"
] |
15,171 |
<p>In the linux file system, where should user scripts be placed?</p>
<p>I'm thinking specifically python scripts to be called by cron.</p>
|
[
{
"answer_id": 15476,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "/home/username/.bin\n"
},
{
"answer_id": 1759292,
"author": "pete",
"author_id": 214121,
"author_profile": "https://Stackoverflow.com/users/214121",
"pm_score": 2,
"selected": false,
"text": "/usr/local/bin $HOME/.scripts"
},
{
"answer_id": 7989517,
"author": "c33s",
"author_id": 590247,
"author_profile": "https://Stackoverflow.com/users/590247",
"pm_score": 6,
"selected": true,
"text": "/usr/local/sbin custom script meant for root\n/usr/local/bin custom script meant for all users including non-root\n (02:48:49) c33s: question: where is the _correct_ location, to put custom scripts\nfor the root user (like a script on a webserver for createing everything needed \nfor a new webuser)? is it /bin, /usr/local/bin,...? /usr/local/scripts is \nmentioned in (*link to this page*)\n(02:49:15) Hydroxide: c33s: typically /usr/local/sbin\n(02:49:27) Hydroxide: c33s: no idea what /usr/local/scripts would be\n(02:49:32) Hydroxide: it's nonstandard\n(02:49:53) Hydroxide: if it's a custom script meant for all users including \nnon-root, then /usr/local/bin\n(02:52:43) Hydroxide: c33s: Debian follows the Filesystem Hierarchy Standard, \nwith a very small number of exceptions, which is online in several formats at \nhttp://www.pathname.com/fhs/ (also linked from http://www.debian.org/devel/ and \nseparately online at http://www.debian.org/doc/packaging-manuals/fhs/fhs-2.3.html)\n(02:53:03) Hydroxide: c33s: if you have the debian-policy package installed, it's \nalso in several formats at /usr/share/doc/debian-policy/fhs/ on your system\n(02:53:37) Hydroxide: c33s: most linux distributions follow that standard, though \nusually less strictly and with more deviations than Debian.\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] |
15,187 |
<p>I'd like to take an existing application (written in OCaml) and create an Emacs "interface" for it (like, for example, the Emacs GDB mode). I would prefer to do this without writing a ton of Lisp code. In MVC terms, I'd like for the View to be Emacs, but for the Model and Controller to remain (primarily) OCaml.</p>
<p>Does anybody know of a way to write Emacs extensions in a language other than Lisp? This could either take the form of bindings to the Emacs extension API in some other language (e.g., making OCaml a first-class Emacs extension language) or an Emacs interaction mode where, for example, the extension has a pipe into which it can write Emacs Lisp expressions and read out result values.</p>
|
[
{
"answer_id": 15260,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "(shell-command-to-string\n \"bash -c \\\"script-to-exec args\\\"\")\n"
},
{
"answer_id": 28643496,
"author": "Erik Kaplun",
"author_id": 247623,
"author_profile": "https://Stackoverflow.com/users/247623",
"pm_score": 2,
"selected": false,
"text": ".ml"
},
{
"answer_id": 34952434,
"author": "AdrieanKhisbe",
"author_id": 1806019,
"author_profile": "https://Stackoverflow.com/users/1806019",
"pm_score": 2,
"selected": false,
"text": "emacs-ffi libffi"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
15,204 |
<p>What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?</p>
|
[
{
"answer_id": 15210,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 6,
"selected": true,
"text": "foreach(ObjectType objectItem in objectTypeList)\n{\n // ...do some stuff\n}\n For Each objectItem as ObjectType in objectTypeList\n 'Do some stuff '\nNext\n"
},
{
"answer_id": 15212,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "for(int i = 0; i < genericList.Count; ++i) \n{\n // Loop body\n}\n foreach(<insertTypeHere> o in genericList)\n{\n // Loop body\n}\n"
},
{
"answer_id": 15218,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 2,
"selected": false,
"text": "For Each tmpObject as ObjectType in ObjectTypeList\n 'Do some stuff '\nNext"
},
{
"answer_id": 15232,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "//C#\nforeach( var item in listVariable) {\n //do stuff\n}\n //C#\nint[] valueTypeArray;\nfor(int i=0; i < valueTypeArray.Length; ++i) {\n int item = valueTypeArray[i];\n //do stuff\n}\n // create a list to test with\nvar theList = Enumerable.Range(0, 100000000).ToList();\n\n// time foreach\nvar sw = Stopwatch.StartNew();\nforeach (var item in theList)\n{\n int inLoop = item;\n}\nConsole.WriteLine(\"list foreach: \" + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\nint cnt = theList.Count;\nfor (int i = 0; i < cnt; i++)\n{\n int inLoop = theList[i];\n}\nConsole.WriteLine(\"list for : \" + sw.Elapsed.ToString());\n\n// now run the same tests, but with an array\nvar theArray = theList.ToArray();\n\nsw.Reset();\nsw.Start();\n\nforeach (var item in theArray)\n{\n int inLoop = item;\n}\nConsole.WriteLine(\"array foreach: \" + sw.Elapsed.ToString());\n\nsw.Reset();\nsw.Start();\n\n// time for\ncnt = theArray.Length;\nfor (int i = 0; i < cnt; i++)\n{\n int inLoop = theArray[i];\n}\nConsole.WriteLine(\"array for : \" + sw.Elapsed.ToString());\n\nConsole.ReadKey();\n list foreach: 00:00:00.5137506\nlist for : 00:00:00.2417709\narray foreach: 00:00:00.1085653\narray for : 00:00:00.0954890\n list foreach: 00:00:01.1289015\nlist for : 00:00:00.9945345\narray foreach: 00:00:00.6405422\narray for : 00:00:00.4913245\n for foreach"
},
{
"answer_id": 15238,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 3,
"selected": false,
"text": "myList<string>().ForEach(\n delegate(string name)\n {\n Console.WriteLine(name);\n });\n myList<string>().ForEach(name => Console.WriteLine(name));\n myList(Of String)().ForEach(Function(name) Console.WriteLine(name))\n public IEnumerable<String> Paths(Func<String> formatter) {\n List<String> paths = new List<String>()\n {\n \"/about\", \"/contact\", \"/services\"\n };\n\n return paths.ForEach(formatter);\n}\n var hostname = \"myhost.com\";\nvar formatter = f => String.Format(\"http://{0}{1}\", hostname, f);\nIEnumerable<String> absolutePaths = Paths(formatter);\n \"http://myhost.com/about\", \"http://myhost.com/contact\""
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1224/"
] |
15,219 |
<p>I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns.</p>
<p>I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this <a href="http://news.infragistics.com/forums/p/9063/45792.aspx" rel="nofollow noreferrer">discussion</a> with no luck.</p>
<p>What I'm doing so far:</p>
<pre><code>col.Type = ColumnType.DropDownList;
col.DataType = "System.String";
col.ValueList = myValueList;
</code></pre>
<p>where <code>myValueList</code> is:</p>
<pre><code>ValueList myValueList = new ValueList();
myValueList.Prompt = "My text prompt";
myValueList.DisplayStyle = ValueListDisplayStyle.DisplayText;
foreach(MyObjectType item in MyObjectTypeCollection)
{
myValueList.ValueItems.Add(item.ID, item.Text); // Note that the ID is a string (not my design)
}
</code></pre>
<p>When I look at the page, I expect to see a drop-down list in the cells for this column, but my columns are empty.</p>
|
[
{
"answer_id": 16347,
"author": "Erick B",
"author_id": 1373,
"author_profile": "https://Stackoverflow.com/users/1373",
"pm_score": 2,
"selected": false,
"text": "UltraWebGrid uwgMyGrid = new UltraWebGrid();\nuwgMyGrid.Columns.Add(\"colTest\", \"Test Dropdown\");\nuwgMyGrid.Columns.FromKey(\"colTest\").Type = ColumnType.DropDownList;\nuwgMyGrid.Columns.FromKey(\"colTest\").ValueList.ValueListItems.Insert(0, \"ONE\", \"Choice 1\");\nuwgMyGrid.Columns.FromKey(\"colTest\").ValueList.ValueListItems.Insert(1, \"TWO\", \"Choice 2\");\n"
},
{
"answer_id": 18507,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": true,
"text": "uwgMyGrid.Columns.FromKey(\"colTest\").AllowUpdate = AllowUpdate.Yes;\n"
},
{
"answer_id": 2681542,
"author": "regor",
"author_id": 322104,
"author_profile": "https://Stackoverflow.com/users/322104",
"pm_score": 0,
"selected": false,
"text": " public void MakeCellValueListDropDownList(UltraWebGrid grid, string columnName, string valueListName, string[] listArray)\n {\n //Set the column to be a dropdownlist\n UltraGridColumn Col = grid.Columns.FromKey(columnName); \n Col.Type = ColumnType.DropDownList;\n Col.DataType = \"System.String\";\n\n try\n {\n ValueList ValList = grid.DisplayLayout.Bands[0].Columns.FromKey(columnName).ValueList;\n ValList.DataSource = listArray;\n foreach (string item in listArray)\n {\n ValList.ValueListItems.Add(item);\n }\n ValList.DataBind();\n }\n catch (ArgumentException)\n {\n\n }\n }\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] |
15,228 |
<p>I'm working on a site which needs to be able to support two or more looks, changable at runtime. I'd hoped to be able to handle the change with a CSS switch, but it looks like I'll need to use a different masterpage for each design.</p>
<p>So, what's the best way to set the masterpage at runtime? Page.MasterPageFile can only be set in the Page.OnPreInit event. It looks like the solutions are to make all my pages inherit from a common base which handles the PreInit event, or to use an HttpModule which does that.</p>
<p>Any advice?</p>
|
[
{
"answer_id": 15242,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "this.Page.MasterPageFile = \"~/default.master\";\n"
},
{
"answer_id": 15274,
"author": "Brian G Swanson",
"author_id": 1795,
"author_profile": "https://Stackoverflow.com/users/1795",
"pm_score": 0,
"selected": false,
"text": "\n<html>\n<head id=\"Head\" runat=\"server\">\n<style id=\"StylePlaceholder\" runat=\"server\" type=\"text/css\"></style>\n</head>\n"
},
{
"answer_id": 578509,
"author": "Paul",
"author_id": 44636,
"author_profile": "https://Stackoverflow.com/users/44636",
"pm_score": 2,
"selected": false,
"text": "Public Module WebFunctions\n\n <System.Runtime.CompilerServices.Extension()> _\n Public Sub SetMaster(ByVal page As Page)\n\n Dim pb As ProfileCommon = DirectCast(HttpContext.Current.Profile, ProfileCommon)\n\n If pb IsNot Nothing Then\n page.MasterPageFile = pb.MasterPage\n End If\n\n End Sub\n\nEnd Module\n Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit\n Me.SetMaster()\n End Sub\n"
},
{
"answer_id": 18512238,
"author": "H.M.",
"author_id": 1218928,
"author_profile": "https://Stackoverflow.com/users/1218928",
"pm_score": 0,
"selected": false,
"text": "public class PageBase : System.Web.UI.Page\n{\n public PageBase()\n {\n this.PreInit += new EventHandler(PageBase_PreInit);\n }\n void PageBase_PreInit(object sender, EventArgs e)\n {\n this.MasterPageFile = \"~/MyMasterPage.Master\";\n }\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
15,240 |
<p>I'd like to make a debug logging function with the same parameters as <code>printf</code>. But one that can be removed by the pre-processor during optimized builds.</p>
<p>For example:</p>
<pre><code>Debug_Print("Warning: value %d > 3!\n", value);
</code></pre>
<p>I've looked at variadic macros but those aren't available on all platforms. <code>gcc</code> supports them, <code>msvc</code> does not.</p>
|
[
{
"answer_id": 15262,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 4,
"selected": false,
"text": "\n int debug_printf( const char *fmt, ... );\n #if defined( DEBUG )\n #define DEBUG_PRINTF(x) debug_printf x\n #else\n #define DEBUG_PRINTF(x)\n #endif\n\n DEBUG_PRINTF(( \"Format string that takes %s %s\\n\", \"any number\", \"of args\" ));\n"
},
{
"answer_id": 15269,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "#include <stdio.h>\n\nvoid XTrace0(LPCTSTR lpszText)\n{\n ::OutputDebugString(lpszText);\n}\n\nvoid XTrace(LPCTSTR lpszFormat, ...)\n{\n va_list args;\n va_start(args, lpszFormat);\n int nBuf;\n TCHAR szBuffer[512]; // get rid of this hard-coded buffer\n nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);\n ::OutputDebugString(szBuffer);\n va_end(args);\n}\n #ifdef _DEBUG\n#define XTRACE XTrace\n#else\n#define XTRACE\n#endif\n"
},
{
"answer_id": 15281,
"author": "hyperlogic",
"author_id": 1841,
"author_profile": "https://Stackoverflow.com/users/1841",
"pm_score": 3,
"selected": false,
"text": "#include <stdarg.h>\n#include <stdio.h>\n\nvoid DBG_PrintImpl(char * format, ...)\n{\n char buffer[256];\n va_list args;\n va_start(args, format);\n vsprintf(buffer, format, args);\n printf(\"%s\", buffer);\n va_end(args);\n}\n"
},
{
"answer_id": 17029,
"author": "Mat Noguchi",
"author_id": 1799,
"author_profile": "https://Stackoverflow.com/users/1799",
"pm_score": 2,
"selected": false,
"text": "#define function sizeof\n"
},
{
"answer_id": 17932,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "#if defined _DEBUG\n\nclass Trace\n{\npublic:\n static Trace &GetTrace () { static Trace trace; return trace; }\n Trace &operator << (int value) { /* output int */ return *this; }\n Trace &operator << (short value) { /* output short */ return *this; }\n Trace &operator << (Trace &(*function)(Trace &trace)) { return function (*this); }\n static Trace &Endl (Trace &trace) { /* write newline and flush output */ return trace; }\n // and so on\n};\n\n#define TRACE(message) Trace::GetTrace () << message << Trace::Endl\n\n#else\n#define TRACE(message)\n#endif\n void Function (int param1, short param2)\n{\n TRACE (\"param1 = \" << param1 << \", param2 = \" << param2);\n}\n std::cout"
},
{
"answer_id": 42775,
"author": "David Bryson",
"author_id": 3663,
"author_profile": "https://Stackoverflow.com/users/3663",
"pm_score": 1,
"selected": false,
"text": "#ifndef _DEBUG_H_\n#define _DEBUG_H_\n#if HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \"stdarg.h\"\n#include \"stdio.h\"\n\n#define ENABLE 1\n#define DISABLE 0\n\nextern FILE* debug_fd;\n\nint debug_file_init(char *file);\nint debug_file_close(void);\n\n#if HAVE_C99\n#define PRINT(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, format, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stdout, format, ##__VA_ARGS__); \\\n} \\\n}\n#else\nvoid PRINT(int enable, char *fmt, ...);\n#endif\n\n#if _DEBUG\n#if HAVE_C99\n#define DEBUG(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, \"%s : %d \" format, __FILE__, __LINE__, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stderr, \"%s : %d \" format, __FILE__, __LINE__, ##__VA_ARGS__); \\\n} \\\n}\n\n#define DEBUGPRINT(x, format, ...) \\\nif ( x ) { \\\nif ( debug_fd != NULL ) { \\\nfprintf(debug_fd, format, ##__VA_ARGS__); \\\n} \\\nelse { \\\nfprintf(stderr, format, ##__VA_ARGS__); \\\n} \\\n}\n#else /* HAVE_C99 */\n\nvoid DEBUG(int enable, char *fmt, ...);\nvoid DEBUGPRINT(int enable, char *fmt, ...);\n\n#endif /* HAVE_C99 */\n#else /* _DEBUG */\n#define DEBUG(x, format, ...)\n#define DEBUGPRINT(x, format, ...)\n#endif /* _DEBUG */\n\n#endif /* _DEBUG_H_ */\n"
},
{
"answer_id": 55663,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "XTRACE(\"x=%d\", x);\n (\"x=%d\", x);\n 0 && XTrace\n 0 && XTrace(\"x=%d\", x);\n"
},
{
"answer_id": 67428,
"author": "snstrand",
"author_id": 10089,
"author_profile": "https://Stackoverflow.com/users/10089",
"pm_score": 5,
"selected": false,
"text": "#ifdef DEBUG\n#define dout cout\n#else\n#define dout 0 && cout\n#endif\n dout << \"in foobar with x= \" << x << \" and y= \" << y << '\\n';\n"
},
{
"answer_id": 13020140,
"author": "Koffiman",
"author_id": 914689,
"author_profile": "https://Stackoverflow.com/users/914689",
"pm_score": 0,
"selected": false,
"text": " static TCHAR __DEBUG_BUF[1024];\n #define DLog(fmt, ...) swprintf(__DEBUG_BUF, fmt, ##__VA_ARGS__); OutputDebugString(__DEBUG_BUF) \n \n int value = 42;\n DLog(L\"The answer is: %d\\n\", value);\n"
},
{
"answer_id": 18129398,
"author": "mousomer",
"author_id": 281617,
"author_profile": "https://Stackoverflow.com/users/281617",
"pm_score": 0,
"selected": false,
"text": "inline void DPRINTF(int level, char *format, ...)\n{\n# ifdef _DEBUG_LOG\n va_list args;\n va_start(args, format);\n if(debugPrint & level) {\n vfprintf(stdout, format, args);\n }\n va_end(args);\n# endif /* _DEBUG_LOG */\n}\n"
},
{
"answer_id": 39186784,
"author": "Orwellophile",
"author_id": 912236,
"author_profile": "https://Stackoverflow.com/users/912236",
"pm_score": 0,
"selected": false,
"text": "#define DEBUG_OUT( fmt, ...) DEBUG_OUT_TCHAR( \\\n TEXT(##fmt), ##__VA_ARGS__ )\n#define DEBUG_OUT_TCHAR( fmt, ...) \\\n Trace( TEXT(\"[DEBUG]\") #fmt, \\\n ##__VA_ARGS__ )\nvoid Trace(LPCTSTR format, ...)\n{\n LPTSTR OutputBuf;\n OutputBuf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, \\\n (size_t)(4096 * sizeof(TCHAR)));\n va_list args;\n va_start(args, format);\n int nBuf;\n _vstprintf_s(OutputBuf, 4095, format, args);\n ::OutputDebugString(OutputBuf);\n va_end(args);\n LocalFree(OutputBuf); // tyvm @sam shaw\n}\n"
},
{
"answer_id": 63047805,
"author": "parth_07",
"author_id": 3447475,
"author_profile": "https://Stackoverflow.com/users/3447475",
"pm_score": 0,
"selected": false,
"text": "#define show(args...) describe(#args,args);\ntemplate<typename T>\nvoid describe(string var_name,T value)\n{\n clog<<var_name<<\" = \"<<value<<\" \";\n}\n\ntemplate<typename T,typename... Args>\nvoid describe(string var_names,T value,Args... args)\n{\n string::size_type pos = var_names.find(',');\n string name = var_names.substr(0,pos);\n var_names = var_names.substr(pos+1);\n clog<<name<<\" = \"<<value<<\" | \";\n describe(var_names,args...);\n}\n int main()\n{\n string a;\n int b;\n double c;\n a=\"string here\";\n b = 7;\n c= 3.14;\n show(a,b,c);\n}\n a = string here | b = 7 | c = 3.14 \n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1841/"
] |
15,241 |
<p>The main web application of my company is crying out for a nifty set of libraries to make it in some way maintainable and scalable, and one of my colleagues has suggested CSLA. So I've bought the book but as :</p>
<blockquote>
<p><em>programmers don't read books anymore</em></p>
</blockquote>
<p>I wanted to gauge the SOFlow community's opinion of it.</p>
<p>So here are my questions:</p>
<ol>
<li>How may people are using CSLA?</li>
<li>What are the pros and cons?</li>
<li>Does CSLA really not fit in with TDD?</li>
<li>What are my alternatives?</li>
<li>If you have stopped using it or decided against why?</li>
</ol>
|
[
{
"answer_id": 1219364,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": 5,
"selected": false,
"text": "WCFDataPortal"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116/"
] |
15,247 |
<p>Given a list of locations such as</p>
<pre class="lang-html prettyprint-override"><code> <td>El Cerrito, CA</td>
<td>Corvallis, OR</td>
<td>Morganton, NC</td>
<td>New York, NY</td>
<td>San Diego, CA</td>
</code></pre>
<p>What's the easiest way to generate a Google Map with pushpins for each location?</p>
|
[
{
"answer_id": 17132,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 5,
"selected": true,
"text": "<head>\n <script \n type=\"text/javascript\"\n href=\"http://maps.google.com/maps?\n file=api&v=2&key=xxxxx\">\n function createMap() {\n var map = new GMap2(document.getElementById(\"map\"));\n map.setCenter(new GLatLng(37.44, -122.14), 14);\n }\n </script>\n</head>\n<body onload=\"createMap()\" onunload=\"GUnload()\">\n var where = new GLatLng(37.925243,-122.307358); //Lat and Lng for El Cerrito, CA\nvar marker = new GMarker(where); // Create marker (Pinhead thingy)\nmap.setCenter(where); // Center map on marker\nmap.addOverlay(marker); // Add marker to map\n var address = \"El Cerrito, CA\";\nvar geocoder = new GClientGeocoder;\ngeocoder.getLatLng(address, function(point) {\n if (point) {\n map.clearOverlays(); // Clear all markers\n map.addOverlay(new GMarker(point)); // Add marker to map\n map.setCenter(point, 10); // Center and zoom map on marker\n }\n});\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
15,254 |
<p>Is it possible to actually make use of placement new in portable code when using it for arrays?</p>
<p>It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for the array to go in if this is the case.</p>
<p>The following example shows the problem. Compiled with Visual Studio, this example results in memory corruption:</p>
<pre><code>#include <new>
#include <stdio.h>
class A
{
public:
A() : data(0) {}
virtual ~A() {}
int data;
};
int main()
{
const int NUMELEMENTS=20;
char *pBuffer = new char[NUMELEMENTS*sizeof(A)];
A *pA = new(pBuffer) A[NUMELEMENTS];
// With VC++, pA will be four bytes higher than pBuffer
printf("Buffer address: %x, Array address: %x\n", pBuffer, pA);
// Debug runtime will assert here due to heap corruption
delete[] pBuffer;
return 0;
}
</code></pre>
<p>Looking at the memory, the compiler seems to be using the first four bytes of the buffer to store a count of the number of items in it. This means that because the buffer is only <code>sizeof(A)*NUMELEMENTS</code> big, the last element in the array is written into unallocated heap.</p>
<p>So the question is can you find out how much additional overhead your implementation wants in order to use placement new[] safely? Ideally, I need a technique that's portable between different compilers. Note that, at least in VC's case, the overhead seems to differ for different classes. For instance, if I remove the virtual destructor in the example, the address returned from new[] is the same as the address I pass in.</p>
|
[
{
"answer_id": 15273,
"author": "Yossi Kreinin",
"author_id": 1648,
"author_profile": "https://Stackoverflow.com/users/1648",
"pm_score": 1,
"selected": false,
"text": "\ntypedef A Arr[NUMELEMENTS]; \n\n A* p = new (buffer) Arr;\n"
},
{
"answer_id": 15343,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 6,
"selected": true,
"text": "int main(int argc, char* argv[])\n{\n const int NUMELEMENTS=20;\n\n char *pBuffer = new char[NUMELEMENTS*sizeof(A)];\n A *pA = (A*)pBuffer;\n\n for(int i = 0; i < NUMELEMENTS; ++i)\n {\n pA[i] = new (pA + i) A();\n }\n\n printf(\"Buffer address: %x, Array address: %x\\n\", pBuffer, pA);\n\n // dont forget to destroy!\n for(int i = 0; i < NUMELEMENTS; ++i)\n {\n pA[i].~A();\n } \n\n delete[] pBuffer;\n\n return 0;\n}\n"
},
{
"answer_id": 15372,
"author": "Andrew Grant",
"author_id": 1043,
"author_profile": "https://Stackoverflow.com/users/1043",
"pm_score": 2,
"selected": false,
"text": "char *pBuffer = new char[ sizeof(A[NUMELEMENTS]) ];\nA *pA = (A*)pBuffer;\n\nfor(int i = 0; i < NUMELEMENTS; ++i)\n{\n pA[i] = new (pA + i) A();\n}\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739/"
] |
15,266 |
<p>Using <strong>NSURLRequest</strong>, I am trying to access a web site that has an expired certificate. When I send the request, my <strong>connection:didFailWithError</strong> delegate method is invoked with the following info:</p>
<pre><code>-1203, NSURLErrorDomain, bad server certificate
</code></pre>
<p>My searches have only turned up one solution: a hidden class method in NSURLRequest:</p>
<pre><code>[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:myHost];
</code></pre>
<p>However, I don't want to use private APIs in a production app for obvious reasons.</p>
<p>Any suggestions on what to do? Do I need to use CFNetwork APIs, and if so, two questions:</p>
<ul>
<li>Any sample code I can use to get started? I haven't found any online.</li>
<li>If I use CFNetwork for this, do I have to ditch NSURL entirely?</li>
</ul>
<hr>
<p>EDIT:</p>
<p>iPhone OS 3.0 introduced a supported method for doing this. More details here: <a href="https://stackoverflow.com/questions/933331/how-to-use-nsurlconnection-to-connect-with-ssl-for-an-untrusted-cert">How to use NSURLConnection to connect with SSL for an untrusted cert?</a></p>
|
[
{
"answer_id": 245903,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 3,
"selected": false,
"text": "CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFSTR(\"http://www.apple.com\"), NULL);\nCFHTTPMessageRef myRequest = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR(\"GET\"), myURL, kCFHTTPVersion1_1);\nCFReadStreamRef myStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, myRequest);\nCFMutableDictionaryRef myDict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);\nCFDictionarySetValue(myDict, kCFStreamSSLValidatesCertificateChain, kCFBooleanFalse);\nCFReadStreamSetProperty(myStream, kCFStreamPropertySSLSettings, myDict); \nCFReadStreamOpen(myStream);\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/544/"
] |
15,272 |
<p>I want a data structure that will allow querying <em>how many items in last <strong>X</strong> minutes</em>. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple items having same timestamp).</p>
<p>So far it seems that with LINQ I could easily filter items with timestamp greater than a given time and aggregate a count. Though I'm hesitant to try to work .NET 3.5 specific stuff into my production environment yet. Are there any other suggestions for a similar data structure?</p>
<p>The other part that I'm interested in is <em>aging</em> old data out, If I'm only going to be asking for counts of items less than 6 hours ago I would like anything older than that to be removed from my data structure because this may be a long-running program.</p>
|
[
{
"answer_id": 15904,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": true,
"text": "list.push_end(new_data)\nwhile list.head.age >= age_limit:\n list.pop_head()\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/163/"
] |
15,310 |
<p>First off I understand that it is a horrible idea to run extremely large/long running reports. I am aware that Microsoft has a rule of thumb stating that a SSRS report should take no longer than 30 seconds to execute. However sometimes gargantuan reports are a preferred evil due to external forces such complying with state laws.</p>
<p>At my place of employment, we have an asp.net (2.0) app that we have migrated from Crystal Reports to SSRS. Due to the large user base and complex reporting UI requirements we have a set of screens that accepts user inputted parameters and creates schedules to be run over night. Since the application supports multiple reporting frameworks we do not use the scheduling/snapshot facilities of SSRS. All of the reports in the system are generated by a scheduled console app which takes user entered parameters and generates the reports with the corresponding reporting solutions the reports were created with. In the case of SSRS reports, the console app generates the SSRS reports and exports them as PDFs via the SSRS web service API. </p>
<p>So far SSRS has been much easier to deal with than Crystal with the exception of a certain 25,000 page report that we have recently converted from crystal reports to SSRS. The SSRS server is a 64bit 2003 server with 32 gigs of ram running SSRS 2005. All of our smaller reports work fantastically, but we are having trouble with our larger reports such as this one. Unfortunately, we can't seem to generate the aforemention report through the web service API. The following error occurs roughly 30-35 minutes into the generation/export:</p>
<p>Exception Message: The underlying connection was closed: An unexpected error occurred on a receive.</p>
<p>The web service call is something I'm sure you all have seen before: </p>
<pre><code>data = rs.Render(this.ReportPath, this.ExportFormat, null, deviceInfo,
selectedParameters, null, null, out encoding, out mimeType, out usedParameters,
out warnings, out streamIds);
</code></pre>
<p>The odd thing is that this report will run/render/export if the report is run directly on the reporting server using the report manager. The proc that produces the data for the report runs for about 5 minutes. The report renders in SSRS native format in the browser/viewer after about 12 minutes. Exporting to pdf through the browser/viewer in the report manager takes an additional 55 minutes. This works reliably and it produces a whopping 1.03gb pdf.</p>
<p>Here are some of the more obvious things I've tried to get the report working via the web service API: </p>
<ul>
<li>set the HttpRuntime ExecutionTimeout
value to 3 hours on the report
server</li>
<li>disabled http keep alives on the report server</li>
<li>increased the script timeout on the report server</li>
<li>set the report to never time out on the server</li>
<li>set the report timeout to several hours on the client call </li>
</ul>
<p>From the tweaks I have tried, I am fairly comfortable saying that any timeout issues have been eliminated. </p>
<p>Based off of my research of the error message, I believe that the web service API does not send chunked responses by default. This means that it tries to send all 1.3gb over the wire in one response. At a certain point, IIS throws in the towel. Unfortunately the API abstracts away web service configuration so I can't seem to find a way to enable response chunking. </p>
<ol>
<li>Does anyone know of anyway to reduce/optimize the PDF export phase and or the size of the PDF without lowering the total page count?</li>
<li>Is there a way to turn on response chunking for SSRS?</li>
<li>Does anyone else have any other theories as to why this runs on the server but not through the API?</li>
</ol>
<p>EDIT: After reading kcrumley's post I began to take a look at the average page size by taking file size / page count. Interestingly enough on smaller reports the math works out so that each page is roughly 5K. Interestingly, when the report gets larger this "average" increases. An 8000 page report for example is averaging over 40K/page. Very odd. I will also add that the number of records per page is set except for the last page in each grouping, so it's not a case where some pages have more records than another. </p>
|
[
{
"answer_id": 10481764,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 2,
"selected": false,
"text": "Times New Roman, Courier New, or Arial FontFamily"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1644/"
] |
15,315 |
<p>Is there a method for handling errors from COM objects in RDML? For instance, when calling Word VBA methods like <code>PasteSpecial</code>, an error is returned and the LANSA application crashes. I cannot find anything in the documentation to allow handling of these errors.</p>
<p>Actually, error handling in general is a weak-point for LANSA and RDML, but that's another topic.</p>
|
[
{
"answer_id": 10481764,
"author": "StuartLC",
"author_id": 314291,
"author_profile": "https://Stackoverflow.com/users/314291",
"pm_score": 2,
"selected": false,
"text": "Times New Roman, Courier New, or Arial FontFamily"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
15,326 |
<p>Here is the scenario: </p>
<p>I have a table with a margin-bottom of 19px. Below that I have a form that contains some fieldsets. One of them is floated right. The problem is that the margin-bottom is not getting the full 19px in IE7. I've gone through all of the IE7 css/margin/float bugs that I can think of and have tried remedies but have been unsuccessful. I have been googling for a while now and cannot find anything that is helping out. </p>
<p>Here is what I have tried. </p>
<ol>
<li>Wrapping the form or fieldset in an unstyled div. No apparent change.</li>
<li>Nixing the margin-bottom on the table and instead wrapping that with a div and giving it a padding-bottom of 19px. No apparent change.</li>
<li>Nixing the margin-bottom on the table and adding a div with a fixed height of 19px. No apparent change.</li>
<li>Putting a clear between the table and the fieldset.</li>
</ol>
<p>I know there are some others that I am forgetting, but those are the things I have tried out recently. This happens to each fieldset. </p>
<hr>
<p>I am using a reset style sheet and have a xhtml transitional doctype. </p>
<p><strong>Edit:</strong> I also have the IE7 web developer toolbar and Firebug. The style information for both browsers says that it has a margin-bottom: 19px; but it clearly is not for IE7.</p>
|
[
{
"answer_id": 15356,
"author": "eplawless",
"author_id": 1370,
"author_profile": "https://Stackoverflow.com/users/1370",
"pm_score": 1,
"selected": false,
"text": "Ctrl+Shift+Y CSS -> View Style Information <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"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>Test</title>\n <style>\n #mytable {\n margin-bottom: 19px;\n border: solid green 1px;\n }\n \n #myform {\n border: solid red 1px; \n overflow: hidden;\n }\n #floaty {\n float: right; \n border: solid blue 1px;\n }\n </style>\n </head>\n <body>\n <table id=\"mytable\">\n <th>Col 1</th>\n <th>Col 3</th>\n <th>Col 2</th>\n <tr>\n <td>Val 1</td>\n <td>Val 2</td>\n <td>Val 3</td>\n </tr>\n </table>\n <form method=\"post\" action=\"test.html\" id=\"myform\">\n <fieldset id=\"floaty\">\n <label for=\"myinput\">Caption:</label>\n <input id=\"myinput\" type=\"text\" />\n </fieldset>\n <fieldset>\n <p>Some example content</p>\n <input type=\"checkbox\" id=\"mycheckbox\" />\n <label for=\"mycheckbox\">Click MEEEEE</label>\n </fieldset>\n </form>\n </body>\n </html>"
},
{
"answer_id": 15408,
"author": "Kevin",
"author_id": 40,
"author_profile": "https://Stackoverflow.com/users/40",
"pm_score": 0,
"selected": false,
"text": "<br style=\"clear:both;\" />\n"
},
{
"answer_id": 13267525,
"author": "user64bit",
"author_id": 1552579,
"author_profile": "https://Stackoverflow.com/users/1552579",
"pm_score": 2,
"selected": false,
"text": "margin-bottom: 19px; <div/> height: 19px margin-bottom <div/> height: 19px <table/> <form/> <table id=\"mytable\">\n <tr>\n <th>Col 1</th>\n <th>Col 3</th>\n <th>Col 2</th>\n </tr>\n <tr>\n <td>Val 1</td>\n <td>Val 2</td>\n <td>Val 3</td>\n </tr>\n</table>\n<div style=\"height:19px;\"></div>\n<form method=\"post\" action=\"test.html\" id=\"myform\">\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
15,334 |
<p>I have recently started using Vim as my text editor and am currently working on my own customizations.</p>
<p>I suppose keyboard mappings can do pretty much anything, but for the time being I'm using them as a sort of snippets facility almost exclusively.</p>
<p>So, for example, if I type <code>def{TAB}</code> (<code>:imap def{TAB} def ():<ESC>3ha</code>), it expands to:</p>
<pre><code>def |(): # '|' represents the caret
</code></pre>
<p>This works as expected, but I find it annoying when Vim waits for a full command while I'm typing a word containing "def" and am not interested in expanding it.</p>
<ul>
<li>Is there a way to avoid this or use this function more effectively to this end?</li>
<li>Is any other Vim feature better suited for this?</li>
</ul>
<hr>
<p>After taking a quick look at <a href="http://www.vim.org/scripts/script.php?script_id=1318" rel="noreferrer">SnippetsEmu</a>, it looks like it's the best option and much easier to customize than I first thought.</p>
<p>To continue with the previous example:</p>
<pre><code>:Snippet def <{}>():
</code></pre>
<p>Once defined, you can expand your snippet by typing <code>def{TAB}</code>.</p>
|
[
{
"answer_id": 32324,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 2,
"selected": false,
"text": ":ab[breviate] :ab[breviate] [<expr>] {lhs} {rhs}\n add abbreviation for {lhs} to {rhs}. If {lhs} already\n existed it is replaced with the new {rhs}. {rhs} may\n contain spaces.\n See |:map-<expr>| for the optional <expr> argument.\n"
},
{
"answer_id": 879590,
"author": "SergioAraujo",
"author_id": 2571881,
"author_profile": "https://Stackoverflow.com/users/2571881",
"pm_score": 5,
"selected": false,
"text": "snippet def \n \"\"\" ${1:docstring} \"\"\"\n def ${2:name}:\n return ${3:value}\n"
},
{
"answer_id": 13133097,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": ":iabbrev def def(): #<LEFT><LEFT><LEFT><LEFT><LEFT>\n :help abbrev au filetype python :iabbrev ... etc\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1670/"
] |
15,366 |
<p>What's the best practice for making sure that certain ajax calls to certain pages are only accepted from authenticated users?</p>
<p>For example:</p>
<p>Let's say that I have a main page called <strong>blog.php</strong> (I know, creativity abounds). Let's also say that there is a page called <strong>delete.php</strong> which looks for the parameter <strong>post_id</strong> and then deletes some entry from a database.</p>
<p>In this very contrived example, there's some mechanism on blog.php which sends a request via ajax to delete.php to delete an entry. </p>
<p>Now this mechanism is only going to be available to authenticated users on blog.php. But what's to stop someone from just calling delete.php with a bunch of random numbers and deleting everything in site?</p>
<p>I did a quick test where I set a session variable in blog.php and then did an ajax call to delete.php to return if the session variable was set or not <strong><em>(it wasn't)</em></strong>.</p>
<p>What's the accepted way to handle this sort of thing?</p>
<hr>
<p>OK. I must have been crazy the first time I tried this.</p>
<p>I just did another test like the one I described above and it worked perfectly.</p>
|
[
{
"answer_id": 15368,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 4,
"selected": true,
"text": "session_start() session_id()"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
15,390 |
<p>What are some standard practices for managing a medium-large JavaScript application? My concerns are both speed for browser download and ease and maintainability of development.</p>
<p>Our JavaScript code is roughly "namespaced" as:</p>
<pre><code>var Client = {
var1: '',
var2: '',
accounts: {
/* 100's of functions and variables */
},
orders: {
/* 100's of functions and variables and subsections */
}
/* etc, etc for a couple hundred kb */
}
</code></pre>
<p>At the moment, we have one (unpacked, unstripped, highly readable) JavaScript file to handle all the business logic on the web application. In addition, there is jQuery and several jQuery extensions. The problem we face is that it takes <em>forever</em> to find anything in the JavaScript code and the browser still has a dozen files to download.</p>
<p>Is it common to have a handful of "source" JavaScript files that gets "compiled" into one final, compressed JavaScript file? Any other handy hints or best practices?</p>
|
[
{
"answer_id": 15402,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 5,
"selected": true,
"text": "<script src='/path/to/js/$file.js' type='text/javascript'>"
},
{
"answer_id": 39011,
"author": "paulgreg",
"author_id": 3122,
"author_profile": "https://Stackoverflow.com/users/3122",
"pm_score": 3,
"selected": false,
"text": "google.load(\"jquery\", \"1.2.3\");\ngoogle.load(\"jqueryui\", \"1.5.2\");\ngoogle.load(\"prototype\", \"1.6\");\ngoogle.load(\"scriptaculous\", \"1.8.1\");\ngoogle.load(\"mootools\", \"1.11\");\ngoogle.load(\"dojo\", \"1.1.1\");\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1848/"
] |
15,395 |
<p>Linq To SQL or Entity framework both integrate nicely with SQL Server 2005.</p>
<p>The SQL Server 2008 spec sheet promises even better integration - but I can't see it.</p>
<p>What are some examples of what you can do Linq-wise when talking to a 2008 server that you can't when talking to SQL Server 2005?</p>
|
[
{
"answer_id": 153273,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "var orders = (\nfrom c in Customers\nfrom o in c.Orders\nselect new {c, o}\n).Skip(10).Take(10).ToList();\n"
}
] |
2008/08/18
|
[
"https://Stackoverflow.com/questions/15395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1855/"
] |
15,414 |
<p>I'm quite used to my IDE setup in Delphi 7, where I have my comments rendered in italics.</p>
<p>This doesn't appear to be possible in VS2008. There's only an option for bold font, not italics.</p>
<p>Is there some kind of registry hack or font magic I can perform to get it to work? The font I'm using is Consolas, if that makes a difference.</p>
<p><strong>Edit:</strong> This is possible. See <a href="https://stackoverflow.com/questions/17508/how-to-modify-the-style-property-of-a-font-on-windows#25676">this</a> answer for details.</p>
<hr>
<p>Adam, as far as I can tell, you can't change the font name for just comments - only the colour, and boldness. If I'm wrong, please tell me!</p>
|
[
{
"answer_id": 15434,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 2,
"selected": false,
"text": "HKCU\\Software\\Microsoft\\VisualStudio\\9.0\\FontAndColors\\{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0} \nComment FontFlags\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] |
15,423 |
<p>I'd like to know what's the way to actually set the icon of a <code>.bat</code> file to an arbitrary icon.
How would I go about doing that programmatically, independently of the language I may be using.</p>
|
[
{
"answer_id": 15437,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 7,
"selected": true,
"text": ".bat .lnk"
},
{
"answer_id": 856655,
"author": "Joey",
"author_id": 73070,
"author_profile": "https://Stackoverflow.com/users/73070",
"pm_score": 3,
"selected": false,
"text": "HKCR\\batfile\\DefaultIcon\n %SystemRoot%\\System32\\imageres.dll,-68\n .cmd"
},
{
"answer_id": 4626066,
"author": "d4rkcell",
"author_id": 566953,
"author_profile": "https://Stackoverflow.com/users/566953",
"pm_score": 4,
"selected": false,
"text": "Bat to Exe"
},
{
"answer_id": 14687898,
"author": "bli",
"author_id": 2039767,
"author_profile": "https://Stackoverflow.com/users/2039767",
"pm_score": 4,
"selected": false,
"text": "SetIconLocation Const DESKTOP = &H10&\nSet objShell = CreateObject(\"Shell.Application\")\nSet objFolder = objShell.NameSpace(DESKTOP)\nSet objFolderItem = objFolder.ParseName(\"Test Shortcut.lnk\")\nSet objShortcut = objFolderItem.GetLink\nobjShortcut.SetIconLocation \"C:\\Windows\\System32\\SHELL32.dll\", 13\nobjShortcut.Save\n"
},
{
"answer_id": 64758203,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 1,
"selected": false,
"text": "call shortcutjs.bat -linkfile mybat3.lnk -target \"%cd%\\Ascii2All.bat\" -iconlocation \"%SystemRoot%\\System32\\SHELL32.dll,77\"\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/883/"
] |
15,470 |
<p>I know this site is written using ASP.Net MVC and I do not see "/Home" in the url. This proves to me that it can be done. What special route and do I need?</p>
|
[
{
"answer_id": 15474,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 5,
"selected": true,
"text": "routes.MapRoute(\n \"Home\",\n \"\",\n new { action = Index, controller = Home }\n);\n"
},
{
"answer_id": 27425188,
"author": "SepehrM",
"author_id": 2550529,
"author_profile": "https://Stackoverflow.com/users/2550529",
"pm_score": 1,
"selected": false,
"text": "routes.MapRoute(\"NoIndex\", \"{action}\", new { controller = \"Home\", action = \"Index\" });\n"
},
{
"answer_id": 28389682,
"author": "Kraig McConaghy",
"author_id": 3578535,
"author_profile": "https://Stackoverflow.com/users/3578535",
"pm_score": 0,
"selected": false,
"text": "routes.MapRoute(\n \"Default\",\n \"{action}\",\n new { controller = \"Home\", action = \"Index\" }\n);\n\nroutes.MapRoute(\n \"Actions\",\n \"{controller}/{action}\",\n new { }\n);\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692/"
] |
15,478 |
<p>GDI+ DrawLines function has a clipping bug that can be reproduced by running the following c# code. When running the code, two line paths appear, that should be identical, because both of them are inside the clipping region. But when the clipping region is set, one of the line segment is not drawn. </p>
<pre><code>protected override void OnPaint(PaintEventArgs e)
{
PointF[] points = new PointF[] { new PointF(73.36f, 196),
new PointF(75.44f, 32),
new PointF(77.52f, 32),
new PointF(79.6f, 196),
new PointF(85.84f, 196) };
Rectangle b = new Rectangle(70, 32, 20, 164);
e.Graphics.SetClip(b);
e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly
e.Graphics.TranslateTransform(80, 0);
e.Graphics.ResetClip();
e.Graphics.DrawLines(Pens.Red, points);
}
</code></pre>
<p>Setting the antials mode on the graphics object resolves this. But that is not a real solution.</p>
<p>Does anybody know of a workaround?</p>
|
[
{
"answer_id": 15813,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );"
},
{
"answer_id": 16914,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 2,
"selected": false,
"text": "protected override void OnPaint(PaintEventArgs e)\n {\n PointF[] points = new PointF[] { new PointF(73.36f, 196), \n new PointF(75.44f, 32), \n new PointF(77.52f, 32), \n new PointF(79.6f, 196), \n new PointF(85.84f, 196) };\n\n e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n Rectangle b = new Rectangle(70, 32, 20, 165);\n e.Graphics.SetClip(b);\n e.Graphics.DrawLines(Pens.Red, points); // clipped incorrectly\n e.Graphics.TranslateTransform(80, 0);\n e.Graphics.ResetClip(); \n e.Graphics.DrawLines(Pens.Red, points);\n }\n protected override void OnPaint ( PaintEventArgs e )\n {\n PointF[] points = new PointF[] { new PointF(73.36f, 196), \n new PointF(75.44f, 32), \n new PointF(77.52f, 32), \n new PointF(79.6f, 196), \n new PointF(85.84f, 196) };\n\n Rectangle b = new Rectangle( 70, 32, 20, 164 );\n Region reg = new Region( b );\n e.Graphics.SetClip( reg, System.Drawing.Drawing2D.CombineMode.Union);\n e.Graphics.DrawLines( Pens.Red, points ); // clipped incorrectly\n e.Graphics.TranslateTransform( 80, 0 );\n e.Graphics.ResetClip();\n e.Graphics.DrawLines( Pens.Red, points );\n }\n e.Graphics.FillRectangle( new SolidBrush( Color.Black ), b );\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1873/"
] |
15,481 |
<p>Sometimes a labeled break or continue can make code a lot more readable. </p>
<pre><code>OUTERLOOP: for ( ;/*stuff*/; ) {
//...lots of code
if ( isEnough() ) break OUTERLOOP;
//...more code
}
</code></pre>
<p>I was wondering what the common convention for the labels was. All caps? first cap? </p>
|
[
{
"answer_id": 15501,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 4,
"selected": false,
"text": "for ( ;/*stuff*/; ) \n{\n lotsOfCode();\n\n if ( !isEnough() )\n {\n moreCode();\n }\n}\n"
},
{
"answer_id": 15894,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 2,
"selected": false,
"text": "myLabel:\n _myLabel:\n labSomething:\n"
},
{
"answer_id": 15939,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 5,
"selected": false,
"text": "outer_loop:\nfor (...) {\n // some code\n for (...) {\n // some code\n if (...)\n continue outer_loop;\n // more code\n }\n // more code\n}\n for (...) {\n // some code\n boolean continueOuterLoop = false;\n for (...) {\n // some code\n if (...) {\n continueOuterLoop = true;\n break;\n }\n // more code\n }\n if (continueOuterLoop)\n continue;\n // more code\n}\n boolean innerLoop (...) {\n for (...) {\n // some code\n if (...) {\n return true;\n }\n // more code\n }\n return false;\n}\n\nfor (...) {\n // some code\n if (innerLoop(...))\n continue;\n // more code\n}\n"
},
{
"answer_id": 15944,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "outerloop:\nfor (...) {\n // some code\n for (...) {\n // some code\n if (...)\n continue outerloop;\n // more code\n }\n // more code\n}\n public void lookMumNoLabels() {\n for (...) {\n // some code\n doMoreInnerCodeLogic(...);\n }\n}\n\nprivate void doMoreInnerCodeLogic(...) {\n for (...) {\n // some code\n if (...) return;\n }\n}\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
15,486 |
<p>So I came across an interesting problem today. We have a WCF web service that returns an IList. Not really a big deal until I wanted to sort it.</p>
<p>Turns out the IList interface doesn't have a sort method built in. </p>
<p>I ended up using the <code>ArrayList.Adapter(list).Sort(new MyComparer())</code> method to solve the problem but it just seemed a bit "ghetto" to me.</p>
<p>I toyed with writing an extension method, also with inheriting from IList and implementing my own Sort() method as well as casting to a List but none of these seemed overly elegant.</p>
<p>So my question is, does anyone have an elegant solution to sorting an IList</p>
|
[
{
"answer_id": 15492,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": -1,
"selected": false,
"text": "IList List<T> System.Linq"
},
{
"answer_id": 15494,
"author": "Brad Leach",
"author_id": 708,
"author_profile": "https://Stackoverflow.com/users/708",
"pm_score": 7,
"selected": true,
"text": "IList<Car> Engine from c in list\norderby c.Engine\nselect c;\n"
},
{
"answer_id": 15495,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "using System.Linq;\n\nIList<Foo> list = new List<Foo>();\nIEnumerable<Foo> sortedEnum = list.OrderBy(f=>f.Bar);\nIList<Foo> sortedList = sortedEnum.ToList();\n"
},
{
"answer_id": 16025,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n{\n IList list = new List<int>() { 1, 3, 2, 5, 4, 6, 9, 8, 7 };\n List<int> stronglyTypedList = new List<int>(Cast<int>(list));\n stronglyTypedList.Sort();\n}\n\nprivate static IEnumerable<T> Cast<T>(IEnumerable list)\n{\n foreach (T item in list)\n {\n yield return item;\n }\n}\n"
},
{
"answer_id": 512755,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class Widget {\n public string Name = string.Empty;\n public int Size = 0;\n\n public Widget(string name, int size) {\n this.Name = name;\n this.Size = size;\n}\n}\n\npublic class WidgetNameSorter : IComparer<Widget> {\n public int Compare(Widget x, Widget y) {\n return x.Name.CompareTo(y.Name);\n}\n}\n\npublic class WidgetSizeSorter : IComparer<Widget> {\n public int Compare(Widget x, Widget y) {\n return x.Size.CompareTo(y.Size);\n}\n}\n List<Widget> widgets = new List<Widget>();\nwidgets.Add(new Widget(\"Zeta\", 6));\nwidgets.Add(new Widget(\"Beta\", 3));\nwidgets.Add(new Widget(\"Alpha\", 9));\n\nwidgets.Sort(new WidgetNameSorter());\nwidgets.Sort(new WidgetSizeSorter());\n"
},
{
"answer_id": 1087089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "using System.Linq;\n\nvar yourList = SomeDAO.GetRandomThings();\nyourList.ToList().Sort( (thing, randomThing) => thing.CompareThisProperty.CompareTo( randomThing.CompareThisProperty ) );\n"
},
{
"answer_id": 3242024,
"author": "John",
"author_id": 239628,
"author_profile": "https://Stackoverflow.com/users/239628",
"pm_score": 1,
"selected": false,
"text": " public class FormatCcdeSorter:IComparer<ReportFormat>\n {\n public int Compare(ReportFormat x, ReportFormat y)\n {\n return x.FormatCode.CompareTo(y.FormatCode);\n }\n }\n ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList\n Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer\n System.Collections.Generic.IList<T>"
},
{
"answer_id": 3691280,
"author": "Yoav",
"author_id": 445117,
"author_profile": "https://Stackoverflow.com/users/445117",
"pm_score": 0,
"selected": false,
"text": " IList<string> ilist = new List<string>();\n ilist.Add(\"B\");\n ilist.Add(\"A\");\n ilist.Add(\"C\");\n\n Console.WriteLine(\"IList\");\n foreach (string val in ilist)\n Console.WriteLine(val);\n Console.WriteLine();\n\n List<string> list = (List<string>)ilist;\n list.Sort();\n Console.WriteLine(\"List\");\n foreach (string val in list)\n Console.WriteLine(val);\n Console.WriteLine();\n\n list = null;\n\n Console.WriteLine(\"IList again\");\n foreach (string val in ilist)\n Console.WriteLine(val);\n Console.WriteLine();\n"
},
{
"answer_id": 4388250,
"author": "Bruno",
"author_id": 535044,
"author_profile": "https://Stackoverflow.com/users/535044",
"pm_score": 1,
"selected": false,
"text": " List<MeuTeste> temp = new List<MeuTeste>();\n\n temp.Add(new MeuTeste(2, \"ramster\", DateTime.Now));\n temp.Add(new MeuTeste(1, \"ball\", DateTime.Now));\n temp.Add(new MeuTeste(8, \"gimm\", DateTime.Now));\n temp.Add(new MeuTeste(3, \"dies\", DateTime.Now));\n temp.Add(new MeuTeste(9, \"random\", DateTime.Now));\n temp.Add(new MeuTeste(5, \"call\", DateTime.Now));\n temp.Add(new MeuTeste(6, \"simple\", DateTime.Now));\n temp.Add(new MeuTeste(7, \"silver\", DateTime.Now));\n temp.Add(new MeuTeste(4, \"inn\", DateTime.Now));\n\n SortList(ref temp, SortDirection.Ascending, \"MyProperty\");\n\n private void SortList<T>(\n ref List<T> lista\n , SortDirection sort\n , string propertyToOrder)\n {\n if (!string.IsNullOrEmpty(propertyToOrder)\n && lista != null\n && lista.Count > 0)\n {\n Type t = lista[0].GetType();\n\n if (sort == SortDirection.Ascending)\n {\n lista = lista.OrderBy(\n a => t.InvokeMember(\n propertyToOrder\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n else\n {\n lista = lista.OrderByDescending(\n a => t.InvokeMember(\n propertyToOrder\n , System.Reflection.BindingFlags.GetProperty\n , null\n , a\n , null\n )\n ).ToList();\n }\n }\n }\n"
},
{
"answer_id": 5037815,
"author": "David Mills",
"author_id": 29696,
"author_profile": "https://Stackoverflow.com/users/29696",
"pm_score": 6,
"selected": false,
"text": "public static class SortExtensions\n{\n // Sorts an IList<T> in place.\n public static void Sort<T>(this IList<T> list, Comparison<T> comparison)\n {\n ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));\n }\n\n // Sorts in IList<T> in place, when T is IComparable<T>\n public static void Sort<T>(this IList<T> list) where T: IComparable<T>\n {\n Comparison<T> comparison = (l, r) => l.CompareTo(r);\n Sort(list, comparison);\n\n }\n\n // Convenience method on IEnumerable<T> to allow passing of a\n // Comparison<T> delegate to the OrderBy method.\n public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)\n {\n return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));\n }\n}\n\n// Wraps a generic Comparison<T> delegate in an IComparer to make it easy\n// to use a lambda expression for methods that take an IComparer or IComparer<T>\npublic class ComparisonComparer<T> : IComparer<T>, IComparer\n{\n private readonly Comparison<T> _comparison;\n\n public ComparisonComparer(Comparison<T> comparison)\n {\n _comparison = comparison;\n }\n\n public int Compare(T x, T y)\n {\n return _comparison(x, y);\n }\n\n public int Compare(object o1, object o2)\n {\n return _comparison((T)o1, (T)o2);\n }\n}\n IList<string> iList = new []\n{\n \"Carlton\", \"Alison\", \"Bob\", \"Eric\", \"David\"\n};\n\n// Use the custom extensions:\n\n// Sort in-place, by string length\niList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));\n\n// Or use OrderBy()\nIEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));\n"
},
{
"answer_id": 12211204,
"author": "Dhanasekar Murugesan",
"author_id": 1565396,
"author_profile": "https://Stackoverflow.com/users/1565396",
"pm_score": 2,
"selected": false,
"text": "try this **USE ORDER BY** :\n\n public class Employee\n {\n public string Id { get; set; }\n public string Name { get; set; }\n }\n\n private static IList<Employee> GetItems()\n {\n List<Employee> lst = new List<Employee>();\n\n lst.Add(new Employee { Id = \"1\", Name = \"Emp1\" });\n lst.Add(new Employee { Id = \"2\", Name = \"Emp2\" });\n lst.Add(new Employee { Id = \"7\", Name = \"Emp7\" });\n lst.Add(new Employee { Id = \"4\", Name = \"Emp4\" });\n lst.Add(new Employee { Id = \"5\", Name = \"Emp5\" });\n lst.Add(new Employee { Id = \"6\", Name = \"Emp6\" });\n lst.Add(new Employee { Id = \"3\", Name = \"Emp3\" });\n\n return lst;\n }\n\n**var lst = GetItems().AsEnumerable();\n\n var orderedLst = lst.OrderBy(t => t.Id).ToList();\n\n orderedLst.ForEach(emp => Console.WriteLine(\"Id - {0} Name -{1}\", emp.Id, emp.Name));**\n"
},
{
"answer_id": 39031496,
"author": "dana",
"author_id": 315689,
"author_profile": "https://Stackoverflow.com/users/315689",
"pm_score": 3,
"selected": false,
"text": "ComparisonComparer<T> Comparer<T>.Create(Comparison<T>) IComparison IList<T> IList List<T> IList IList<T> List<T>.Sort() List<T>.Sort() List<T>.Sort(Comparison<T>) List<T>.Sort(IComparer<T>) List<T>.Sort(Int32, Int32, IComparer<T>) List<T>.Sort() IList<T> using System;\nusing System.Collections.Generic;\n\npublic static class IListExtensions\n{\n public static void Sort<T>(this IList<T> list)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort();\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort();\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, Comparison<T> comparison)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(comparison);\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort(comparison);\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, IComparer<T> comparer)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(comparer);\n }\n else\n {\n var copy = new List<T>(list);\n copy.Sort(comparer);\n Copy(copy, 0, list, 0, list.Count);\n }\n }\n\n public static void Sort<T>(this IList<T> list, int index, int count,\n IComparer<T> comparer)\n {\n if (list is List<T> listImpl)\n {\n listImpl.Sort(index, count, comparer);\n }\n else\n {\n var range = new List<T>(count);\n for (int i = 0; i < count; i++)\n {\n range.Add(list[index + i]);\n }\n range.Sort(comparer);\n Copy(range, 0, list, index, count);\n }\n }\n\n private static void Copy<T>(IList<T> sourceList, int sourceIndex,\n IList<T> destinationList, int destinationIndex, int count)\n {\n for (int i = 0; i < count; i++)\n {\n destinationList[destinationIndex + i] = sourceList[sourceIndex + i];\n }\n }\n}\n class Foo\n{\n public int Bar;\n\n public Foo(int bar) { this.Bar = bar; }\n}\n\nvoid TestSort()\n{\n IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };\n IList<Foo> foos = new List<Foo>()\n {\n new Foo(1),\n new Foo(4),\n new Foo(5),\n new Foo(3),\n new Foo(2),\n };\n\n ints.Sort();\n foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));\n}\n List<T> IList<T> List<T> IList"
},
{
"answer_id": 58669695,
"author": "Momodu Deen Swarray",
"author_id": 10032850,
"author_profile": "https://Stackoverflow.com/users/10032850",
"pm_score": 0,
"selected": false,
"text": " var ordered = theIList.Cast<T>().OrderBy(e => e);\n ObservableCollection<Plugin.ContactService.Shared.Contact> ContactItems= new ObservableCollection<Contact>();\n\n foreach (var item in ordered)\n {\n ContactItems.Add(item);\n }\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
15,496 |
<p>After reading <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c">Hidden Features of C#</a> I wondered, What are some of the hidden features of Java?</p>
|
[
{
"answer_id": 15538,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 5,
"selected": false,
"text": "List<String> ls = List(\"a\", \"b\", \"c\");\n List<Map<String, String>> data = List(Map( o(\"name\", \"michael\"), o(\"sex\", \"male\")));\n"
},
{
"answer_id": 17702,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 4,
"selected": false,
"text": "goto"
},
{
"answer_id": 35108,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 7,
"selected": false,
"text": "class Souper {\n Collection<String> values() {\n ...\n }\n}\n\nclass ThreadSafeSortedSub extends Souper {\n @Override\n ConcurrentSkipListSet<String> values() {\n ...\n }\n}\n values Set String ConcurrentSkipListSet"
},
{
"answer_id": 39433,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 7,
"selected": false,
"text": "// code goes here\n\ngetmeout:{\n for (int i = 0; i < N; ++i) {\n for (int j = i; j < N; ++j) {\n for (int k = j; k < N; ++k) {\n //do something here\n break getmeout;\n }\n }\n }\n}\n goto"
},
{
"answer_id": 42686,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 8,
"selected": false,
"text": "public class Baz<T extends Foo & Bar> {}\n public static <A, B extends Collection<A> & Comparable<B>>\nboolean foo(B b1, B b2, A a) {\n return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);\n}\n"
},
{
"answer_id": 47493,
"author": "David Carlson",
"author_id": 4901,
"author_profile": "https://Stackoverflow.com/users/4901",
"pm_score": 8,
"selected": false,
"text": "public class App {\n public App(String name) { System.out.println(name + \"'s constructor called\"); }\n\n static { System.out.println(\"static initializer called\"); }\n\n { System.out.println(\"instance initializer called\"); }\n\n static { System.out.println(\"static initializer2 called\"); }\n\n { System.out.println(\"instance initializer2 called\"); }\n\n public static void main( String[] args ) {\n new App(\"one\");\n new App(\"two\");\n }\n}\n main static initializer called\nstatic initializer2 called\ninstance initializer called\ninstance initializer2 called\none's constructor called\ninstance initializer called\ninstance initializer2 called\ntwo's constructor called\n List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};\n\nMap<String,String> codes = new HashMap<String,String>(){{ \n put(\"1\",\"one\"); \n put(\"2\",\"two\");\n}};\n"
},
{
"answer_id": 52914,
"author": "Adrian Mouat",
"author_id": 4332,
"author_profile": "https://Stackoverflow.com/users/4332",
"pm_score": 7,
"selected": false,
"text": "enum Cats {\n FELIX(2), SHEEBA(3), RUFUS(7);\n\n private int mAge;\n Cats(int age) {\n mAge = age;\n }\n public int getAge() {\n return mAge;\n }\n}\n"
},
{
"answer_id": 55221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "class SelfBounded<T extends SelfBounded<T>> {\n}\n"
},
{
"answer_id": 55679,
"author": "Kevin Wong",
"author_id": 4792,
"author_profile": "https://Stackoverflow.com/users/4792",
"pm_score": 7,
"selected": false,
"text": "Collections.<String,Integer>emptyMap()\n"
},
{
"answer_id": 64164,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 6,
"selected": false,
"text": "java.util.Arrays List<Integer> ints = Arrays.asList(1,2,3);\n"
},
{
"answer_id": 64274,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 3,
"selected": false,
"text": "finally return int getCount() { \n try { return 1; }\n finally { System.out.println(\"Bye!\"); }\n}\n final int foo;\nif(...)\n foo = 1;\nelse\n throw new Exception();\nfoo+1;\n"
},
{
"answer_id": 64618,
"author": "James A. N. Stauffer",
"author_id": 6770,
"author_profile": "https://Stackoverflow.com/users/6770",
"pm_score": 7,
"selected": false,
"text": "public static void doSomething() {\n try {\n //Normally you would have code that doesn't explicitly appear \n //to throw exceptions so it would be harder to see the problem.\n throw new RuntimeException();\n } finally {\n return;\n }\n }\n"
},
{
"answer_id": 75519,
"author": "18Rabbit",
"author_id": 12662,
"author_profile": "https://Stackoverflow.com/users/12662",
"pm_score": 5,
"selected": false,
"text": "// For each Object, instantiated as foo, in myCollection\nfor(Object foo: myCollection) {\n System.out.println(foo.toString());\n}\n for (Suit suit : suits)\n for (Rank rank : ranks)\n sortedDeck.add(new Card(suit, rank));\n // Returns the sum of the elements of a\nint sum(int[] a) {\n int result = 0;\n for (int i : a)\n result += i;\n return result;\n}\n"
},
{
"answer_id": 76317,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 3,
"selected": false,
"text": "int const = 1; // \"not a statement\"\nconst int i = 1; // \"illegal start of expression\"\n"
},
{
"answer_id": 82236,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": false,
"text": "class Example\n{\n public static void main(String[] args)\n {\n System.out.println(\"Hello World!\");\n http://Phi.Lho.free.fr\n\n System.exit(0);\n }\n}\n"
},
{
"answer_id": 83113,
"author": "Chris Mazzola",
"author_id": 15816,
"author_profile": "https://Stackoverflow.com/users/15816",
"pm_score": 7,
"selected": false,
"text": "kill -3 PID"
},
{
"answer_id": 101659,
"author": "Tahir Akhtar",
"author_id": 18027,
"author_profile": "https://Stackoverflow.com/users/18027",
"pm_score": 6,
"selected": false,
"text": "import java.util.Comparator;\n\npublic class ContainerClass {\nboolean sortAscending;\npublic Comparator createComparator(final boolean sortAscending){\n Comparator comparator = new Comparator<Integer>() {\n\n public int compare(Integer o1, Integer o2) {\n if (sortAscending || ContainerClass.this.sortAscending) {\n return o1 - o2;\n } else {\n return o2 - o1;\n }\n }\n\n };\n return comparator;\n}\n}\n"
},
{
"answer_id": 101851,
"author": "Das",
"author_id": 17585,
"author_profile": "https://Stackoverflow.com/users/17585",
"pm_score": 6,
"selected": false,
"text": "public class UnsafeUtil {\n\n public static Unsafe unsafe;\n private static long fieldOffset;\n private static UnsafeUtil instance = new UnsafeUtil();\n\n private Object obj;\n\n static {\n try {\n Field f = Unsafe.class.getDeclaredField(\"theUnsafe\");\n f.setAccessible(true);\n\n unsafe = (Unsafe)f.get(null);\n fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField(\"obj\"));\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n };\n}\n"
},
{
"answer_id": 107067,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public class Example\n{\n public static void main(String[] Args)\n {\n int a = 5;\n Integer b = a; // Box!\n System.out.println(\"A : \" + a);\n System.out.println(\"B : \" + b);\n }\n}\n"
},
{
"answer_id": 129378,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 3,
"selected": false,
"text": "load() String realProp = new String(prop.getBytes(\"ISO-8859-1\"), \"UTF-8\");\n load() store()"
},
{
"answer_id": 137600,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 5,
"selected": false,
"text": "public void setFoo(Foo aFoo){\n Foo old = this.foo;\n this.foo = aFoo;\n changeSupport.firePropertyChange(\"foo\", old, aFoo);\n}\n public void setFoo(Foo aFoo){\n changeSupport.firePropertyChange(\"foo\", this.foo, this.foo = aFoo);\n}\n"
},
{
"answer_id": 139379,
"author": "Martin Spamer",
"author_id": 15527,
"author_profile": "https://Stackoverflow.com/users/15527",
"pm_score": 3,
"selected": false,
"text": "Class.forName( className ).newInstance();\n this.getClass().getClassLoader().getResourceAsStream( ... ) ;\n"
},
{
"answer_id": 142676,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": false,
"text": "private void writeObject(ObjectOutputStream out) throws IOException;\nprivate void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;\n"
},
{
"answer_id": 146121,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 4,
"selected": false,
"text": "public Foo foo(String in) {\n class FooFormat extends Format {\n public Object parse(String s, ParsePosition pp) { // parse stuff }\n }\n return (Foo) new FooFormat().parse(in);\n\n}\n"
},
{
"answer_id": 169064,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 6,
"selected": false,
"text": "public Object getElementAt(int index) {\n final Object element;\n if (index == 0) {\n element = \"Result 1\";\n } else if (index == 1) {\n element = \"Result 2\";\n } else {\n element = \"Result 3\";\n }\n return element;\n}\n"
},
{
"answer_id": 229899,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 3,
"selected": false,
"text": " final String foo = \"42\";\n new Thread() {\n public void run() {\n dowhatever(foo);\n }\n }.start();\n"
},
{
"answer_id": 238827,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 5,
"selected": false,
"text": "new URL(\"http://www.yahoo.com\").equals(new URL(\"http://209.191.93.52\"))\n true"
},
{
"answer_id": 238837,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 6,
"selected": false,
"text": "Map map = new HashMap() {{\n put(\"a key\", \"a value\");\n put(\"another key\", \"another value\");\n}};\n JFrame frame = new JFrame();\n\nJPanel panel = new JPanel(); \n\npanel.add( new JLabel(\"Hey there\"){{ \n setBackground(Color.black);\n setForeground( Color.white);\n}});\n\npanel.add( new JButton(\"Ok\"){{\n addActionListener( new ActionListener(){\n public void actionPerformed( ActionEvent ae ){\n System.out.println(\"Button pushed\");\n }\n });\n }});\n\n\n frame.add( panel );\n JFrame frame = new JFrame(){{\n add( new JPanel(){{\n add( new JLabel(\"Hey there\"){{ \n setBackground(Color.black);\n setForeground( Color.white);\n }});\n\n add( new JButton(\"Ok\"){{\n addActionListener( new ActionListener(){\n public void actionPerformed( ActionEvent ae ){\n System.out.println(\"Button pushed\");\n }\n });\n }});\n }});\n }};\n"
},
{
"answer_id": 259287,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": 7,
"selected": false,
"text": "public void foo(String... bars) {\n for (String bar: bars)\n System.out.println(bar);\n}\n"
},
{
"answer_id": 321782,
"author": "David Koelle",
"author_id": 2197,
"author_profile": "https://Stackoverflow.com/users/2197",
"pm_score": 3,
"selected": false,
"text": "class Thing {\n private int x;\n\n public int addThings(Thing t2) {\n return this.x + t2.x; // Can access t2's private value!\n }\n}\n"
},
{
"answer_id": 404567,
"author": "Romain Guy",
"author_id": 298575,
"author_profile": "https://Stackoverflow.com/users/298575",
"pm_score": 4,
"selected": false,
"text": "final boolean[] result = new boolean[1];\nSwingUtilities.invokeAndWait(new Runnable() {\n public void run() { result[0] = true; }\n});\n"
},
{
"answer_id": 457863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "if( null != aObject && aObject instanceof String )\n{\n ...\n}\n if( aObject instanceof String )\n{\n ...\n}\n"
},
{
"answer_id": 512216,
"author": "Sarel Botha",
"author_id": 35264,
"author_profile": "https://Stackoverflow.com/users/35264",
"pm_score": 3,
"selected": false,
"text": "String w = \"world\";\nString s = String.format(\"Hello %s %d\", w, 3);\n"
},
{
"answer_id": 512368,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "List<String> myList = list(\"foo\", \"bar\");\nSet<String> mySet = set(\"foo\", \"bar\");\nMap<String, String> myMap = map(v(\"foo\", \"2\"), v(\"bar\", \"3\"));\n"
},
{
"answer_id": 556664,
"author": "youri",
"author_id": 16805,
"author_profile": "https://Stackoverflow.com/users/16805",
"pm_score": 4,
"selected": false,
"text": "package package.name;\n\npublic class util {\n\n private static void doStuff1(){\n //the end\n }\n\n private static String doStuff2(){\n return \"the end\";\n }\n\n}\n import static package.name.util.*;\n\npublic class main{\n\n public static void main(String[] args){\n doStuff1(); // wee no more typing util.doStuff1()\n System.out.print(doStuff2()); // or util.doStuff2()\n }\n\n}\n import static java.lang.Math.*;\nimport static java.lang.System.out;\npublic class HelloWorld {\n public static void main(String[] args) {\n out.println(\"Hello World!\");\n out.println(\"Considering a circle with a diameter of 5 cm, it has:\");\n out.println(\"A circumference of \" + (PI * 5) + \"cm\");\n out.println(\"And an area of \" + (PI * pow(5,2)) + \"sq. cm\");\n }\n}\n"
},
{
"answer_id": 556756,
"author": "chillitom",
"author_id": 56679,
"author_profile": "https://Stackoverflow.com/users/56679",
"pm_score": 4,
"selected": false,
"text": " list.subList(from, to).clear();\n"
},
{
"answer_id": 556772,
"author": "Rahel Lüthy",
"author_id": 57448,
"author_profile": "https://Stackoverflow.com/users/57448",
"pm_score": 5,
"selected": false,
"text": "java.lang.Void Callable<Void>"
},
{
"answer_id": 562852,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 7,
"selected": false,
"text": "public interface Room {\n public Room north();\n public Room south();\n public Room east();\n public Room west();\n}\n\npublic enum Rooms implements Room {\n FIRST {\n public Room north() {\n return SECOND;\n }\n },\n SECOND {\n public Room south() {\n return FIRST;\n }\n }\n\n public Room north() { return null; }\n public Room south() { return null; }\n public Room east() { return null; }\n public Room west() { return null; }\n}\n public enum AffinityStrategies implements AffinityStrategy {\n enum"
},
{
"answer_id": 574522,
"author": "paulmurray",
"author_id": 63189,
"author_profile": "https://Stackoverflow.com/users/63189",
"pm_score": 3,
"selected": false,
"text": "enum Foo1 implements Bar {}\nenum Foo2 implements Bar {}\n\nclass HelperClass {\n static <T extends Enum<T> & Bar> void fooBar(T the enum) {}\n}\n enum PrimaryColor {Red, Green, Blue;}\nenum PastelColor {Pink, HotPink, Rockmelon, SkyBlue, BabyBlue;}\n\nenum TransportMedium {Land, Sea, Air;}\nenum Vehicle {Car, Truck, BigBoat, LittleBoat, JetFighter, HotAirBaloon;}\n import java.util.EnumSet;\n\nimport javax.swing.JComponent;\n\npublic class zz extends JComponent {\n\n public static void main(String[] args) {\n System.out.println(PrimaryColor.Green + \" \" + ParentUtil.pctOf(PrimaryColor.Green) + \"%\");\n System.out.println(TransportMedium.Air + \" \" + ParentUtil.pctOf(TransportMedium.Air) + \"%\");\n }\n\n\n}\n\nclass ParentUtil {\n private ParentUtil(){}\n static <P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> //\n float pctOf(P parent) {\n return (float) parent.getChildren().size() / //\n (float) EnumSet.allOf(parent.getChildClass()).size() //\n * 100f;\n }\n public static <P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> //\n EnumSet<C> loadChildrenOf(P p) {\n EnumSet<C> cc = EnumSet.noneOf(p.getChildClass());\n for(C c: EnumSet.allOf(p.getChildClass())) {\n if(c.getParent() == p) {\n cc.add(c);\n }\n }\n return cc;\n }\n}\n\ninterface Parent<P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> {\n Class<C> getChildClass();\n\n EnumSet<C> getChildren();\n}\n\ninterface Child<P extends Enum<P> & Parent<P, C>, C extends Enum<C> & Child<P, C>> {\n Class<P> getParentClass();\n\n P getParent();\n}\n\nenum PrimaryColor implements Parent<PrimaryColor, PastelColor> {\n Red, Green, Blue;\n\n private EnumSet<PastelColor> children;\n\n public Class<PastelColor> getChildClass() {\n return PastelColor.class;\n }\n\n public EnumSet<PastelColor> getChildren() {\n if(children == null) children=ParentUtil.loadChildrenOf(this);\n return children;\n }\n}\n\nenum PastelColor implements Child<PrimaryColor, PastelColor> {\n Pink(PrimaryColor.Red), HotPink(PrimaryColor.Red), //\n Rockmelon(PrimaryColor.Green), //\n SkyBlue(PrimaryColor.Blue), BabyBlue(PrimaryColor.Blue);\n\n final PrimaryColor parent;\n\n private PastelColor(PrimaryColor parent) {\n this.parent = parent;\n }\n\n public Class<PrimaryColor> getParentClass() {\n return PrimaryColor.class;\n }\n\n public PrimaryColor getParent() {\n return parent;\n }\n}\n\nenum TransportMedium implements Parent<TransportMedium, Vehicle> {\n Land, Sea, Air;\n\n private EnumSet<Vehicle> children;\n\n public Class<Vehicle> getChildClass() {\n return Vehicle.class;\n }\n\n public EnumSet<Vehicle> getChildren() {\n if(children == null) children=ParentUtil.loadChildrenOf(this);\n return children;\n }\n}\n\nenum Vehicle implements Child<TransportMedium, Vehicle> {\n Car(TransportMedium.Land), Truck(TransportMedium.Land), //\n BigBoat(TransportMedium.Sea), LittleBoat(TransportMedium.Sea), //\n JetFighter(TransportMedium.Air), HotAirBaloon(TransportMedium.Air);\n\n private final TransportMedium parent;\n\n private Vehicle(TransportMedium parent) {\n this.parent = parent;\n }\n\n public Class<TransportMedium> getParentClass() {\n return TransportMedium.class;\n }\n\n public TransportMedium getParent() {\n return parent;\n }\n}\n"
},
{
"answer_id": 851055,
"author": "David Plumpton",
"author_id": 16709,
"author_profile": "https://Stackoverflow.com/users/16709",
"pm_score": 3,
"selected": false,
"text": "http://google.com\n"
},
{
"answer_id": 945115,
"author": "Huxi",
"author_id": 115167,
"author_profile": "https://Stackoverflow.com/users/115167",
"pm_score": 3,
"selected": false,
"text": "public class Foo {\n private int bar;\n\n public Foo() {\n setBar(17);\n }\n\n private void setBar(int bar) {\n this.bar=bar;\n }\n\n public int getBar() {\n return bar;\n }\n\n public String toString() {\n return \"Foo[bar=\"+bar+\"]\";\n }\n}\n import java.lang.reflect.*;\n\npublic class AccessibleExample {\n public static void main(String[] args)\n throws NoSuchMethodException,IllegalAccessException, InvocationTargetException, NoSuchFieldException {\n Foo foo=new Foo();\n System.out.println(foo);\n\n Method method=Foo.class.getDeclaredMethod(\"setBar\", int.class);\n method.setAccessible(true);\n method.invoke(foo, 42);\n\n System.out.println(foo);\n Field field=Foo.class.getDeclaredField(\"bar\");\n field.setAccessible(true);\n field.set(foo, 23);\n System.out.println(foo);\n }\n}\n Foo[bar=17]\nFoo[bar=42]\nFoo[bar=23]\n"
},
{
"answer_id": 949397,
"author": "AaronG",
"author_id": 86001,
"author_profile": "https://Stackoverflow.com/users/86001",
"pm_score": 4,
"selected": false,
"text": "String s = \"A\";\ns += \" String\"; // so s == \"A String\"\n String s = new String(\"A\");\ns = new StringBuffer(s).append(\" String\").toString();\n String s = \"\";\nfor (int i = 0 ; i < 1000 ; ++i)\n s += \" \" + i; // Really an Object instantiation & 3 method invocations!\n StringBuilder buf = new StringBuilder(); // Empty buffer\nfor (int i = 0 ; i < 1000 ; ++i)\n buf.append(' ').append(i); // Cut out the object instantiation & reduce to 2 method invocations\nString s = buf.toString();\n"
},
{
"answer_id": 1025199,
"author": "Ron",
"author_id": 61572,
"author_profile": "https://Stackoverflow.com/users/61572",
"pm_score": 6,
"selected": false,
"text": "new Object() {\n void foo(String s) {\n System.out.println(s);\n }\n}.foo(\"Hello\");\n"
},
{
"answer_id": 1025306,
"author": "Dave Jarvis",
"author_id": 59087,
"author_profile": "https://Stackoverflow.com/users/59087",
"pm_score": 3,
"selected": false,
"text": "public class Slow {\n /** Loop counter; initialized to 0. */\n private long i;\n\n public static void main( String args[] ) {\n Slow slow = new Slow();\n\n slow.run();\n }\n\n private void run() {\n while( i++ < 10000000000L )\n ;\n }\n}\n public class Fast {\n /** Loop counter; initialized to 0. */\n private long i;\n\n public static void main( String args[] ) {\n Fast fast = new Fast();\n\n fast.run();\n }\n\n private void run() {\n long i = getI();\n\n while( i++ < 10000000000L )\n ;\n\n setI( i );\n }\n\n private long setI( long i ) {\n this.i = i;\n }\n\n private long getI() {\n return this.i;\n }\n}\n slow.setI( 0 )"
},
{
"answer_id": 1276933,
"author": "Ivan Tarasov",
"author_id": 110225,
"author_profile": "https://Stackoverflow.com/users/110225",
"pm_score": 3,
"selected": false,
"text": "compareAndSet final AtomicBoolean dataMsgReceived = new AtomicBoolean(false);\nfinal AtomicReference<Message> message = new AtomicReference<Message>();\nwithMessageHandler(new MessageHandler() {\n public void handleMessage(Message msg) {\n if (msg.isData()) {\n synchronized (dataMsgReceived) {\n message.set(msg);\n dataMsgReceived.set(true);\n dataMsgReceived.notifyAll();\n }\n }\n }\n}, new Interruptible() {\n public void run() throws InterruptedException {\n synchronized (dataMsgReceived) {\n while (!dataMsgReceived.get()) {\n dataMsgReceived.wait();\n }\n }\n }\n});\n waitMessageHandler(…) private final AtomicReference<MessageHandler> messageHandler = new AtomicReference<MessageHandler>();\npublic void withMessageHandler(MessageHandler handler, Interruptible logic) throws InterruptedException {\n synchronized (messageHandler) {\n try {\n messageHandler.set(handler);\n logic.run();\n } finally {\n messageHandler.set(null);\n }\n }\n}\n handleMessage(…)"
},
{
"answer_id": 1305616,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "int[] arr = {1, 2, 3};\nint[] arr2 = arr.clone();\n"
},
{
"answer_id": 1674342,
"author": "Lastnico",
"author_id": 201554,
"author_profile": "https://Stackoverflow.com/users/201554",
"pm_score": 3,
"selected": false,
"text": "StringBuilder StringBuffer StringBuilder Map<String, List<String>> anagrams = new HashMap<String, List<String>>();\n\n// Can now be replaced with this:\n\nMap<String, List<String>> anagrams = new HashMap<>();\n String s = \"something\";\nswitch(s) {\n case \"quux\":\n processQuux(s);\n // fall-through\n\n case \"foo\":\n case \"bar\":\n processFooOrBar(s);\n break;\n\n case \"baz\":\n processBaz(s);\n // fall-through\n\n default:\n processDefault(s);\n break;\n}\n static void copy(String src, String dest) throws IOException {\n InputStream in = new FileInputStream(src);\n try {\n OutputStream out = new FileOutputStream(dest);\n try {\n byte[] buf = new byte[8 * 1024];\n int n;\n while ((n = in.read(buf)) >= 0)\n out.write(buf, 0, n);\n } finally {\n out.close();\n }\n } finally {\n in.close();\n }\n}\n static void copy(String src, String dest) throws IOException {\n try (InputStream in = new FileInputStream(src);\n OutputStream out = new FileOutputStream(dest)) {\n byte[] buf = new byte[8192];\n int n;\n while ((n = in.read(buf)) >= 0)\n out.write(buf, 0, n);\n }\n}\n"
},
{
"answer_id": 1807455,
"author": "kcak11",
"author_id": 218432,
"author_profile": "https://Stackoverflow.com/users/218432",
"pm_score": 4,
"selected": false,
"text": "java javaw -splash java -splash:C:\\myfolder\\myimage.png -classpath myjarfile.jar com.my.package.MyClass\n C:\\myfolder\\myimage.png"
},
{
"answer_id": 1859579,
"author": "crowne",
"author_id": 97745,
"author_profile": "https://Stackoverflow.com/users/97745",
"pm_score": 7,
"selected": false,
"text": "java -classpath ./lib/* so.Main\n java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main\n"
},
{
"answer_id": 1918613,
"author": "SRG",
"author_id": 195463,
"author_profile": "https://Stackoverflow.com/users/195463",
"pm_score": 5,
"selected": false,
"text": " Runtime.getRuntime().addShutdownHook(new Thread() {\n public void run() {\n endApp();\n }\n });;\n"
},
{
"answer_id": 2034744,
"author": "stacker",
"author_id": 241590,
"author_profile": "https://Stackoverflow.com/users/241590",
"pm_score": 3,
"selected": false,
"text": "String title=\"\";\n String Überschrift=\"\";\n"
},
{
"answer_id": 2121023,
"author": "Karussell",
"author_id": 194609,
"author_profile": "https://Stackoverflow.com/users/194609",
"pm_score": 3,
"selected": false,
"text": "Integer a = 1;\nInteger b = 1;\nInteger c = new Integer(1);\nInteger d = new Integer(1);\n\nInteger e = 128;\nInteger f = 128;\n\nassertTrue (a == b); // again: this is true!\nassertFalse(e == f); // again: this is false!\nassertFalse(c == d); // again: this is false!\n"
},
{
"answer_id": 2131355,
"author": "Luigi R. Viggiano",
"author_id": 258289,
"author_profile": "https://Stackoverflow.com/users/258289",
"pm_score": 5,
"selected": false,
"text": "import java.rmi.RemoteException;\n\nclass Thrower {\n public static void spit(final Throwable exception) {\n class EvilThrower<T extends Throwable> {\n @SuppressWarnings(\"unchecked\")\n private void sneakyThrow(Throwable exception) throws T {\n throw (T) exception;\n }\n }\n new EvilThrower<RuntimeException>().sneakyThrow(exception);\n }\n}\n\npublic class ThrowerSample {\n public static void main( String[] args ) {\n Thrower.spit(new RemoteException(\"go unchecked!\"));\n }\n}\n public static void main(String[] args) {\n throw null;\n}\n Long value = new Long(0);\nSystem.out.println(value.equals(0));\n public int returnSomething() {\n try {\n throw new RuntimeException(\"foo!\");\n } finally {\n return 0;\n }\n}\n String[] strings = new String[] { \"foo\", \"bar\" };\n// the above is equivalent to the following:\nString[] strings = { \"foo\", \"bar\" };\n public class Foo {\n public void doSomething(String[] arg) {}\n\n public void example() {\n String[] strings = { \"foo\", \"bar\" };\n doSomething(strings);\n }\n}\n public class Foo {\n\n public void doSomething(String[] arg) {}\n\n public void example() {\n doSomething({ \"foo\", \"bar\" });\n }\n}\n"
},
{
"answer_id": 2372429,
"author": "Yanamon",
"author_id": 282693,
"author_profile": "https://Stackoverflow.com/users/282693",
"pm_score": 2,
"selected": false,
"text": "Class<T> public interface SomeInterface {\n void doSomething(Object o);\n}\npublic abstract class RuntimeCheckingTemplate<T> {\n private Class<T> clazz;\n protected RuntimeChecking(Class<T> clazz) {\n this.clazz = clazz;\n }\n\n public void doSomething(Object o) {\n if (clazz.isInstance(o)) {\n doSomethingWithGeneric(clazz.cast(o));\n } else {\n // log it, do something by default, throw an exception, etc.\n }\n }\n\n protected abstract void doSomethingWithGeneric(T t);\n}\n\npublic class ClassThatWorksWithStrings extends RuntimeCheckingTemplate<String> {\n public ClassThatWorksWithStrings() {\n super(String.class);\n }\n\n protected abstract void doSomethingWithGeneric(T t) {\n // Do something with the generic and know that a runtime exception won't occur \n // because of a wrong type\n }\n}\n"
},
{
"answer_id": 2607251,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "minVal = (a < b) ? a : b;\n"
},
{
"answer_id": 3004405,
"author": "mbenturk",
"author_id": 210705,
"author_profile": "https://Stackoverflow.com/users/210705",
"pm_score": 3,
"selected": false,
"text": "String input = \"1 fish 2 fish red fish blue fish\";\nScanner s = new Scanner(input).useDelimiter(\"\\\\s*fish\\\\s*\");\nSystem.out.println(s.nextInt());\nSystem.out.println(s.nextInt());\nSystem.out.println(s.next());\nSystem.out.println(s.next());\ns.close();\n"
},
{
"answer_id": 3089101,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 4,
"selected": false,
"text": "(new Object() {\n public String someMethod(){ \n return \"some value\";\n }\n}).someMethod();\n"
},
{
"answer_id": 3130075,
"author": "Jason Wang",
"author_id": 144282,
"author_profile": "https://Stackoverflow.com/users/144282",
"pm_score": 4,
"selected": false,
"text": "public int aMethod(){\n http://www.google.com\n return 1;\n}\n"
},
{
"answer_id": 3147440,
"author": "st0le",
"author_id": 216517,
"author_profile": "https://Stackoverflow.com/users/216517",
"pm_score": 4,
"selected": false,
"text": "System.out.printf(\"%d %f %.4f\", 3,Math.E,Math.E);\n int[] q = new int[] { 1,3,4,5};\nint position = Arrays.binarySearch(q, 2);\n"
},
{
"answer_id": 3181454,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "public class WithoutMain {\n static {\n System.out.println(\"Look ma, no main!!\");\n System.exit(0);\n }\n}\n\n$ java WithoutMain\nLook ma, no main!!\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/486/"
] |
15,513 |
<p>I've been tasked with <em>improving the performance of an ASP.NET 2.0 application</em>.<br> The page I'm currently focused on has many problems but one that I'm having trouble digging into is the render time of the page. Using Trace.axd the duration between Begin Render and End Render is 1.4 seconds. From MSDN I see that</p>
<blockquote>
<p>All ASP.NET Web server controls have a
Render method that writes out the
control's markup that is sent to the
browser.</p>
</blockquote>
<p>If I had the source code for all the controls on the page, I would just instrument them to trace out their render time. Unfortunately, this particular page has lots of controls, most of them third-party. Is there tool or technique to get better visibility into what is going on during the render? I would like to know if there is a particularly poorly performing control, or if there are simply too many controls on the page.</p>
|
[
{
"answer_id": 15516,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<%@Page Trace=\"true\" %>\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1767/"
] |
15,514 |
<p>In my example below I'm using a <code>dijit.form.DateTextBox</code>:</p>
<pre><code><input type="text" name="startDate" dojoType="dijit.form.DateTextBox" constraints="{datePattern:'MM/dd/yyyy'}" value='<c:out value="${sessionScope.adminMessageForm.startDate}"/>' />
</code></pre>
<p>So for example, if the user starts to enter "asdf" into the date the field turns yellow and a popup error message appears saying <code>The value entered is not valid.</code>. Even if I remove the <code>constraints="{datePattern:'MM/dd/yyyy'}"</code> it still validates. </p>
<p>Without going into details as to why, I would like to be able keep the dojoType and still prevent validation in particular circumstances.</p>
|
[
{
"answer_id": 15677,
"author": "RodeoClown",
"author_id": 943,
"author_profile": "https://Stackoverflow.com/users/943",
"pm_score": 4,
"selected": true,
"text": "<input type=\"text\" name=\"startDate\" dojoType=\"dijit.form.DateTextBox\" \n constraints=\"{datePattern:'MM/dd/yyyy'}\" \n value='<c:out value=\"${sessionScope.adminMessageForm.startDate}\"/>'\n validate='return true;'\n/>\n"
},
{
"answer_id": 59751,
"author": "esarjeant",
"author_id": 644,
"author_profile": "https://Stackoverflow.com/users/644",
"pm_score": 1,
"selected": false,
"text": " enableValidator:function() {\n this.validatorOn = true;\n },\n\n disableValidator: function() {\n this.validatorOn = false;\n },\n if (this.validatorOn)\n { ... }\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/700/"
] |
15,537 |
<p>If I press <kbd>Ctrl</kbd>+<kbd>B</kbd> that ought to give me ASCII code 2, but <kbd>Ctrl</kbd>+<kbd>C</kbd> is going to be interpreted as a Break.</p>
<p>So I figure I've got to redirect a file in. How do I get these characters into a file?</p>
|
[
{
"answer_id": 15542,
"author": "Steve M",
"author_id": 1693,
"author_profile": "https://Stackoverflow.com/users/1693",
"pm_score": 2,
"selected": false,
"text": "perl -e 'print \"\\xFF\"'\n FF"
},
{
"answer_id": 15574,
"author": "Daniel Fone",
"author_id": 1848,
"author_profile": "https://Stackoverflow.com/users/1848",
"pm_score": 3,
"selected": false,
"text": "echo $'\\002\\003' > ./myfile\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/257/"
] |
15,593 |
<p>I understand what <a href="http://msdn.microsoft.com/en-us/library/ms404247.aspx" rel="noreferrer">System.WeakReference</a> does, but what I can't seem to grasp is a practical example of what it might be useful for. The class itself seems to me to be, well, a hack. It seems to me that there are other, better means of solving a problem where a WeakReference is used in examples I've seen. What's the canonical example of where you've really got to use a WeakReference? Aren't we trying to get <i>farther</i> away from this type of behavior and use of this class? </p>
|
[
{
"answer_id": 15616,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "class Cache<TKey,TValue> : IEnumerable<KeyValuePair<TKey,TValue>>\n{ Dictionary<TKey,WeakReference> dict = new Dictionary<TKey,WeakReference>();\n\n public TValue this[TKey key]\n { get {lock(dict){ return getInternal(key);}}\n set {lock(dict){ setInteral(key,value);}} \n }\n\n void setInteral(TKey key, TValue val)\n { if (dict.ContainsKey(key)) dict[key].Target = val;\n else dict.Add(key,new WeakReference(val));\n } \n\n\n public void Clear() { dict.Clear(); }\n\n /// <summary>Removes any dead weak references</summary>\n /// <returns>The number of cleaned-up weak references</returns>\n public int CleanUp()\n { List<TKey> toRemove = new List<TKey>(dict.Count);\n foreach(KeyValuePair<TKey,WeakReference> kv in dict)\n { if (!kv.Value.IsAlive) toRemove.Add(kv.Key);\n }\n\n foreach (TKey k in toRemove) dict.Remove(k);\n return toRemove.Count;\n }\n\n public bool Contains(string key) \n { lock (dict) { return containsInternal(key); }\n }\n\n bool containsInternal(TKey key)\n { return (dict.ContainsKey(key) && dict[key].IsAlive);\n }\n\n public bool Exists(Predicate<TValue> match) \n { if (match==null) throw new ArgumentNullException(\"match\");\n\n lock (dict)\n { foreach (WeakReference weakref in dict.Values) \n { if ( weakref.IsAlive \n && match((TValue) weakref.Target)) return true;\n } \n }\n\n return false;\n }\n\n /* ... */\n }\n"
},
{
"answer_id": 15627,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 7,
"selected": true,
"text": "public MyForm()\n{\n MyApplication.Foo += someHandler;\n}\n"
},
{
"answer_id": 347508,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 2,
"selected": false,
"text": "Dictionary<myobject, myvalue> Dictionary<WeakReference,myvalue>"
},
{
"answer_id": 12124101,
"author": "hIpPy",
"author_id": 58678,
"author_profile": "https://Stackoverflow.com/users/58678",
"pm_score": 0,
"selected": false,
"text": "WeakReference AppDomain WeakReference WeakReference wrStaticObject staticObject class ThingsWrapper {\n //private static object staticObject = new object();\n private static WeakReference wrStaticObject \n = new WeakReference(new object());\n}\n class StaticGarbageTest\n{\n public static void Main1()\n {\n var s = new ThingsWrapper();\n s = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n }\n}\nclass ThingsWrapper\n{\n private static Thing staticThing = new Thing(\"staticThing\");\n private Thing privateThing = new Thing(\"privateThing\");\n ~ThingsWrapper()\n { Console.WriteLine(\"~ThingsWrapper\"); }\n}\nclass Thing\n{\n protected string name;\n public Thing(string name) {\n this.name = name;\n Console.WriteLine(\"Thing() \" + name);\n }\n public override string ToString() { return name; }\n ~Thing() { Console.WriteLine(\"~Thing() \" + name); }\n}\n staticThing ThingsWrapper AppDomain Thing() staticThing\nThing() privateThing\n~Thing() privateThing\n~ThingsWrapper\n~Thing() staticThing\n Thing WeakReference wrStaticThing class WeakReferenceTest\n{\n public static void Main1()\n {\n var s = new WeakReferenceThing();\n s = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n if (WeakReferenceThing.wrStaticThing.IsAlive)\n Console.WriteLine(\"WeakReference: {0}\", \n (Thing)WeakReferenceThing.wrStaticThing.Target);\n else \n Console.WriteLine(\"WeakReference is dead.\");\n }\n}\nclass WeakReferenceThing\n{\n public static WeakReference wrStaticThing;\n static WeakReferenceThing()\n { wrStaticThing = new WeakReference(new Thing(\"wrStaticThing\")); }\n ~WeakReferenceThing()\n { Console.WriteLine(\"~WeakReferenceThing\"); }\n //lazy-loaded method to new Thing\n}\n wrStaticThing Thing() wrStaticThing\n~Thing() wrStaticThing\n~WeakReferenceThing\nWeakReference is dead.\n WeakReference"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1875/"
] |
15,621 |
<p>I have a few C# <code>.dll</code> projects which are common to many applications. Currently, I have one big repository. I have each DLL stored as a separate project within the repository and every application project stored as a project within the same repository.</p>
<p>I recently switched to Subversion for source control and I fear that I did not do a good job of structuring the repository. I would like to hear what others are doing.</p>
|
[
{
"answer_id": 15633,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 3,
"selected": false,
"text": "branch/\ntags/\ntrunk/\n branch/\ntags/\ntrunk/\n project1/\n project2/\n project1/\n branch/\n tags/\n trunk/\n\nproject2/\n branch/\n tags/\n trunk/\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1511/"
] |
15,656 |
<p>Another SSRS question here: <br />
We have a development, a QA, a Prod-Backup and a Production SSRS set of servers. <br />
On our production and prod-backup, SSRS will go to sleep if not used for a period of time. <br /><br />
This does not occur on our development or QA server.
<br />In the corporate environment we're in, we don't have physical (or even remote login) access to these machines, and have to work with a team of remote administrators to configure our SSRS application.<br />
<br /> We have asked that they fix, if possible, this issue. So far, they haven't been able to identify the issue, and I would like to know if any of my peers know the answer to this question. Thanks.</p>
|
[
{
"answer_id": 10721575,
"author": "Lynn Crumbling",
"author_id": 656243,
"author_profile": "https://Stackoverflow.com/users/656243",
"pm_score": 5,
"selected": false,
"text": "C:\\Program Files\\Microsoft SQL Server\\\n MSRS10_50.MSSQLSERVER\\Reporting Services\\ReportServer\\rsreportserver.config\n RecycleTime"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1580/"
] |
15,674 |
<p>When using Subversion (svn) for source control with multiple projects I've noticed that the revision number increases across all of my projects' directories. To illustrate my svn layout (using fictitious project names): </p>
<pre>
/NinjaProg/branches
/tags
/trunk
/StealthApp/branches
/tags
/trunk
/SnailApp/branches
/tags
/trunk
</pre>
<p>When I perform a commit to the trunk of the Ninja Program, let's say I get that it has been updated to revision 7. The next day let's say that I make a small change to the Stealth Application and it comes back as revision 8.</p>
<p>The question is this: <strong>Is it common accepted practice to, when maintaining multiple projects with one Subversion server, to have unrelated projects' revision number increase across all projects?</strong> Or am I doing it wrong and should be creating individual repositories for each project? Or is it something else entirely?</p>
<p><strong>EDIT:</strong> I delayed in flagging an answer because it had become clear that there are reasons for both approaches, and even though this question came first, I'd like to point to some other questions that are ultimately asking the same question: </p>
<p><a href="https://stackoverflow.com/questions/130447/should-i-store-all-projects-in-one-repository-or-mulitiple">Should I store all projects in one repository or mulitiple?</a></p>
<p><a href="https://stackoverflow.com/questions/252459/one-svn-repository-or-many">One SVN Repository or many?</a> </p>
|
[
{
"answer_id": 16057,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 2,
"selected": false,
"text": "<Location /svn>\n DAV svn\n SVNParentPath /var/www/svn\n\n AuthType Basic\n AuthName \"Subversion Repository\"\n AuthUserFile /var/www/svn/password\n Require valid-user\n</Location>\n svnadmin create /var/www/svn/myproject\n"
},
{
"answer_id": 26836,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 2,
"selected": false,
"text": "svnadmin create /var/www/svn/myproject"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1339/"
] |
15,678 |
<p>I have a solution with several projects, where the startup project has a post-build event that does all the copying of "plugin" projects and other organizing tasks. After upgrading the solution from VS 2005 to VS 2008, it appears as though the post-build event only fires if I modify the startup project, which means my updated plugins don't get plugged in to the current debugging session. This makes sense, but it seems like a change in behavior. Is anyone else noticing a change in behavior with regard to which projects get built?</p>
<p>Does anyone know of a workaround that I can use to force the startup project to rebuild whenever I hit F5? Perhaps I configured VS 2005 to work this way so long ago that I've forgotten all about it ...</p>
|
[
{
"answer_id": 15699,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 2,
"selected": false,
"text": "devenv project.csproj /clean\n"
},
{
"answer_id": 3814728,
"author": "Cristian Diaconescu",
"author_id": 11545,
"author_profile": "https://Stackoverflow.com/users/11545",
"pm_score": 0,
"selected": false,
"text": "\"$(DevEnvDir)devenv.exe\" \"$(ProjectPath)\" /clean\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
] |
15,687 |
<p>So, you are all ready to do a big SVN Commit and it bombs because you have inconsistent line endings in some of your files. Fun part is, you're looking at 1,000s of files spanning dozens of folders of different depths.</p>
<p>What do you do?</p>
|
[
{
"answer_id": 9727551,
"author": "David W.",
"author_id": 368630,
"author_profile": "https://Stackoverflow.com/users/368630",
"pm_score": 3,
"selected": false,
"text": "$ find . -type f -name \"*.java\" -exec dos2unix {}\\;\n dos2unix svn:eol-style"
},
{
"answer_id": 59680444,
"author": "freshNfunky",
"author_id": 8124631,
"author_profile": "https://Stackoverflow.com/users/8124631",
"pm_score": 0,
"selected": false,
"text": "([^\\r])\\n $1\\r\\n *.xml;*.txt;*.csv;... \\n\\n \\n\\r\\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/307/"
] |
15,694 |
<p>I've recently been looking into targeting the .NET Client Profile for a WPF application I am building. However, I was frustrated to notice that the Client Profile is only valid for the following OS configurations: </p>
<ul>
<li>Windows XP SP2+</li>
<li><strike>Windows Server 2003</strike> <strong>Edit:</strong> <a href="http://blogs.windowsclient.net/trickster92/archive/2008/05/21/introducing-the-net-framework-client-profile.aspx" rel="nofollow noreferrer">Appears</a> the Client Profile will not install on Windows Server 2003.</li>
</ul>
<p>In addition, the client profile is <strong>not</strong> valid for x64 or ia64 editions; and will also not install if <em>any previous version of the .NET Framework has been installed</em>.</p>
<p>I'm wondering if the effort in adding the extra OS configurations to the testing matrix is worth the effort. Is there any metrics available that state the percentage of users that could possibly benefit from the client profile? I believe that once the .NET Framework has been installed, extra information is passed to a web server as part of a web request signifying that the framework is available. Granted, I would imagine that Windows XP SP2 users without the .NET Framework installed would be a large amount of people. It would then be a question of whether my application targeted those individuals specifically.</p>
<p>Has anyone else determined if it is worth the extra effort to target these specific users?</p>
<p><strong>Edit: It seems that it is possible to get a compiler warning if you use features not included in the Client Profile. As I usually run with warnings as errors, this will hopefully be enough to minimise testing in this configuration.</strong> Of course, this configuration will still need to be tested, but it should be as simple as testing if the install/initial run works on XP with SP2+.</p>
|
[
{
"answer_id": 15738,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 2,
"selected": false,
"text": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; .NET CLR 2.0.50727).\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
15,708 |
<p>One of my favourite tools for linux is <a href="http://en.wikipedia.org/wiki/Lsof" rel="noreferrer" title="Wikipedia">lsof</a> - a real swiss army knife!</p>
<p>Today I found myself wondering which programs on a WinXP system had a specific file open. Is there any equivalent utility to lsof? Additionally, the file in question was over a network share so I'm not sure if that complicates matters.</p>
|
[
{
"answer_id": 599268,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "lsof -p pid handle -p pid\nlistdlls -p pid\n pslist"
},
{
"answer_id": 731125,
"author": "Sean",
"author_id": 26095,
"author_profile": "https://Stackoverflow.com/users/26095",
"pm_score": 3,
"selected": false,
"text": "TaskList /M nameof.dll\n"
},
{
"answer_id": 9802841,
"author": "Alois Mahdal",
"author_id": 835945,
"author_profile": "https://Stackoverflow.com/users/835945",
"pm_score": 3,
"selected": false,
"text": "c:\\SysInternals>handle\n[...]\n------------------------------------------------------------------------------\ngvim.exe pid: 5380 FOO\\alois.mahdal\n 10: File (RW-) C:\\Windows\n 1C: File (RW-) D:\\some\\locked\\path\\OpenFile.txt\n[...]\n\nc:\\SysInternals>listdlls\n[...]\n------------------------------------------------------------------------------\nListdlls.exe pid: 6840\nCommand line: listdlls\n\n Base Size Version Path\n 0x00400000 0x29000 2.25.0000.0000 D:\\opt\\SysinternalsSuite\\Listdlls.exe\n 0x76ed0000 0x180000 6.01.7601.17725 C:\\Windows\\SysWOW64\\ntdll.dll\n[...]\n\nc:\\SysInternals>listdlls\n findstr /c:pid: /c:<filename> c:\\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm\nSystem pid: 4 \\<unable to open process>\nsmss.exe pid: 308 NT AUTHORITY\\SYSTEM\navgrsa.exe pid: 384 NT AUTHORITY\\SYSTEM\n[...]\ncmd.exe pid: 7140 FOO\\alois.mahdal\nconhost.exe pid: 1212 FOO\\alois.mahdal\ngvim.exe pid: 3408 FOO\\alois.mahdal\n 188: File (RW-) D:\\some\\locked\\path\\OpenFile.txt\ntaskmgr.exe pid: 6016 FOO\\alois.mahdal\n[...]\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1848/"
] |
15,709 |
<p>So for my text parsing in C# <a href="https://stackoverflow.com/questions/13963/best-method-of-textfile-parsing-in-c">question</a>, I got directed at YAML. I'm hitting a wall with this library I was recommended, so this is a quickie.</p>
<pre><code>heading:
name: A name
taco: Yes
age: 32
heading:
name: Another name
taco: No
age: 27
</code></pre>
<p>And so on. Is that valid?</p>
|
[
{
"answer_id": 15726,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 4,
"selected": false,
"text": "---\nheading:\n name: A name\n taco: Yes\n age: 32\n---\nheading:\n name: Another name\n taco: No\n age: 27\n - heading:\n name: A name\n taco: Yes\n age: 32\n- heading:\n name: Another name\n taco: No\n age: 27\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
15,716 |
<p>I have created a UserControl that has a <code>ListView</code> in it. The ListView is publicly accessible though a property. When I put the UserControl in a form and try to design the <code>ListView</code> though the property, the <code>ListView</code> stays that way until I compile again and it reverts back to the default state. </p>
<p>How do I get my design changes to stick for the <code>ListView</code>?</p>
|
[
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "public ListView MyListView { get { return this.listView1; } }\n"
},
{
"answer_id": 15803,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 4,
"selected": true,
"text": "[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic ListView MyListView { get { return this.listView1; } }\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15716",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/788/"
] |
15,729 |
<p>As I browse through the site, I find a lot of terms that many developers just starting out (and even some advanced developers) may be unfamiliar with.</p>
<p>It would be great if people could post here with a term and definition that might be unknown to beginners or those from different programming backgrounds. </p>
<p>Some not-so-common terms I've seen are 'auto boxing', 'tuples', 'orthogonal code', 'domain driven design', 'test driven development', etc.</p>
<p>Code snippets would also be helpful where applicable..</p>
|
[
{
"answer_id": 15717,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "public ListView MyListView { get { return this.listView1; } }\n"
},
{
"answer_id": 15803,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 4,
"selected": true,
"text": "[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic ListView MyListView { get { return this.listView1; } }\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] |
15,732 |
<p>I'm generating some xml files that needs to conform to an xsd file that was given to me. How should I verify they conform?</p>
|
[
{
"answer_id": 15739,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 5,
"selected": false,
"text": "import org.apache.xerces.parsers.DOMParser;\nimport java.io.File;\nimport org.w3c.dom.Document;\n\npublic class SchemaTest {\n public static void main (String args[]) {\n File docFile = new File(\"memory.xml\");\n try {\n DOMParser parser = new DOMParser();\n parser.setFeature(\"http://xml.org/sax/features/validation\", true);\n parser.setProperty(\n \"http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation\", \n \"memory.xsd\");\n ErrorChecker errors = new ErrorChecker();\n parser.setErrorHandler(errors);\n parser.parse(\"memory.xml\");\n } catch (Exception e) {\n System.out.print(\"Problem parsing the file.\");\n }\n }\n}\n"
},
{
"answer_id": 16054,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 9,
"selected": true,
"text": "import javax.xml.XMLConstants;\nimport javax.xml.transform.Source;\nimport javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.*;\nimport java.net.URL;\nimport org.xml.sax.SAXException;\n//import java.io.File; // if you use File\nimport java.io.IOException;\n...\nURL schemaFile = new URL(\"http://host:port/filename.xsd\");\n// webapp example xsd: \n// URL schemaFile = new URL(\"http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd\");\n// local file example:\n// File schemaFile = new File(\"/location/to/localfile.xsd\"); // etc.\nSource xmlFile = new StreamSource(new File(\"web.xml\"));\nSchemaFactory schemaFactory = SchemaFactory\n .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\ntry {\n Schema schema = schemaFactory.newSchema(schemaFile);\n Validator validator = schema.newValidator();\n validator.validate(xmlFile);\n System.out.println(xmlFile.getSystemId() + \" is valid\");\n} catch (SAXException e) {\n System.out.println(xmlFile.getSystemId() + \" is NOT valid reason:\" + e);\n} catch (IOException e) {}\n http://www.w3.org/2001/XMLSchema http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
},
{
"answer_id": 6690151,
"author": "chickeninabiscuit",
"author_id": 3966,
"author_profile": "https://Stackoverflow.com/users/3966",
"pm_score": 4,
"selected": false,
"text": "<schemavalidate> \n <fileset dir=\"${configdir}\" includes=\"**/*.xml\" />\n</schemavalidate>\n"
},
{
"answer_id": 9826988,
"author": "juwens",
"author_id": 534812,
"author_profile": "https://Stackoverflow.com/users/534812",
"pm_score": 2,
"selected": false,
"text": "SAXCount -f -s -n my.xml\n"
},
{
"answer_id": 16518985,
"author": "Paulo Fidalgo",
"author_id": 1006863,
"author_profile": "https://Stackoverflow.com/users/1006863",
"pm_score": 3,
"selected": false,
"text": "// create a SchemaFactory capable of understanding WXS schemas\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\n// load a WXS schema, represented by a Schema instance\nSource schemaFile = new StreamSource(new File(\"mySchema.xsd\"));\nSchema schema = factory.newSchema(schemaFile);\n\n// create a Validator instance, which can be used to validate an instance document\nValidator validator = schema.newValidator();\n\n// validate the DOM tree\ntry {\n validator.validate(new StreamSource(new File(\"instance.xml\"));\n} catch (SAXException e) {\n // instance document is invalid!\n}\n"
},
{
"answer_id": 41225329,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 4,
"selected": false,
"text": "xsi:schemaLocation xsi:noNamespaceSchemaLocation <document xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNamespaceSchemaLocation=\"http://www.example.com/document.xsd\">\n ...\n <document xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://www.example.com/my_namespace http://www.example.com/document.xsd\">\n ...\n SchemaFactory factory = SchemaFactory.newInstance(\"http://www.w3.org/2001/XMLSchema\");\nSchema schema = factory.newSchema();\n xmlsns:xsi public static void verifyValidatesInternalXsd(String filename) throws Exception {\n InputStream xmlStream = new new FileInputStream(filename);\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n factory.setValidating(true);\n factory.setNamespaceAware(true);\n factory.setAttribute(\"http://java.sun.com/xml/jaxp/properties/schemaLanguage\",\n \"http://www.w3.org/2001/XMLSchema\");\n DocumentBuilder builder = factory.newDocumentBuilder();\n builder.setErrorHandler(new RaiseOnErrorHandler());\n builder.parse(new InputSource(xmlStream));\n xmlStream.close();\n }\n\n public static class RaiseOnErrorHandler implements ErrorHandler {\n public void warning(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n public void error(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n public void fatalError(SAXParseException e) throws SAXException {\n throw new RuntimeException(e);\n }\n }\n Source xmlFile = new StreamSource(xmlFileLocation);\nSchemaFactory schemaFactory = SchemaFactory\n .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = schemaFactory.newSchema();\nValidator validator = schema.newValidator();\nvalidator.setResourceResolver(new LSResourceResolver() {\n @Override\n public LSInput resolveResource(String type, String namespaceURI,\n String publicId, String systemId, String baseURI) {\n InputSource is = new InputSource(\n getClass().getResourceAsStream(\n \"some_local_file_in_the_jar.xsd\"));\n // or lookup by URI, etc...\n return new Input(is); // for class Input see \n // https://stackoverflow.com/a/2342859/32453\n }\n});\nvalidator.validate(xmlFile);\n saxReader.setEntityResolver(your_resolver_here);"
},
{
"answer_id": 47514401,
"author": "razvanone",
"author_id": 2148681,
"author_profile": "https://Stackoverflow.com/users/2148681",
"pm_score": 2,
"selected": false,
"text": " @Test\npublic void testCheckXmlIsValidAgainstSchema() {\n logger.info(\"Validating an XML file against the latest schema...\");\n\n MyValidationEventCollector vec = new MyValidationEventCollector();\n\n validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);\n\n assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));\n}\n\nprivate void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {\n try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {\n final JAXBContext jContext = JAXBContext.newInstance(rootClass);\n // Unmarshal the data from InputStream\n final Unmarshaller unmarshaller = jContext.createUnmarshaller();\n\n final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);\n unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));\n\n unmarshaller.setEventHandler(vec);\n\n unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate\n\n for (String validationError : vec.getValidationErrors()) {\n logger.trace(validationError);\n }\n } catch (final Exception e) {\n logger.error(\"The validation of the XML file \" + xmlFileName + \" failed: \", e);\n }\n}\n\nclass MyValidationEventCollector implements ValidationEventHandler {\n private final List<String> validationErrors;\n\n public MyValidationEventCollector() {\n validationErrors = new ArrayList<>();\n }\n\n public List<String> getValidationErrors() {\n return Collections.unmodifiableList(validationErrors);\n }\n\n @Override\n public boolean handleEvent(final ValidationEvent event) {\n String pattern = \"line {0}, column {1}, error message {2}\";\n String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),\n event.getMessage());\n if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {\n validationErrors.add(errorMessage);\n }\n return true; // you collect the validation errors in a List and handle them later\n }\n}\n"
},
{
"answer_id": 52645727,
"author": "jschnasse",
"author_id": 1485527,
"author_profile": "https://Stackoverflow.com/users/1485527",
"pm_score": 0,
"selected": false,
"text": "Source xmlFile = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(\"your.xml\"));\nSchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\nSchema schema = factory.newSchema(Thread.currentThread().getContextClassLoader().getResource(\"your.xsd\"));\nValidator validator = schema.newValidator();\nvalidator.validate(xmlFile);\n"
},
{
"answer_id": 58040690,
"author": "Loris Securo",
"author_id": 6245535,
"author_profile": "https://Stackoverflow.com/users/6245535",
"pm_score": 1,
"selected": false,
"text": "// create the XSD schema from your schema file\nXMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory.newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);\nXMLValidationSchema validationSchema = schemaFactory.createSchema(schemaInputStream);\n\n// create the XML reader for your XML file\nWstxInputFactory inputFactory = new WstxInputFactory();\nXMLStreamReader2 xmlReader = (XMLStreamReader2) inputFactory.createXMLStreamReader(xmlInputStream);\n\ntry {\n // configure the reader to validate against the schema\n xmlReader.validateAgainst(validationSchema);\n\n // parse the XML\n while (xmlReader.hasNext()) {\n xmlReader.next();\n }\n\n // no exceptions, the XML is valid\n\n} catch (XMLStreamException e) {\n\n // exceptions, the XML is not valid\n\n} finally {\n xmlReader.close();\n}\n XMLInputFactory XMLValidationSchema"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1650/"
] |
15,734 |
<p>I know that there is no official API for Google Analytics but is there a way to access Google Analytics Reports with C#?</p>
|
[
{
"answer_id": 23441943,
"author": "Valentin V",
"author_id": 430254,
"author_profile": "https://Stackoverflow.com/users/430254",
"pm_score": 0,
"selected": false,
"text": "async/await dynamic"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890/"
] |
15,744 |
<p>I'm wondering about instances when it makes sent to use #define and #if statements. I've known about it for a while, but never incorporated it into my way of coding. How exactly does this affect the compilation?</p>
<blockquote>
<p>Is #define the only thing that determines if the code is included when compiled? If I have #define DEBUGme as a custom symbol, the only way to exclude it from compile is to remove this #define statement?</p>
</blockquote>
|
[
{
"answer_id": 15758,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 5,
"selected": true,
"text": "#define #define #if static void Main(string[] args)\n {\n#if DEBUG\n //this only compiles if in DEBUG\n Console.WriteLine(\"DEBUG\")\n#endif \n#if !DEBUG\n //this only compiles if not in DEBUG\n Console.WriteLine(\"RELEASE\")\n#endif\n //This always compiles\n Console.ReadLine()\n }\n"
},
{
"answer_id": 15761,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": false,
"text": "#define USEFOREACH\n\n#if USEFOREACH\n foreach(var item in items)\n { \n#else\n for(int i=0; i < items.Length; ++i)\n { var item = items[i]; //take item\n#endif\n\n doSomethingWithItem(item);\n }\n"
},
{
"answer_id": 15778,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 2,
"selected": false,
"text": "#if defined(DEBUG)\n#undef DEBUG\n#endif\n"
},
{
"answer_id": 16016,
"author": "Ali Parr",
"author_id": 1169,
"author_profile": "https://Stackoverflow.com/users/1169",
"pm_score": 1,
"selected": false,
"text": "#define PLAYSOUNDS\n #ifdef PLAYSOUNDS\n// Do lots of funk to play a sound\nreturn true;\n#else\nreturn true;\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] |
15,774 |
<p>I run an ASP.NET website solution with a few other projects in it. I've known that MSBuild projects are capable of this, but is it the best way? Are they easy to create? Is nAnt, CruiseControl.NET or any other solution better?</p>
<p>When I build the site (using <a href="http://msdn.microsoft.com/en-us/asp.net/aa336619.aspx" rel="nofollow noreferrer">Web Deployment Projects</a>), can I automate part of the build so that it does not copy certain folders from the project into the Release folder? For instance, I have folders with local search indexes, images and other content part of the folder, but I never need or upload those when deploying the project. </p>
<p>I'm also looking toward this type of solution to automatically increment build and version numbers.</p>
|
[
{
"answer_id": 32861,
"author": "icelava",
"author_id": 2663,
"author_profile": "https://Stackoverflow.com/users/2663",
"pm_score": 2,
"selected": false,
"text": "<!-- To modify your build process, add your task inside one of the targets below and uncomment it. \nOther similar extension points exist, see Microsoft.WebDeployment.targets.\n<Target Name=\"BeforeBuild\">\n</Target>\n<Target Name=\"BeforeMerge\">\n</Target>\n<Target Name=\"AfterMerge\">\n</Target>\n<Target Name=\"AfterBuild\">\n</Target>\n-->\n"
},
{
"answer_id": 157767,
"author": "Chris",
"author_id": 40352,
"author_profile": "https://Stackoverflow.com/users/40352",
"pm_score": 4,
"selected": true,
"text": " <Target Name=\"AfterBuild\">\n <!-- ============================ Script Compression============================ -->\n <MakeDir Directories=\"$(OutputPath)\\compressed\" />\n <Exec Command=\"java -jar c:\\yuicompressor-2.2.5\\build\\yuicompressor-2.2.5.jar --charset UTF-8 styles.css -o compressed/styles.css\" WorkingDirectory=\"$(OutputPath)\" />\n <Exec Command=\"move /Y .\\compressed\\* .\\\" WorkingDirectory=\"$(OutputPath)\" />\n <RemoveDir Directories=\"$(OutputPath)\\sql\" />\n <Exec Command=\"c:\\7zip-4.4.2\\7za.exe a $(ZipName).zip $(OutputPath)\\*\" />\n </Target>\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1888/"
] |
15,798 |
<p>I need to validate an XML string (and not a file)
against a DTD description file. </p>
<p>How can that be done in <code>python</code>?</p>
|
[
{
"answer_id": 15931,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 6,
"selected": true,
"text": "from StringIO import StringIO\n\nfrom lxml import etree\n\ndtd = etree.DTD(StringIO(\"\"\"<!ELEMENT foo EMPTY>\"\"\"))\nroot = etree.XML(\"<foo/>\")\nprint(dtd.validate(root))\n# True\n\nroot = etree.XML(\"<foo>bar</foo>\")\nprint(dtd.validate(root))\n# False\nprint(dtd.error_log.filter_from_errors())\n# <string>:1:0:ERROR:VALID:DTD_NOT_EMPTY: Element foo was declared EMPTY this one has content\n"
},
{
"answer_id": 270538,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/python -u\nimport libxml2\nimport sys\n\n# Memory debug specific\nlibxml2.debugMemory(1)\n\ndtd=\"\"\"<!ELEMENT foo EMPTY>\"\"\"\ninstance=\"\"\"<?xml version=\"1.0\"?>\n<foo></foo>\"\"\"\n\ndtd = libxml2.parseDTD(None, 'test.dtd')\nctxt = libxml2.newValidCtxt()\ndoc = libxml2.parseDoc(instance)\nret = doc.validateDtd(ctxt, dtd)\nif ret != 1:\n print \"error doing DTD validation\"\n sys.exit(1)\n\ndoc.freeDoc()\ndtd.freeDtd()\ndel dtd\ndel ctxt\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446497/"
] |
15,816 |
<p>I use VNC to connect to a Linux workstation at work. At work I have a 20" monitor that runs at 1600x1200, while at home I use my laptop with its resolution of 1440x900.
If I set the vncserver to run at 1440x900 I miss out on a lot of space on my monitor, whereas if I set it to run at 1600x1200 it doesn't fit on the laptop's screen, and I have to scroll it all the time.</p>
<p>Is there any good way to resize a VNC session on the fly?</p>
<p>My VNC server is RealVNC E4.x (I don't remember the exact version) running on SuSE64.</p>
|
[
{
"answer_id": 15926,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 5,
"selected": false,
"text": "$vncserver :0 -geometry 1600x1200\n$vncserver :1 -geometry 1440x900\n"
},
{
"answer_id": 1083668,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 8,
"selected": true,
"text": "vncserver -geometry 1600x1200 -randr 1600x1200,1440x900,1024x768\n xrandr -s 1600x1200\nxrandr -s 1440x900\nxrandr -s 1024x768\n"
},
{
"answer_id": 3839759,
"author": "Tijs",
"author_id": 463917,
"author_profile": "https://Stackoverflow.com/users/463917",
"pm_score": 6,
"selected": false,
"text": "vnc4server -geometry 1280x1024 -geometry 800x600\n xrandr\n xrandr -s 800x600\n"
},
{
"answer_id": 6560690,
"author": "nhed",
"author_id": 652904,
"author_profile": "https://Stackoverflow.com/users/652904",
"pm_score": 3,
"selected": false,
"text": "function vncNextRes()\n{\n xrandr -s $(($(xrandr | grep '^*'|sed 's@^\\*\\([0-9]*\\).*$@\\1@')+1)) > /dev/null 2>&1 || \\\n xrandr -s 0\n}\n function vncNextRes()\n{\n xrandr -s $(($(xrandr 2>/dev/null | grep -n '\\* *$'| sed 's@:.*@@')-2)) || \\\n xrandr -s 0\n}\n"
},
{
"answer_id": 8388065,
"author": "Peter",
"author_id": 391313,
"author_profile": "https://Stackoverflow.com/users/391313",
"pm_score": 5,
"selected": false,
"text": "bash> xrandr\n SZ: Pixels Physical Refresh\n 0 1920 x 1200 ( 271mm x 203mm ) 60\n 1 1920 x 1080 ( 271mm x 203mm ) 60\n 2 1600 x 1200 ( 271mm x 203mm ) 60\n 3 1680 x 1050 ( 271mm x 203mm ) 60\n 4 1400 x 1050 ( 271mm x 203mm ) 60\n 5 1360 x 768 ( 271mm x 203mm ) 60\n 6 1280 x 1024 ( 271mm x 203mm ) 60\n 7 1280 x 960 ( 271mm x 203mm ) 60\n 8 1280 x 800 ( 271mm x 203mm ) 60\n 9 1280 x 720 ( 271mm x 203mm ) 60\n*10 1024 x 768 ( 271mm x 203mm ) *60\n 11 800 x 600 ( 271mm x 203mm ) 60\n 12 640 x 480 ( 271mm x 203mm ) 60\nCurrent rotation - normal\nCurrent reflection - none\nRotations possible - normal\nReflections possible - none\n bash> xrandr -s 5\n"
},
{
"answer_id": 11648533,
"author": "inukaze",
"author_id": 983309,
"author_profile": "https://Stackoverflow.com/users/983309",
"pm_score": 0,
"selected": false,
"text": "#!/bin/sh\n\necho `xrandr --current | grep current | awk '{print $8}'` >> RES1\necho `xrandr --current | grep current | awk '{print $10}'` >> RES2\ncat RES2 | sed -i 's/,//g' RES2\n\nP1RES=$(cat RES1)\nP2RES=$(cat RES2)\nrm RES1 RES2\necho \"$P1RES\"'x'\"$P2RES\" >> RES\nRES=$(cat RES)\n\n# Play The Game\n\n# Finish The Game with Lower Resolution\n\nxrandr -s $RES\n"
},
{
"answer_id": 23974330,
"author": "Hammad Khan",
"author_id": 777982,
"author_profile": "https://Stackoverflow.com/users/777982",
"pm_score": 5,
"selected": false,
"text": "System > Preference > Display"
},
{
"answer_id": 28777978,
"author": "Kashyap",
"author_id": 496289,
"author_profile": "https://Stackoverflow.com/users/496289",
"pm_score": 2,
"selected": false,
"text": "'Resize remote session to local window' zooming 'xrandr: Failed to get size of gamma for output default' yum install gnome-* tigervnc-server OS: RHEL 6.6 (Santiago)\nVNC Server:\nName : tigervnc-server\nArch : x86_64\nVersion : 1.1.0\nRelease : 16.el6\n\n# May be this is relevant..\n$ xrandr --version\nxrandr program version 1.4.0\nServer reports RandR version 1.4\n$ \n\n# I start the server using vncserver -geometry 800x600\n# Xvnc is started by vncserver with following args:\n/usr/bin/Xvnc :1 -desktop plabb13.sgdcelab.sabre.com:1 (sg219898) -auth /login/sg219898/.Xauthority \n-geometry 800x600 -rfbwait 30000 -rfbauth /login/sg219898/.vnc/passwd -rfbport 5901 -fp catalogue:/e\ntc/X11/fontpath.d -pn\n\n\n# I'm running GNOME (installed using sudo yum install gnome-*)\nName : gnome-desktop\nArch : x86_64\nVersion : 2.28.2\nRelease : 11.el6\n\nName : gnome-session\nArch : x86_64\nVersion : 2.28.0\nRelease : 22.el6\n\nConnect using Tiger 32-bit VNC Client v1.3.1 on Windows 7.\n"
},
{
"answer_id": 38630417,
"author": "omiday",
"author_id": 6648502,
"author_profile": "https://Stackoverflow.com/users/6648502",
"pm_score": 5,
"selected": false,
"text": "xrandr man xrandr $ vncserver -geometry 1600x900 :1\n host:5901\n $ xrandr\nScreen 0: minimum 32 x 32, current 1600 x 900, maximum 32768 x 32768\nVNC-0 connected 1600x900+0+0 0mm x 0mm\n 1600x900 60.00 +\n 1920x1200 60.00 \n 1920x1080 60.00 \n 1600x1200 60.00 \n 1680x1050 60.00 \n 1400x1050 60.00 \n 1360x768 60.00 \n 1280x1024 60.00 \n 1280x960 60.00 \n 1280x800 60.00 \n 1280x720 60.00 \n 1024x768 60.00 \n 800x600 60.00 \n 640x480 60.00 \n $ cvt 2560 1600\n# 2560x1600 59.99 Hz (CVT 4.10MA) hsync: 99.46 kHz; pclk: 348.50 MHz\nModeline \"2560x1600_60.00\" 348.50 2560 2760 3032 3504 1600 1603 1609 1658 -hsync +vsync\n $ gtf 2560 1600 60\n# 2560x1600 @ 60.00 Hz (GTF) hsync: 99.36 kHz; pclk: 348.16 MHz\nModeline \"2560x1600_60.00\" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync\n $ xrandr --newmode \"2560x1600_60.00\" 348.16 2560 2752 3032 3504 1600 1601 1604 1656 -HSync +Vsync\n xrandr VNC-0 connected 1600x900+0+0 0mm x 0mm\n $ xrandr --addmode VNC-0 \"2560x1600_60.00\"\n $ xrandr -s \"2560x1600_60.00\"\n"
},
{
"answer_id": 39777101,
"author": "Nicholas Sushkin",
"author_id": 789544,
"author_profile": "https://Stackoverflow.com/users/789544",
"pm_score": 2,
"selected": false,
"text": "function vncsize {\n local x=$1 y=$2\n local mode\n if mode=$(cvt \"$x\" \"$y\" 2>/dev/null)\n then\n if [[ $mode =~ \"Modeline (.*)$\" ]]\n then\n local newMode=${BASH_REMATCH[1]//\\\"/}\n local modeName=${newMode%% *}\n local newSize=( ${modeName//[\\\"x_]/ } )\n local screen=$(xrandr -q|grep connected|cut -d' ' -f1)\n xrandr --newmode $newMode\n xrandr --addmode \"$screen\" \"$modeName\"\n xrandr --size \"${newSize[0]}x${newSize[1]}\" &&\n return 0\n else\n echo \"Unable to parse modeline for ($x $y) from $mode\"\n return 2\n fi\n else\n echo \"\\`$x $y' is not a valid X Y pair\"\n return 1\n fi\n}\n"
},
{
"answer_id": 47251869,
"author": "Will Berger",
"author_id": 8928866,
"author_profile": "https://Stackoverflow.com/users/8928866",
"pm_score": 4,
"selected": false,
"text": "ssh vncserver -geometry 1200x1600\n :1 ipaddress:1"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
15,828 |
<p>Is there a free or open source library to read Excel files (.xls) directly from a C# program? </p>
<p>It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.</p>
|
[
{
"answer_id": 15839,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 6,
"selected": false,
"text": "select * from [Sheet1$]"
},
{
"answer_id": 15970,
"author": "hitec",
"author_id": 120,
"author_profile": "https://Stackoverflow.com/users/120",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Data;\nusing System.Data.OleDb;\n\nnamespace ExportExcelToAccess\n{\n /// <summary>\n /// Summary description for ExcelHelper.\n /// </summary>\n public sealed class ExcelHelper\n {\n private const string CONNECTION_STRING = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=<FILENAME>;Extended Properties=\\\"Excel 8.0;HDR=Yes;\\\";\";\n\n public static DataTable GetDataTableFromExcelFile(string fullFileName, ref string sheetName)\n {\n OleDbConnection objConnection = new OleDbConnection();\n objConnection = new OleDbConnection(CONNECTION_STRING.Replace(\"<FILENAME>\", fullFileName));\n DataSet dsImport = new DataSet();\n\n try\n {\n objConnection.Open();\n\n DataTable dtSchema = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);\n\n if( (null == dtSchema) || ( dtSchema.Rows.Count <= 0 ) )\n {\n //raise exception if needed\n }\n\n if( (null != sheetName) && (0 != sheetName.Length))\n {\n if( !CheckIfSheetNameExists(sheetName, dtSchema) )\n {\n //raise exception if needed\n }\n }\n else\n {\n //Reading the first sheet name from the Excel file.\n sheetName = dtSchema.Rows[0][\"TABLE_NAME\"].ToString();\n }\n\n new OleDbDataAdapter(\"SELECT * FROM [\" + sheetName + \"]\", objConnection ).Fill(dsImport);\n }\n catch (Exception)\n {\n //raise exception if needed\n }\n finally\n {\n // Clean up.\n if(objConnection != null)\n {\n objConnection.Close();\n objConnection.Dispose();\n }\n }\n\n\n return dsImport.Tables[0];\n #region Commented code for importing data from CSV file.\n // string strConnectionString = \"Provider=Microsoft.Jet.OLEDB.4.0;\" +\"Data Source=\" + System.IO.Path.GetDirectoryName(fullFileName) +\";\" +\"Extended Properties=\\\"Text;HDR=YES;FMT=Delimited\\\"\";\n //\n // System.Data.OleDb.OleDbConnection conText = new System.Data.OleDb.OleDbConnection(strConnectionString);\n // new System.Data.OleDb.OleDbDataAdapter(\"SELECT * FROM \" + System.IO.Path.GetFileName(fullFileName).Replace(\".\", \"#\"), conText).Fill(dsImport);\n // return dsImport.Tables[0];\n\n #endregion\n }\n\n /// <summary>\n /// This method checks if the user entered sheetName exists in the Schema Table\n /// </summary>\n /// <param name=\"sheetName\">Sheet name to be verified</param>\n /// <param name=\"dtSchema\">schema table </param>\n private static bool CheckIfSheetNameExists(string sheetName, DataTable dtSchema)\n {\n foreach(DataRow dataRow in dtSchema.Rows)\n {\n if( sheetName == dataRow[\"TABLE_NAME\"].ToString() )\n {\n return true;\n } \n }\n return false;\n }\n }\n}\n"
},
{
"answer_id": 16051,
"author": "Robin Robinson",
"author_id": 1629,
"author_profile": "https://Stackoverflow.com/users/1629",
"pm_score": 8,
"selected": true,
"text": "var fileName = string.Format(\"{0}\\\\fileNameHere\", Directory.GetCurrentDirectory());\nvar connectionString = string.Format(\"Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;\", fileName);\n\nvar adapter = new OleDbDataAdapter(\"SELECT * FROM [workSheetNameHere$]\", connectionString);\nvar ds = new DataSet();\n\nadapter.Fill(ds, \"anyNameHere\");\n\nDataTable data = ds.Tables[\"anyNameHere\"];\n var data = ds.Tables[\"anyNameHere\"].AsEnumerable();\n var query = data.Where(x => x.Field<string>(\"phoneNumber\") != string.Empty).Select(x =>\n new MyContact\n {\n firstName= x.Field<string>(\"First Name\"),\n lastName = x.Field<string>(\"Last Name\"),\n phoneNumber =x.Field<string>(\"Phone Number\"),\n });\n"
},
{
"answer_id": 43534,
"author": "Dmitry Shechtman",
"author_id": 3583,
"author_profile": "https://Stackoverflow.com/users/3583",
"pm_score": 5,
"selected": false,
"text": "Dictionary<string, string> props = new Dictionary<string, string>();\nprops[\"Provider\"] = \"Microsoft.Jet.OLEDB.4.0\";\nprops[\"Data Source\"] = repFile;\nprops[\"Extended Properties\"] = \"Excel 8.0\";\n\nStringBuilder sb = new StringBuilder();\nforeach (KeyValuePair<string, string> prop in props)\n{\n sb.Append(prop.Key);\n sb.Append('=');\n sb.Append(prop.Value);\n sb.Append(';');\n}\nstring properties = sb.ToString();\n\nusing (OleDbConnection conn = new OleDbConnection(properties))\n{\n conn.Open();\n DataSet ds = new DataSet();\n string columns = String.Join(\",\", columnNames.ToArray());\n using (OleDbDataAdapter da = new OleDbDataAdapter(\n \"SELECT \" + columns + \" FROM [\" + worksheet + \"$]\", conn))\n {\n DataTable dt = new DataTable(tableName);\n da.Fill(dt);\n ds.Tables.Add(dt);\n }\n}\n"
},
{
"answer_id": 7425567,
"author": "Balena",
"author_id": 945938,
"author_profile": "https://Stackoverflow.com/users/945938",
"pm_score": 1,
"selected": false,
"text": "Take.io"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
] |
15,838 |
<p>Can the performance of this sequential search algorithm (taken from
<a href="http://books.google.co.uk/books?id=to6M9_dbjosC&dq=the+practice+of+programming&pg=PP1&ots=3YH6Ggq0_a&sig=F2-ajdO37xA4iRec2sCyQF55Jjc&hl=en&sa=X&oi=book_result&resnum=1&ct=result" rel="noreferrer">The Practice of Programming</a>) be improved using any of C's native utilities, e.g. if I set the i variable to be a register variable ?</p>
<pre><code>int lookup(char *word, char*array[])
{
int i
for (i = 0; array[i] != NULL; i++)
if (strcmp(word, array[i]) == 0)
return i;
return -1;
}
</code></pre>
|
[
{
"answer_id": 15876,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 1,
"selected": false,
"text": "for (i = 0; i < n; ++i)\n foo(a[i]);\n char **p = a;\nfor (i = 0; i < n; ++i)\n foo(*p);\n ++p;\n for (p = a; *p != NULL; ++p)\n foo(*p)\n"
},
{
"answer_id": 15915,
"author": "popopome",
"author_id": 1556,
"author_profile": "https://Stackoverflow.com/users/1556",
"pm_score": 2,
"selected": false,
"text": "int lookup(char *word, char*array[], int array_len)\n{\n int i = 0;\n array[array_len] = word;\n for (;; ++i)\n if (strcmp(word, array[i]) == 0) \n break;\n array[array_len] = NULL;\n return (i != array_len) ? i : -1;\n}\n"
},
{
"answer_id": 16094,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "wrd_end = wrd_ptr + wrd_len;\narr_end = arr_ptr - wrd_len;\nwhile (arr_ptr < arr_end)\n{\n wrd_beg = wrd_ptr; arr_beg = arr_ptr;\n while (wrd_ptr == arr_ptr)\n {\n wrd_ptr++; arr_ptr++;\n if (wrd_ptr == wrd_en)\n return wrd_beg;\n }\n wrd_ptr++;\n}\n"
},
{
"answer_id": 252622,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "char s[] = \"\\x05Hello\";\n for(i=0; i<len; ++i) {\n s_len = strings[i][0];\n if(\n s_len == match_len\n && strings[i][s_len] == match[s_len-1]\n && 0 == memcmp(strings[i]+1, match, s_len-1)\n ) {\n return 1;\n }\n}\n"
},
{
"answer_id": 20116661,
"author": "alchak",
"author_id": 3016771,
"author_profile": "https://Stackoverflow.com/users/3016771",
"pm_score": -1,
"selected": false,
"text": "/* there is no more quick */\nint lookup(char *word, char*array[])\n{\n int i;\n for(i=0; *(array++) != NULL;i++)\n if (strcmp(word, *array) == 0)\n return i;\n return -1;\n}\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
15,851 |
<p>After I was convinced that labeled breaks/continues are a total "nono" over <a href="https://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-brakecontinue#15501">here</a>, I need help to remove the label out of my code.</p>
<p>I have a square matrix and a vector that has the same length. The vector has already some values in it an depending on the values in the matrix the vector is changed in the loop.</p>
<p>I hope, the code-fragment is basically understandable… </p>
<pre><code>vectorLoop:
for( int idx = 0; idx < vectorLength; idx++) {
if( conditionAtVectorPosition( v, idx ) ) continue vectorLoop;
matrixLoop:
for( rowIdx = 0; rowIdx < n; rowIdx++ ) {
if( anotherConditionAtVector( v, rowIdx ) ) continue matrixLoop;
if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) continue vectorLoop;
}
setValueInVector( v, idx );
}
</code></pre>
<p>Please convince me, that there is a more readable/better version without the labels.</p>
|
[
{
"answer_id": 15855,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "for( int idx = 0; idx < vectorLength; idx++) {\n if( conditionAtVectorPosition( v, idx ) ) continue;\n\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) break;\n }\n if( !conditionAtMatrixRowCol( m, rowIdx, idx ) )\n setValueInVector( v, idx );\n}\n"
},
{
"answer_id": 15870,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "for( int idx = 0; idx < vectorLength; idx++) {\n if( conditionAtVectorPosition( v, idx ) \n || !CheckedEntireMatrix(v)) continue;\n\n setValueInVector( v, idx );\n}\n\nprivate bool CheckedEntireMatrix(Vector v)\n{\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) return false;\n } \n return true;\n}\n"
},
{
"answer_id": 15901,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 0,
"selected": false,
"text": "for( int idx = 0; idx < vectorLength; idx++) {\n if (!conditionAtVectorPosition( v, idx ) \n && checkedRow(v, idx))\n setValueInVector( v, idx );\n}\n\nprivate boolean checkedRow(Vector v, int idx) {\n for( rowIdx = 0; rowIdx < n; rowIdx++ ) {\n if( anotherConditionAtVector( v, rowIdx ) ) continue;\n if( conditionAtMatrixRowCol( m, rowIdx, idx ) ) return false;\n } \n return true;\n}\n"
},
{
"answer_id": 15903,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 0,
"selected": false,
"text": "for( int idx = 0; idx < vectorLength; idx++) {\n if( !conditionAtVectorPosition( v, idx ) && CheckedEntireMatrix(v))\n setValueInVector( v, idx );\n}\n\ninline bool CheckedEntireMatrix(Vector v) {\n for(rowIdx = 0; rowIdx < n; rowIdx++)\n if ( !anotherConditionAtVector(v,rowIdx) && conditionAtMatrixRowCol(m,rowIdx,idx) ) \n return false;\n return true;\n}\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
15,880 |
<p>I need to read from Outlook .MSG file in .NET <em>without</em> using COM API for Outlook (cos it will not be installed on the machines that my app will run). Are there any free 3rd party libraries to do that? I want to extract From, To, CC and BCC fields. Sent/Receive date fields would be good if they are also stored in MSG files.</p>
|
[
{
"answer_id": 2365689,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 3,
"selected": false,
"text": "Public Sub ProcessMail()\n\n Dim Sess As RDOSession\n Dim myMsg As RDOMail\n Dim myString As String\n\n Set Sess = CreateObject(\"Redemption.RDOSession\")\n Set myMsg = Sess.GetMessageFromMsgFile(\"C:\\TestHarness\\kmail.msg\")\n\n myString = myMsg.Body\n myMsg.Body = Replace(myString, \"8750\", \"XXXX\")\n\n myMsg.Save\n\nEnd Sub\n"
},
{
"answer_id": 5582452,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 1,
"selected": false,
"text": "// Load message\nMailMessage message = new MailMessage();\nmessage.Load(@\"c:\\Temp\\t\\message.msg\");\n\n// show From, To and Sent date\nConsole.WriteLine(\"From: {0}\", message.From);\nConsole.WriteLine(\"To: {0}\", message.To);\nConsole.WriteLine(\"Sent: {0}\", message.Date.LocalTime);\n\n// find and try to parse the first 'Received' header\nMailDateTime receivedDate = null;\nstring received = message.Headers.GetRaw(\"Received\");\nif (received != null)\n{\n int lastSemicolon = received.LastIndexOf(';');\n if (lastSemicolon >= 0)\n {\n string rawDate = received.Substring(lastSemicolon + 1);\n MimeHeader header = new MimeHeader(\"Date\", rawDate);\n receivedDate = header.Value as MailDateTime;\n }\n}\n\n// display the received date if available\nif (receivedDate != null)\n Console.WriteLine(\"Received: {0}\", receivedDate.LocalTime);\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39/"
] |
15,899 |
<p>I have a <code>XmlDocument</code> in java, created with the <code>Weblogic XmlDocument</code> parser.</p>
<p>I want to replace the content of a tag in this <code>XMLDocument</code> with my own data, or insert the tag if it isn't there.</p>
<pre><code><customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
</code></pre>
<p>For example I want to insert a URL in the location tag:</p>
<pre><code><location>http://something</location>
</code></pre>
<p>but otherwise leave the XML as is.</p>
<p>Currently I use a <code>XMLCursor</code>:</p>
<pre><code> XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
</code></pre>
<p>I tried to find a "quick" <code>xquery</code> way to do this since the <code>XmlDocument</code> has an <code>execQuery</code> method, but didn't find it very easy. </p>
<p>Do anyone have a better way than this? It seems a bit elaborate.</p>
|
[
{
"answer_id": 15961,
"author": "alanl",
"author_id": 1464,
"author_profile": "https://Stackoverflow.com/users/1464",
"pm_score": 0,
"selected": false,
"text": "query fn:replace(string,pattern,replace)\n"
},
{
"answer_id": 15967,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 2,
"selected": false,
"text": "public class CustomData {\n public String tag1;\n public String tag2;\n public String location;\n public String tag3;\n}\n XStream xstream = new XStream();\n// if you need to output the main tag in lowercase, use the following line\nxstream.alias(\"customdata\", CustomData.class); \n CustomData d = (CustomData)xstream.fromXML(xml);\nd.location = \"http://stackoverflow.com\";\nxml = xstream.toXML(d);\n"
},
{
"answer_id": 16019,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 4,
"selected": true,
"text": "// get the list of customdata nodes\nNodeList customDataNodeSet = findNodes(document, \"//customdata\" );\n\nfor (int i=0 ; i < customDataNodeSet.getLength() ; i++) {\n Node customDataNode = customDataNodeSet.item( i );\n\n // get the location nodes (if any) within this one customdata node\n NodeList locationNodeSet = findNodes(customDataNode, \"location\" );\n\n if (locationNodeSet.getLength() > 0) {\n // replace\n locationNodeSet.item( 0 ).setTextContent( \"http://stackoverflow.com/\" );\n }\n else {\n // insert\n Element newLocationNode = document.createElement( \"location\" );\n newLocationNode.setTextContent(\"http://stackoverflow.com/\" );\n customDataNode.appendChild( newLocationNode );\n }\n}\n private NodeList findNodes( Object obj, String xPathString )\n throws XPathExpressionException {\n\n XPath xPath = XPathFactory.newInstance().newXPath();\n XPathExpression expression = xPath.compile( xPathString );\n return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );\n}\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86/"
] |
15,917 |
<p>I'm using NHibernate on a project and I need to do data auditing. I found <a href="http://www.codeproject.com/KB/cs/NHibernate_IInterceptor.aspx" rel="nofollow noreferrer">this article</a> on codeproject which discusses the IInterceptor interface.</p>
<p>What is your preferred way of auditing data? Do you use database triggers? Do you use something similar to what's dicussed in the article?</p>
|
[
{
"answer_id": 212932,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 2,
"selected": false,
"text": "public interface IRepository<EntityType> where EntityType:IAuditably\n{ \n public void Save(EntityType entity);\n}\n public class NHibernateRepository<EntityType>:IRepository<EntityType>\n{\n /*...*/\n public void Save ( EntityType entity )\n {\n session.SaveOrUpdate(entity);\n }\n}\n public class AuditingRepository<EntityType>:IRepository<EntityType>\n{\n /*...*/\n public void Save ( EntityType entity )\n {\n entity.LastUser = security.CurrentUser;\n entity.LastUpdate = DateTime.UtcNow;\n innerRepository.Save(entity)\n }\n}\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1122/"
] |
15,949 |
<p>I have a tomcat instance setup but the database connection I have configured in <code>context.xml</code> keeps dying after periods of inactivity.</p>
<p>When I check the logs I get the following error:</p>
<p>com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
The last packet successfully received from the server was68051 seconds
ago. The last packet sent successfully to the server was 68051 seconds
ago, which is longer than the server configured value of
'wait_timeout'. You should consider either expiring and/or testing
connection validity before use in your application, increasing the
server configured values for client timeouts, or using the Connector/J
connection property 'autoReconnect=true' to avoid this problem.</p>
<p>Here is the configuration in context.xml:</p>
<pre><code><Resource name="dataSourceName"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="username"
password="********"
removeAbandoned = "true"
logAbandoned = "true"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://127.0.0.1:3306/databasename?autoReconnect=true&amp;useEncoding=true&amp;characterEncoding=UTF-8" />
</code></pre>
<p>I am using <code>autoReconnect=true</code> like the error says to do, but the connection keeps dying. I have never seen this happen before.</p>
<p>I have also verified that all database connections are being closed properly.</p>
|
[
{
"answer_id": 16168,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 5,
"selected": true,
"text": "* Jakarta-Commons DBCP\n* Jakarta-Commons Collections\n* Jakarta-Commons Pool\n removeAbandonedTimeout=\"60\"\n testWhileIdle=true\ntimeBetweenEvictionRunsMillis=300000\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22/"
] |
15,954 |
<p>How can a <code>sdbm</code> hash function (such as <a href="http://www.cse.yorku.ca/~oz/hash.html" rel="nofollow noreferrer">this</a>) be implemented in C# ?</p>
|
[
{
"answer_id": 15971,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 2,
"selected": false,
"text": "uint sdbm( string str )\n{\n uint hash = 0;\n foreach( char ch in str )\n {\n hash = ch + (hash << 6) + (hash << 16) - hash;\n }\n return hash;\n}\n"
},
{
"answer_id": 15972,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "private static ulong SBDM(string str)\n{\n ulong hash = 0;\n\n foreach (char c in str)\n {\n hash = c + (hash << 6) + (hash << 16) - hash;\n }\n\n return hash;\n}\n String.GetHashCode()"
},
{
"answer_id": 18111,
"author": "Christo",
"author_id": 1658,
"author_profile": "https://Stackoverflow.com/users/1658",
"pm_score": 0,
"selected": false,
"text": "private uint sdbm(byte[] str)\n{\n uint hash = 0;\n\n foreach (char ch in str)\n hash = ch + (hash << 6) + (hash << 16) - hash;\n\n return hash;\n}\n BitConverter.GetBytes uint Hash = sdbm(BitConverter.GetBytes(myID));\n"
}
] |
2008/08/19
|
[
"https://Stackoverflow.com/questions/15954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1658/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.