qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
186,494
|
<p>I've seen second one in another's code and I suppose this length comparison have been done to increase code productivity. It was used in a parser for a script language with a specific dictionary: words are 4 to 24 letters long with the average of 7-8 lettets, alphabet includes 26 latin letters plus "@","$" and "_". </p>
<p>Length comparison were used to escape == operator working with STL strings, which obviously takes more time then simple integer comparison. But in the same time first letter distribution in the given dictionary is simply wider than a distribution of words size, so two first letters of comparing strings will be generally more often different, than the sizes of that strings. That makes length comparison unnecessary.</p>
<p>I've ran some tests and that is what I've found out: While testing two random strings comparison million times, second way is much faster, so length comparison seems to be helpful. But in a working project it works even slower in a debug mode and insufficiantly faster in a release mode.</p>
<p>So, my question is: why length comparison can fasten the comparison and why can it slow it down?</p>
<p>UPD: I don't like that second way either, but it had been done for a reason, I suppose, and I wonder, what is this reason.</p>
<p>UPD2: Seriously, the question is not how to do best. I'm not even using STL strings in this case anymore. There's no wonder that length comparison is unnecessary and wrong etc. The wonder is - it really tends to work slightly better in one certain test. How is this possible?</p>
|
[
{
"answer_id": 200831,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "Lhs[0] Rhs[0]"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25459/"
] |
186,496
|
<p>Lets assume my classes are loaded from a compressed .war file or loaded elsewhere,
how can I discover all the resources in a given package? Enumerating files will not really work, since this is a war file. Most likely this will involve using the current classloader?</p>
<p>Is there a library out there that does something like that? Googling revealed only some hacks with listing files.</p>
|
[
{
"answer_id": 3232402,
"author": "DerHeiligste",
"author_id": 168819,
"author_profile": "https://Stackoverflow.com/users/168819",
"pm_score": 3,
"selected": false,
"text": "PathMatchingResourcePatternResolver"
},
{
"answer_id": 12014366,
"author": "jcfolsom",
"author_id": 1098387,
"author_profile": "https://Stackoverflow.com/users/1098387",
"pm_score": 5,
"selected": false,
"text": "ClassLoader.getResources(\"\")"
},
{
"answer_id": 26188028,
"author": "Vlad Patryshev",
"author_id": 770110,
"author_profile": "https://Stackoverflow.com/users/770110",
"pm_score": 2,
"selected": false,
"text": "ls myResources/*.ext > myResources/list.txt"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16542/"
] |
186,502
|
<p>Is it possible to receive DllMain like notifications about thread attach/detach in stand-alone exe without using any extra dlls?</p>
<p><strong>Edit:</strong> This is just a theoretical question that has to do with some testing I'm doing. not a real life situation.</p>
|
[
{
"answer_id": 188123,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "WaitForDebugEvent() CreateProcess() DEBUG_ONLY_THIS_PROCESS WaitForDebugEvent()"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9611/"
] |
186,507
|
<p>I was looking for a pattern to model something I'm thinking of doing in a personal project and I was wondering if a modified version of the decorator patter would work.</p>
<p>Basicly I'm thinking of creating a game where the characters attributes are modified by what items they have equiped. The way that the decorator stacks it's modifications is perfect for this, however I've never seen a decorator that allows you to drop intermediate decorators, which is what would happen when items are unequiped.</p>
<p>Does anyone have experience using the decorator pattern in this way? Or am I barking up the wrong tree?</p>
<p><strong>Clarification</strong></p>
<p>To explain "Intermediate decorators" if for example my base class is coffe which is decorated with milk which is decorated with sugar (using the example in Head first design patterns) milk would be an intermediate decorator as it decorates the base coffee, and is decorated by the sugar.</p>
<p><strong>Yet More Clarification :)</strong></p>
<p>The idea is that items change stats, I'd agree that I am shoehorning the decorator into this. I'll look into the state bag. essentially I want a single point of call for the statistics and for them to go up/down when items are equiped/unequiped.</p>
<p>I could just apply the modifiers to the characters stats on equiping and roll them back when unequiping. Or whenever a stat is asked for iterate through all the items and calculate the stat.</p>
<p>I'm just looking for feedback here, I'm aware that I might be using a chainsaw where scissors would be more appropriate...</p>
|
[
{
"answer_id": 186861,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 2,
"selected": false,
"text": "Character.unequip(LIGHTSABER);\n"
},
{
"answer_id": 194033,
"author": "Sandman",
"author_id": 19911,
"author_profile": "https://Stackoverflow.com/users/19911",
"pm_score": 1,
"selected": false,
"text": "Public class Character {\n\n //various character related variables and methods here...\n\n Command[] equipCommands;\n Command[] unequipCommands;\n\n public Character(Command[] p_equipCommands, Command[] p_unequipCommands) {\n\n equipCommands = p_equipCommands;\n unequipCommands = p_unEquipCommands;\n }\n\n public void itemEquiped(int itemID) {\n\n equipCommands[itemID].execute(this);\n }\n\n public void itemUnequiped(int itemID) {\n\n unequipCommands[itemID].execute(this);\n }\n}\n public class SwordOfDragonSlayingEquipCommand implements ItemCommand{\n\n public void execute(Character p_character) {\n\n //There's probably a better way of doing this, but of the top of my head...\n p_character.addItemToInventory(Weapons.getIteM(Weapons.SWORD_OF_DRAGON_SLAYING));\n\n //other methods that raise stats, give bonuses etc. here...\n }\n}\n\npublic class SwordOfDragonSlayingUnequipCommand implements ItemCommand{\n\n public void execute(Character p_character) {\n\n //There's probably a better way of doing this, but of the top of my head...\n p_character.removeItemFromInventory(Weapons.getIteM(Weapons.SWORD_OF_DRAGON_SLAYING));\n\n //other methods that lower stats, remove bonuses etc. here...\n }\n}\n"
},
{
"answer_id": 194462,
"author": "Jeff",
"author_id": 16639,
"author_profile": "https://Stackoverflow.com/users/16639",
"pm_score": 1,
"selected": false,
"text": "character.GetStrength() {\n foreach(item in character.items)\n strFromItems += item.GetStrengthBonusForItems();\n foreach(buff in character.buffs)\n strFromBuffs += buff.GetStrengthBonusForBuffs();\n ...\n\n return character.baseStrength + strFromItems + ...;\n}\n character.GetStr() { ... // same as above, strength is rarely queried }\n character.GetMaxHP() { \n if (character._maxHPDirty) RecalcMaxHP();\n return character.cachedMaxHP;\n }\n // repeat for damage, and your probably done, but profile to figure out\n // exactly which stats are important to your game\n // changes in diablo happen very infrequently compared to queries, \n // so up propegate to optimize queries. Moreover, 10 people edit \n // the stat calculation formulas so having the up propegation match \n // the caculation w/o writing code is pretty important for robustness.\n\n character.OnEquip(item) {\n statList.merge(item.statlist);\n }\n\n character.GetStrength() {\n statList.getStat(STRENGTH);\n }\n\n statlist.getStat(id) {\n if (IS_FAST_STAT(id)) return cachedFastStats[id];\n return cachedStats.lookup(id);\n }\n\n statlist.merge(statlist) {\n // left for an exercise for the reader\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
186,520
|
<p>From one apache server file_get_contents returns the contents of a url straight away. On another apache server file_get contents won't return the contents of the same url until the keep-alive limit of the server hosting that url has been expired. The 2 php servers are retrieving the same url but through different network routes. What could be causing one php installation to wait for the remote keep-alive limit before returning? </p>
|
[
{
"answer_id": 186552,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 3,
"selected": true,
"text": "fopen file_get_contents fopen"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9831/"
] |
186,523
|
<p>Which other restrictions are there on names (beside the obvious uniqueness within a scope)?</p>
<p>Where are those defined?</p>
|
[
{
"answer_id": 186540,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "int @int = 5; __ __foo"
},
{
"answer_id": 8794978,
"author": "qwertium",
"author_id": 1139177,
"author_profile": "https://Stackoverflow.com/users/1139177",
"pm_score": 6,
"selected": false,
"text": "class Program\n{\n private static void Main(string[] args)\n {\n int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 5;\n }\n}\n error CS0645: Identifier too long"
},
{
"answer_id": 42806560,
"author": "Yawar Murtaza",
"author_id": 1039644,
"author_profile": "https://Stackoverflow.com/users/1039644",
"pm_score": 1,
"selected": false,
"text": " public class AaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaAAAAAZZZ\n{ \n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
186,527
|
<p>I have some problems on a site with the concurrent access to a list. This list keeps a cart of items, and multiple deletes are crashing the site.
<strong>Which is the best method to sync them?</strong>
Is a lock enough?
The lock option seems to be ugly because the code is spread all over the place and is pretty messy.</p>
<p>Update:
This is a list implemented like this:
public class MyList : List< SomeCustomType> { }</p>
<p>This is a legacy site so not so many modifications are allowed to it.
How should I refactor this in order to safely lock when iterating over it ?</p>
<p>any idea!</p>
|
[
{
"answer_id": 186885,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 2,
"selected": false,
"text": "lock (myList.SyncRoot) \n{\n // Access the collection.\n}\n"
},
{
"answer_id": 9375328,
"author": "The Dag",
"author_id": 513549,
"author_profile": "https://Stackoverflow.com/users/513549",
"pm_score": 0,
"selected": false,
"text": "class extends List<T> List<T> \npublic class MyCollection\n{\n object syncRoot = new object();\n List list = new List(); \n\npublic void Add(T item) { lock (syncRoot) list.Add(item); }\n\npublic int Count\n{\n get { lock (syncRoot) return list.Count; }\n}\n\npublic IteratorWrapper GetIteratorWrapper()\n{\n return new IteratorWrapper(this);\n}\n\n\npublic class IteratorWrapper : IDisposable, IEnumerable<T>\n{\n bool disposed;\n MyCollection<T> c;\n public IteratorWrapper(MyCollection<T> c) { this.c = c; Monitor.Enter(c.syncRoot); }\n public void Dispose() { if (!disposed) Monitor.Exit(c.syncRoot); disposed = true; }\n\n public IEnumerator<T> GetEnumerator()\n {\n return c.list.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n\n\n public void Add(T item) { lock (syncRoot) list.Add(item); }\n\npublic int Count\n{\n get { lock (syncRoot) return list.Count; }\n}\n\npublic IteratorWrapper GetIteratorWrapper()\n{\n return new IteratorWrapper(this);\n}\n\n\npublic class IteratorWrapper : IDisposable, IEnumerable<T>\n{\n bool disposed;\n MyCollection<T> c;\n public IteratorWrapper(MyCollection<T> c) { this.c = c; Monitor.Enter(c.syncRoot); }\n public void Dispose() { if (!disposed) Monitor.Exit(c.syncRoot); disposed = true; }\n\n public IEnumerator<T> GetEnumerator()\n {\n return c.list.GetEnumerator();\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n }\n \nclass Program\n{\n static MyCollection strings = new MyCollection(); \n\nstatic void Main(string[] args)\n{\n new Thread(adder).Start();\n Thread.Sleep(15);\n dump();\n Thread.Sleep(125);\n dump();\n Console.WriteLine(\"Press any key.\");\n Console.ReadKey(true);\n}\n\nstatic void dump()\n{\n Console.WriteLine(string.Format(\"Count={0}\", strings.Count).PadLeft(40, '-'));\n using (var enumerable = strings.GetIteratorWrapper())\n {\n foreach (var s in enumerable)\n Console.WriteLine(s);\n }\n Console.WriteLine(\"\".PadLeft(40, '-'));\n}\n\nstatic void adder()\n{\n for (int i = 0; i < 100; i++)\n {\n strings.Add(Guid.NewGuid().ToString(\"N\"));\n Thread.Sleep(7);\n }\n}\n\n\n static void Main(string[] args)\n{\n new Thread(adder).Start();\n Thread.Sleep(15);\n dump();\n Thread.Sleep(125);\n dump();\n Console.WriteLine(\"Press any key.\");\n Console.ReadKey(true);\n}\n\nstatic void dump()\n{\n Console.WriteLine(string.Format(\"Count={0}\", strings.Count).PadLeft(40, '-'));\n using (var enumerable = strings.GetIteratorWrapper())\n {\n foreach (var s in enumerable)\n Console.WriteLine(s);\n }\n Console.WriteLine(\"\".PadLeft(40, '-'));\n}\n\nstatic void adder()\n{\n for (int i = 0; i < 100; i++)\n {\n strings.Add(Guid.NewGuid().ToString(\"N\"));\n Thread.Sleep(7);\n }\n}\n }\n var a = new string[strings.Count];\nfor (int i=0; i < strings.Count; i++) { ... }\n var n = strings.Count;\nvar a = new string[n];\nfor (int i=0; i < n; i++) { ... }\n add/remove/lookup"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2099426/"
] |
186,544
|
<p>I need a function which executes an INSERT statement on a database and returns the Auto_Increment primary key. I have the following C# code but, while the INSERT statement works fine (I can see the record in the database, the PK is generated correctly and rows == 1), the id value is always 0. Any ideas on what might be going wrong?</p>
<pre><code> public int ExecuteInsertStatement(string statement)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement;
int rows = cmdInsert.ExecuteNonQuery();
if (rows == 1)
{
IDbCommand cmdId = connection.CreateCommand();
cmdId.CommandText = "SELECT @@Identity;";
id = (int)cmdId.ExecuteScalar();
}
return id;
}
private void InitializeAndOpenConnection()
{
if (connection == null)
connection = OleDbProviderFactory.Instance.CreateConnection(connectString);
if(connection.State != ConnectionState.Open)
connection.Open();
}
</code></pre>
<p>In response to answers, I tried:</p>
<pre><code>public int ExecuteInsertStatement(string statement, string tableName)
{
InitializeAndOpenConnection();
int id = -1;
IDbCommand cmdInsert = connection.CreateCommand();
cmdInsert.CommandText = statement + ";SELECT OID FROM " + tableName + " WHERE OID = SCOPE_IDENTITY();";
id = (int)cmdInsert.ExecuteScalar();
return id;
}
</code></pre>
<p>but I'm now getting the error "Characters found after end of SQL statement"</p>
<p>I'm using an MS Access database with OleDb connection, Provider=Microsoft.Jet.OLEDB.4.0</p>
|
[
{
"answer_id": 186564,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": -1,
"selected": false,
"text": "public int ExecuteInsertStatement(string statement)\n{\n InitializeAndOpenConnection();\n\n IDbCommand cmdInsert = connection.CreateCommand();\n cmdInsert.CommandText = statement + \"; SELECT @@Identity\";\n object result = cmdInsert.ExecuteScalar();\n\n if (object == DBNull.Value)\n {\n return -1;\n }\n else\n {\n return Convert.ToInt32(result);\n }\n}\n"
},
{
"answer_id": 186565,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 2,
"selected": false,
"text": "SELECT SCOPE_IDENTITY() \n"
},
{
"answer_id": 186659,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "SELECT @@IDENTITY INSERT"
},
{
"answer_id": 900394,
"author": "Fuangwith S.",
"author_id": 24550,
"author_profile": "https://Stackoverflow.com/users/24550",
"pm_score": 0,
"selected": false,
"text": "OleDbConnection connection = String.Format(\"Provider=Microsoft.Jet.OLEDB.4.0;Password={0};Data Source={1};Persist Security Info=True\",dbinfo.Password,dbinfo.MsAccessDBFile);\nconnection.Open();\nOleDbTransaction transaction = null;\ntry{\n connection.BeginTransaction();\n String commandInsert = \"INSERT INTO TB_SAMPLE ([NAME]) VALUES ('MR. DUKE')\";\n OleDbCommand cmd = new OleDbCommand(commandInsert , connection, transaction);\n cmd.ExecuteNonQuery();\n String commandIndentity = \"SELECT @@IDENTITY\";\n cmd = new OleDbCommandcommandIndentity, connection, transaction);\n Console.WriteLine(\"New Running No = {0}\", (int)cmd.ExecuteScalar());\n connection.Commit();\n}catch(Exception ex){\n connection.Rollback();\n}finally{\n connection.Close();\n} \n"
},
{
"answer_id": 2036484,
"author": "imam kuncoro",
"author_id": 242000,
"author_profile": "https://Stackoverflow.com/users/242000",
"pm_score": -1,
"selected": false,
"text": "CREATE procedure dbo.sp_whlogin\n(\n @id nvarchar(20),\n @ps nvarchar(20),\n @curdate datetime,\n @expdate datetime\n)\n\nAS\nBEGIN\n DECLARE @role nvarchar(20)\n DECLARE @menu varchar(255)\n DECLARE @loginid int\n\n SELECT @role = RoleID\n FROM dbo.TblUsers\n WHERE UserID = @id AND UserPass = @ps\n\n if @role is not null \n BEGIN\n INSERT INTO TblLoginLog (UserID, LoginAt, ExpireAt, IsLogin) VALUES (@id, @curdate, @expdate, 1);\n SELECT @loginid = @@IDENTITY;\n SELECT @loginid as loginid, RoleName as role, RoleMenu as menu FROM TblUserRoles WHERE RoleName = @role\n END\n else\n BEGIN\n SELECT '' as role, '' as menu\n END\nEND\nGO\n"
},
{
"answer_id": 30603486,
"author": "user1943915",
"author_id": 1943915,
"author_profile": "https://Stackoverflow.com/users/1943915",
"pm_score": 0,
"selected": false,
"text": " class Program\n{\n static string path = @\"<your path>\";\n static string db = @\"Test.mdb\";\n static void Main(string[] args)\n {\n string cs = String.Format(@\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}\\{1}\", path, db);\n // Using the same connection for the insert and the SELECT @@IDENTITY\n using (OleDbConnection con = new OleDbConnection(cs))\n {\n con.Open();\n OleDbCommand cmd = con.CreateCommand();\n for (int i = 0; i < 3; i++)\n {\n cmd.CommandText = \"INSERT INTO TestTable(OurTxt) VALUES ('\" + i.ToString() + \"')\";\n cmd.ExecuteNonQuery();\n\n cmd.CommandText = \"SELECT @@IDENTITY\";\n Console.WriteLine(\"AutoNumber: {0}\", (int)cmd.ExecuteScalar());\n }\n con.Close();\n }\n // Using a new connection and then SELECT @@IDENTITY\n using (OleDbConnection con = new OleDbConnection(cs))\n {\n con.Open();\n OleDbCommand cmd = con.CreateCommand();\n cmd.CommandText = \"SELECT @@IDENTITY\";\n Console.WriteLine(\"\\nNew connection, AutoNumber: {0}\", (int)cmd.ExecuteScalar());\n con.Close();\n }\n }\n}\n AutoNumber: 1 <br>\nAutoNumber: 2 <br>\nAutoNumber: 3 <br>\n\nNew connection, AutoNumber: 0\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23826/"
] |
186,548
|
<p>I am using IIS6, I've written an HttpModule, and I get this error? After googling the web I find that this problem is caused by the .NET framework 3.5, so I put this on a machine where I didn't install .NET 3.5, but the problem is still there!</p>
|
[
{
"answer_id": 186610,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 5,
"selected": false,
"text": "Response.Headers(\"X-Foo\") = \"bar\"\n Response.AddHeader(\"X-Foo\", \"bar\")\n"
},
{
"answer_id": 2852833,
"author": "Michael Itzoe",
"author_id": 24566,
"author_profile": "https://Stackoverflow.com/users/24566",
"pm_score": 3,
"selected": false,
"text": "Response.AddHeader Response.Headers.Add"
},
{
"answer_id": 21110920,
"author": "Russell",
"author_id": 185589,
"author_profile": "https://Stackoverflow.com/users/185589",
"pm_score": 0,
"selected": false,
"text": "Response.Headers .Headers Response.AddHeader() Response.ClearHeaders()"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20142/"
] |
186,553
|
<p>There is the button control in silverlight application . Can I send a mouse click event to it programmatically?</p>
|
[
{
"answer_id": 186618,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": -1,
"selected": false,
"text": ".Click(Object o, EventArgs e)"
},
{
"answer_id": 2038555,
"author": "Damián Ulises Cedillo",
"author_id": 247630,
"author_profile": "https://Stackoverflow.com/users/247630",
"pm_score": 0,
"selected": false,
"text": " private void btnSave_Click(object sender, RoutedEventArgs e)\n {\n //.....Save Operation\n\n //--At Finish refresh the datagrid\n btnRead_Click(btnRead, new RoutedEventArgs());\n }\n"
},
{
"answer_id": 3095409,
"author": "Nadzzz",
"author_id": 224214,
"author_profile": "https://Stackoverflow.com/users/224214",
"pm_score": 4,
"selected": false,
"text": "if (button is Button)\n{\n ButtonAutomationPeer peer = new ButtonAutomationPeer((Button)button);\n\n IInvokeProvider ip = (IInvokeProvider)peer;\n ip.Invoke();\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
186,556
|
<p>Say you have 100 directories and for each directory you have a file named .pdf stored somewhere else. If you want to move/copy each file into the directory with the same name, can this be done on the Windows command line?</p>
|
[
{
"answer_id": 186592,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 2,
"selected": false,
"text": "for /f %%f in ('dir /s /b c:\\source\\*.pdf') do copy \"%%f\" c:\\target\n for /f %%f in (files.txt) do copy \"%%f\" c:\\target\n"
},
{
"answer_id": 186608,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "setlocal\nset target_dir=D:\\\nset source_dir=C:\\WINDOWS\n\nfor %%i in (%source_dir%\\*.pdf) do move %%i %target_dir%\\%%~ni.%%~xi\n\nendlocal\n"
},
{
"answer_id": 217613,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 2,
"selected": false,
"text": "for /f %f in ('dir /s /b mypath\\*.pdf') do @copy %~nxf myotherpath\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13220/"
] |
186,569
|
<p>Will users who do not have admin rights on their computers be able to upgrade to new Flash player version by themselves?</p>
<p>This would be interesting to know for:
Windows 98
Windows XP/2000/Vista
Macs
Unix/Linux</p>
|
[
{
"answer_id": 186595,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": true,
"text": "~/.mozilla/plugins .tar.gz"
},
{
"answer_id": 186668,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 3,
"selected": false,
"text": "Library/Internet Plug-ins\n /Library/Internet Plug-ins\n /Users/<username>/Library/Internet Plug-ins\n"
},
{
"answer_id": 750767,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "* %APPDATA% is the folder which holds your applications profiles and settings.\n* You can open this folder simply choosing \"Start → Run → Type in %APPDATA% → OK\".\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
186,572
|
<p>Using SQL Server - which is the fastest or best practice method to use for date retrieval? Is there a difference?</p>
|
[
{
"answer_id": 186578,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 3,
"selected": false,
"text": "CURRENT_TIMESTAMP GETDATE()"
},
{
"answer_id": 186582,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 8,
"selected": true,
"text": "CURRENT_TIMESTAMP"
},
{
"answer_id": 186586,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 5,
"selected": false,
"text": "CURRENT_TIMESTAMP GETDATE()"
},
{
"answer_id": 186777,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 4,
"selected": false,
"text": "CURRENT_TIMESTAMP getdatetime() DATE TIME CURRENT_DATE CURRENT_TIME getdate()"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
186,588
|
<p>When you limit the number of rows to be returned by a SQL query, usually used in paging, there are two methods to determine the total number of records:</p>
<h3>Method 1</h3>
<p>Include the <code>SQL_CALC_FOUND_ROWS</code> option in the original <code>SELECT</code>, and then get the total number of rows by running <code>SELECT FOUND_ROWS()</code>:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE id > 100 LIMIT 10;
SELECT FOUND_ROWS();
</code></pre>
<h3>Method 2</h3>
<p>Run the query normally, and then get the total number of rows by running <code>SELECT COUNT(*)</code></p>
<pre><code>SELECT * FROM table WHERE id > 100 LIMIT 10;
SELECT COUNT(*) FROM table WHERE id > 100;
</code></pre>
<p><strong>Which method is the best / fastest?</strong></p>
|
[
{
"answer_id": 188682,
"author": "nathan",
"author_id": 16430,
"author_profile": "https://Stackoverflow.com/users/16430",
"pm_score": 8,
"selected": true,
"text": "SQL_CALC_FOUND_ROWS SQL_CALC_FOUND_ROWS SQL_CALC_FOUND_ROWS"
},
{
"answer_id": 25124430,
"author": "Pierre-Olivier Vares",
"author_id": 2955802,
"author_profile": "https://Stackoverflow.com/users/2955802",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;\nSELECT count(*) FROM count_test WHERE b = 666;\n SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;\n"
},
{
"answer_id": 36485946,
"author": "Jessé Catrinck",
"author_id": 3625217,
"author_profile": "https://Stackoverflow.com/users/3625217",
"pm_score": 3,
"selected": false,
"text": "COUNT(*) SQL_CALC_FOUND_ROWS SELECT Person.Id, Person.Name, Job.Description, Card.Number\nFROM Person\nJOIN Job ON Job.Id = Person.Job_Id\nLEFT JOIN Card ON Card.Person_Id = Person.Id\nWHERE Job.Name = 'WEB Developer'\nORDER BY Person.Name\n SELECT COUNT(*)\nFROM Person\nJOIN Job ON Job.Id = Person.Job_Id\nWHERE Job.Name = 'WEB Developer'\n"
},
{
"answer_id": 55708509,
"author": "Madhur Bhaiya",
"author_id": 2469308,
"author_profile": "https://Stackoverflow.com/users/2469308",
"pm_score": 5,
"selected": false,
"text": "SQL_CALC_FOUND_ROWS LIMIT COUNT(*) LIMIT SELECT * FROM tbl_name WHERE id > 100 LIMIT 10;\nSELECT COUNT(*) WHERE id > 100;\n SQL_CALC_FOUND_ROWS"
},
{
"answer_id": 55909522,
"author": "Code4R7",
"author_id": 7740888,
"author_profile": "https://Stackoverflow.com/users/7740888",
"pm_score": 2,
"selected": false,
"text": "SELECT \n `mytable`.*,\n COUNT(*) OVER() AS `total_count`\nFROM `mytable`\nORDER BY `mycol`\nLIMIT 10, 20\n SELECT `TABLE_ROWS` AS `rows_approx`\nFROM `INFORMATION_SCHEMA`.`TABLES`\nWHERE `TABLE_SCHEMA` = DATABASE()\n AND `TABLE_TYPE` = \"BASE TABLE\"\n AND `TABLE_NAME` = ?\n"
},
{
"answer_id": 69598853,
"author": "Ja Loc",
"author_id": 4678594,
"author_profile": "https://Stackoverflow.com/users/4678594",
"pm_score": 0,
"selected": false,
"text": "select fieldname \nfrom table_add \nwhere \ndescryption_per like '%marihuana%' \nor addiction_per like '%alkohol%';\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
] |
186,606
|
<p>Can i override fetchall method in a model? I need to check sth everytime fetchAll is called. The model extends Zend_db_table_abstract</p>
|
[
{
"answer_id": 198102,
"author": "Kieran Hall",
"author_id": 6085,
"author_profile": "https://Stackoverflow.com/users/6085",
"pm_score": 3,
"selected": false,
"text": "<?php\nabstract class My_Db_Table_Abstract extends Zend_Db_Table_Abstract\n{\n ...\n\n public function fetchAll($where, $order)\n {\n ...\n }\n\n ...\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24789/"
] |
186,622
|
<ol>
<li>How precise is the VB6 <code>Date</code> data type (by way of fractions of a second)?</li>
<li>How to format it to show fractions of a second?</li>
</ol>
<p>I'm revisiting VB6 after many years absence, and for the life of me can't remember the things I used to know. I considered putting a <a href="/questions/tagged/memory-leak" class="post-tag" title="show questions tagged 'memory-leak'" rel="tag">memory-leak</a> tag on this, because my memory leaked (hur hur hur).</p>
<p>I found this API call afterwards, and it seems to work:</p>
<pre><code>Declare Sub GetSystemTime Lib "kernel32.dll" (lpSystemTime As SystemTime)
Public Type SystemTime
Year As Integer
Month As Integer
DayOfWeek As Integer
Day As Integer
Hour As Integer
Minute As Integer
Second As Integer
Milliseconds As Integer
End Type
</code></pre>
|
[
{
"answer_id": 187052,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": false,
"text": "Date Double Double Double Date Now DateSerial DateDiff DateAdd Double StdDataFormat"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18797/"
] |
186,631
|
<p>I have a WCF service and I want to expose it as both a RESTfull service and as a SOAP service.
Anyone has done something like this before?</p>
|
[
{
"answer_id": 186695,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 10,
"selected": true,
"text": "<endpointBehaviors>\n <behavior name=\"jsonBehavior\">\n <enableWebScript/>\n </behavior>\n</endpointBehaviors>\n <services>\n <service name=\"TestService\">\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" contract=\"ITestService\"/>\n <endpoint address=\"json\" binding=\"webHttpBinding\" behaviorConfiguration=\"jsonBehavior\" contract=\"ITestService\"/>\n </service>\n</services>\n public interface ITestService\n{\n [OperationContract]\n [WebGet]\n string HelloWorld(string text)\n}\n [ServiceContract(Namespace = \"http://test\")]\npublic interface ITestService\n{\n [OperationContract]\n [WebGet(UriTemplate = \"accounts/{id}\")]\n Account[] GetAccount(string id);\n}\n <behavior name=\"poxBehavior\">\n <webHttp/>\n</behavior>\n <services>\n <service name=\"TestService\">\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" contract=\"ITestService\"/>\n <endpoint address=\"xml\" binding=\"webHttpBinding\" behaviorConfiguration=\"poxBehavior\" contract=\"ITestService\"/>\n </service>\n</services>\n <client>\n <endpoint address=\"http://www.example.com/soap\" binding=\"basicHttpBinding\"\n contract=\"ITestService\" name=\"BasicHttpBinding_ITestService\" />\n </client>\n TestServiceClient client = new TestServiceClient();\nclient.GetAccount(\"A123\");\n"
},
{
"answer_id": 2295887,
"author": "Tuomas Hietanen",
"author_id": 17791,
"author_profile": "https://Stackoverflow.com/users/17791",
"pm_score": 5,
"selected": false,
"text": "<system.serviceModel>\n <services>\n <service name=\"MyService\" behaviorConfiguration=\"MyServiceBehavior\">\n <endpoint name=\"rest\" address=\"\" binding=\"webHttpBinding\" contract=\"MyService\" behaviorConfiguration=\"restBehavior\"/>\n <endpoint name=\"mex\" address=\"mex\" binding=\"mexHttpBinding\" contract=\"MyService\"/>\n <endpoint name=\"soap\" address=\"soap\" binding=\"basicHttpBinding\" contract=\"MyService\"/>\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"MyServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\"/>\n <serviceDebug includeExceptionDetailInFaults=\"true\" />\n </behavior>\n </serviceBehaviors>\n <endpointBehaviors>\n <behavior name=\"restBehavior\">\n <webHttp/>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n</system.serviceModel>\n /// <summary> MyService documentation here ;) </summary>\n[ServiceContract(Name = \"MyService\", Namespace = \"http://myservice/\", SessionMode = SessionMode.NotAllowed)]\n//[ServiceKnownType(typeof (IList<MyDataContractTypes>))]\n[ServiceBehavior(Name = \"MyService\", Namespace = \"http://myservice/\")]\npublic class MyService\n{\n [OperationContract(Name = \"MyResource1\")]\n [WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = \"MyXmlResource/{key}\")]\n public string MyResource1(string key)\n {\n return \"Test: \" + key;\n }\n\n [OperationContract(Name = \"MyResource2\")]\n [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = \"MyJsonResource/{key}\")]\n public string MyResource2(string key)\n {\n return \"Test: \" + key;\n }\n}\n [OperationContract(Name = \"MyResourceSave\")]\n[WebInvoke(Method = \"POST\", ResponseFormat = WebMessageFormat.Json, UriTemplate = \"MyJsonResource\")]\npublic string MyResourceSave(string thing){\n //...\n"
},
{
"answer_id": 3508407,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": 5,
"selected": false,
"text": "public class Hello {\n public string Name { get; set; }\n}\n\npublic class HelloResponse {\n public string Result { get; set; }\n}\n\npublic class HelloService : IService\n{\n public object Any(Hello request)\n {\n return new HelloResponse { Result = \"Hello, \" + request.Name };\n }\n}\n"
},
{
"answer_id": 48614701,
"author": "Jailson Evora",
"author_id": 7002459,
"author_profile": "https://Stackoverflow.com/users/7002459",
"pm_score": 2,
"selected": false,
"text": "<endpointBehaviors>\n <behavior name=\"restfulBehavior\">\n <webHttp defaultOutgoingResponseFormat=\"Json\" defaultBodyStyle=\"Wrapped\" automaticFormatSelectionEnabled=\"False\" />\n </behavior>\n</endpointBehaviors>\n <serviceBehaviors>\n <behavior>\n <serviceMetadata httpGetEnabled=\"true\" httpsGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n</serviceBehaviors>\n <bindings>\n <basicHttpBinding>\n <binding name=\"soapService\" />\n </basicHttpBinding>\n <webHttpBinding>\n <binding name=\"jsonp\" crossDomainScriptAccessEnabled=\"true\" />\n </webHttpBinding>\n</bindings>\n <services>\n <service name=\"ComposerWcf.ComposerService\">\n <endpoint address=\"\" behaviorConfiguration=\"restfulBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"jsonp\" name=\"jsonService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"soapService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" name=\"metadata\" contract=\"IMetadataExchange\" />\n </service>\n</services>\n namespace ComposerWcf.Interface\n{\n [ServiceContract]\n public interface IComposerService\n {\n [OperationContract]\n [WebInvoke(Method = \"GET\", UriTemplate = \"/autenticationInfo/{app_id}/{access_token}\", ResponseFormat = WebMessageFormat.Json,\n RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]\n Task<UserCacheComplexType_RootObject> autenticationInfo(string app_id, string access_token);\n }\n}\n <system.serviceModel>\n\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"restfulBehavior\">\n <webHttp defaultOutgoingResponseFormat=\"Json\" defaultBodyStyle=\"Wrapped\" automaticFormatSelectionEnabled=\"False\" />\n </behavior>\n </endpointBehaviors>\n <serviceBehaviors>\n <behavior>\n <serviceMetadata httpGetEnabled=\"true\" httpsGetEnabled=\"true\" />\n <serviceDebug includeExceptionDetailInFaults=\"false\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n\n <bindings>\n <basicHttpBinding>\n <binding name=\"soapService\" />\n </basicHttpBinding>\n <webHttpBinding>\n <binding name=\"jsonp\" crossDomainScriptAccessEnabled=\"true\" />\n </webHttpBinding>\n </bindings>\n\n <protocolMapping>\n <add binding=\"basicHttpsBinding\" scheme=\"https\" />\n </protocolMapping>\n\n <serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\" multipleSiteBindingsEnabled=\"true\" />\n\n <services>\n <service name=\"ComposerWcf.ComposerService\">\n <endpoint address=\"\" behaviorConfiguration=\"restfulBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"jsonp\" name=\"jsonService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"soapService\" contract=\"ComposerWcf.Interface.IComposerService\" />\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" name=\"metadata\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n\n</system.serviceModel>\n"
},
{
"answer_id": 49169251,
"author": "Nayas Subramanian",
"author_id": 4315441,
"author_profile": "https://Stackoverflow.com/users/4315441",
"pm_score": 0,
"selected": false,
"text": "[ServiceContract]\npublic interface ITestService\n{\n\n [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = \"/product\", ResponseFormat = WebMessageFormat.Json)]\n string GetData();\n}\n\npublic class TestService : ITestService\n{\n public string GetJsonData()\n {\n return \"I am good...\";\n }\n}\n <service name=\"TechCity.Business.TestService\">\n\n <endpoint address=\"soap\" binding=\"basicHttpBinding\" name=\"SoapTest\"\n bindingName=\"BasicSoap\" contract=\"TechCity.Interfaces.ITestService\" />\n <endpoint address=\"mex\"\n contract=\"IMetadataExchange\" binding=\"mexHttpBinding\"/>\n <endpoint behaviorConfiguration=\"jsonBehavior\" binding=\"webHttpBinding\"\n name=\"Http\" contract=\"TechCity.Interfaces.ITestService\" />\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8739/test\" />\n </baseAddresses>\n </host>\n </service>\n <endpointBehaviors>\n <behavior name=\"jsonBehavior\">\n <webHttp automaticFormatSelectionEnabled=\"true\" />\n <!-- use JSON serialization -->\n </behavior>\n </endpointBehaviors>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15314/"
] |
186,633
|
<p>I am actually loading a page as a modal dialog box as window.showModalDialog("url.aspx"). The first time the modal dialog is poped up the page load event gets called. When i close it and call the same again, the Control does not come to the PageLoad. Instead the page pops up with the previous values in all its controls. </p>
<p>I actually want the PageLoad to be triggered everytime the modal dialog pops up.</p>
|
[
{
"answer_id": 618237,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "InPage <%@ OutputCache Location=\"None\" %>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20951/"
] |
186,634
|
<p>I've got the following example running in a simple Silverlight page:</p>
<pre><code>public Page()
{
InitializeComponent();
InitializeOther();
}
private DoubleCollection dashes;
public DoubleCollection Dashes
{
get
{
//dashes = new DoubleCollection(); //works ok
//dashes.Add(2.0);
//dashes.Add(2.0);
if (dashes == null)
{
dashes = new DoubleCollection(); //causes exception
dashes.Add(2.0);
dashes.Add(2.0);
}
return dashes;
}
set
{
dashes = value;
}
}
private void InitializeOther()
{
Line line;
for (int i = 0; i < 10; i++)
{
line = new Line();
line.Stroke = new SolidColorBrush(Colors.Blue);
line.StrokeDashArray = Dashes; //exception thrown here
line.X1 = 10;
line.Y2 = 10;
line.X2 = 400;
line.Y2 = 10 + (i * 40);
canvas1.Children.Add(line);
}
}
</code></pre>
<p>The above code throws a System.ArgumentException on the line marked. One solution to the problem is also marked in the example.</p>
<p>Does anybody know if this problem is related to the fact that the property System.Windows.Shapes.Shape.StrokeDashArray is a dependency property? </p>
|
[
{
"answer_id": 188301,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 0,
"selected": false,
"text": "line = new Line(); \nline.Stroke = new SolidColorBrush(Colors.Blue);\nline.StrokeDashArray = **new DoubleCollection() { 2.0, 2.0 };** \nline.X1 = 10; \n...\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23724/"
] |
186,648
|
<p>I'm working on a C++ library that (among other stuff) has functions to read config files; and I want to add tests for this. So far, this has lead me to create lots of valid and invalid config files, each with only a few lines that test one specific functionality. But it has now got very unwieldy, as there are so many files, and also lots of small C++ test apps. Somehow this seems wrong to me :-) so do you have hints how to organise all these tests, the test apps, and the test data?</p>
<p>Note: the library's public API itself is not easily testable (it requires a config file as parameter). The juicy, bug-prone methods for actually reading and interpreting config values are private, so I don't see a way to test them directly?</p>
<p>So: would you stick with testing against real files; and if so, how would you organise all these files and apps so that they are still maintainable?</p>
|
[
{
"answer_id": 186690,
"author": "richq",
"author_id": 4596,
"author_profile": "https://Stackoverflow.com/users/4596",
"pm_score": 3,
"selected": false,
"text": " project/\n src/\n tests/\n test1/\n input/\n test2\n input/\n"
},
{
"answer_id": 186778,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "/project/src/component_a/piece_2/this_bit\n /project/test/the_first_components/connection_tests/test_a\n /project/test/component_a/piece_2/this_bit/test_a\n"
},
{
"answer_id": 186804,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "solution/project1/src <-- source code\nsolution/project1/src/tests <-- unit test code \nsolution/project2/src <-- source code\nsolution/project2/src/tests <-- unit test code \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
] |
186,653
|
<p>Unless I am missing an obvious built-in method, what is the quickest way to get the <em>n</em>th occurrence of a string within a string?</p>
<p>I realize that I could loop the <a href="https://msdn.microsoft.com/en-us/library/k8b1470s(v=vs.110).aspx" rel="noreferrer">IndexOf</a> method by updating its start index on each iteration of the loop. But doing it this way seems wasteful to me.</p>
|
[
{
"answer_id": 187394,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 7,
"selected": false,
"text": "/((s).*?){n}/ s public static class StringExtender\n{\n public static int NthIndexOf(this string target, string value, int n)\n {\n Match m = Regex.Match(target, \"((\" + Regex.Escape(value) + \").*?){\" + n + \"}\");\n\n if (m.Success)\n return m.Groups[2].Captures[n - 1].Index;\n else\n return -1;\n }\n}\n Regex.Escape"
},
{
"answer_id": 1529503,
"author": "Schotime",
"author_id": 29376,
"author_profile": "https://Stackoverflow.com/users/29376",
"pm_score": 4,
"selected": false,
"text": "private int IndexOfOccurence(string s, string match, int occurence)\n{\n int i = 1;\n int index = 0;\n\n while (i <= occurence && (index = s.IndexOf(match, index + 1)) != -1)\n {\n if (i == occurence)\n return index;\n\n i++;\n }\n\n return -1;\n}\n public static int IndexOfOccurence(this string s, string match, int occurence)\n{\n int i = 1;\n int index = 0;\n\n while (i <= occurence && (index = s.IndexOf(match, index + 1)) != -1)\n {\n if (i == occurence)\n return index;\n\n i++;\n }\n\n return -1;\n}\n"
},
{
"answer_id": 5386443,
"author": "Tod Thomson",
"author_id": 372666,
"author_profile": "https://Stackoverflow.com/users/372666",
"pm_score": 4,
"selected": false,
"text": "public static int IndexOfNth(this string input,\n string value, int startIndex, int nth)\n{\n if (nth < 1)\n throw new NotSupportedException(\"Param 'nth' must be greater than 0!\");\n if (nth == 1)\n return input.IndexOf(value, startIndex);\n var idx = input.IndexOf(value, startIndex);\n if (idx == -1)\n return -1;\n return input.IndexOfNth(value, idx + 1, --nth);\n}\n using System;\nusing MbUnit.Framework;\n\nnamespace IndexOfNthTest\n{\n [TestFixture]\n public class Tests\n {\n //has 4 instances of the \n private const string Input = \"TestTest\";\n private const string Token = \"Test\";\n\n /* Test for 0th index */\n\n [Test]\n public void TestZero()\n {\n Assert.Throws<NotSupportedException>(\n () => Input.IndexOfNth(Token, 0, 0));\n }\n\n /* Test the two standard cases (1st and 2nd) */\n\n [Test]\n public void TestFirst()\n {\n Assert.AreEqual(0, Input.IndexOfNth(\"Test\", 0, 1));\n }\n\n [Test]\n public void TestSecond()\n {\n Assert.AreEqual(4, Input.IndexOfNth(\"Test\", 0, 2));\n }\n\n /* Test the 'out of bounds' case */\n\n [Test]\n public void TestThird()\n {\n Assert.AreEqual(-1, Input.IndexOfNth(\"Test\", 0, 3));\n }\n\n /* Test the offset case (in and out of bounds) */\n\n [Test]\n public void TestFirstWithOneOffset()\n {\n Assert.AreEqual(4, Input.IndexOfNth(\"Test\", 4, 1));\n }\n\n [Test]\n public void TestFirstWithTwoOffsets()\n {\n Assert.AreEqual(-1, Input.IndexOfNth(\"Test\", 8, 1));\n }\n }\n}\n"
},
{
"answer_id": 11381309,
"author": "Sameer Shaikh",
"author_id": 1509689,
"author_profile": "https://Stackoverflow.com/users/1509689",
"pm_score": -1,
"selected": false,
"text": "Console.WriteLine(str.IndexOf((@\"\\\")+2)+1);\n"
},
{
"answer_id": 23627017,
"author": "user3227623",
"author_id": 3227623,
"author_profile": "https://Stackoverflow.com/users/3227623",
"pm_score": 1,
"selected": false,
"text": "String.Split()"
},
{
"answer_id": 51754699,
"author": "ShadowBeast",
"author_id": 6882924,
"author_profile": "https://Stackoverflow.com/users/6882924",
"pm_score": 2,
"selected": false,
"text": "public static int IndexOfNthSB(string input,\n char value, int startIndex, int nth)\n {\n if (nth < 1)\n throw new NotSupportedException(\"Param 'nth' must be greater than 0!\");\n var nResult = 0;\n for (int i = startIndex; i < input.Length; i++)\n {\n if (input[i] == value)\n nResult++;\n if (nResult == nth)\n return i;\n }\n return -1;\n }\n"
},
{
"answer_id": 51913441,
"author": "Matthias",
"author_id": 568266,
"author_profile": "https://Stackoverflow.com/users/568266",
"pm_score": 0,
"selected": false,
"text": "var index = line.Select((x, i) => (x, i)).Where(x => x.Item1 == '\"').ElementAt(5).Item2;"
},
{
"answer_id": 57527477,
"author": "ivvi",
"author_id": 1257965,
"author_profile": "https://Stackoverflow.com/users/1257965",
"pm_score": 0,
"selected": false,
"text": "using System;\n\nstatic class MainClass {\n private static int IndexOfNth(this string target, string substring,\n int seqNr, int startIdx = 0)\n {\n if (seqNr < 1)\n {\n throw new IndexOutOfRangeException(\"Parameter 'nth' must be greater than 0.\");\n }\n\n var idx = target.IndexOf(substring, startIdx);\n\n if (idx < 0 || seqNr == 1) { return idx; }\n\n return target.IndexOfNth(substring, --seqNr, ++idx); // skip\n }\n\n static void Main () {\n Console.WriteLine (\"abcbcbcd\".IndexOfNth(\"bc\", 1));\n Console.WriteLine (\"abcbcbcd\".IndexOfNth(\"bc\", 2));\n Console.WriteLine (\"abcbcbcd\".IndexOfNth(\"bc\", 3));\n Console.WriteLine (\"abcbcbcd\".IndexOfNth(\"bc\", 4));\n }\n}\n 1\n3\n5\n-1\n"
},
{
"answer_id": 59440071,
"author": "xFreeD",
"author_id": 10636977,
"author_profile": "https://Stackoverflow.com/users/10636977",
"pm_score": 1,
"selected": false,
"text": " private static int OrdinalIndexOf(string str, string substr, int n)\n {\n int pos = -1;\n do\n {\n pos = str.IndexOf(substr, pos + 1);\n } while (n-- > 0 && pos != -1);\n return pos;\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16989/"
] |
186,655
|
<p>I coded something using Date statement in Access VBA. It was working fine until the start of this month, but now I am seeing that the Date has automatically changed the format from <code>dd/mm/yyyy</code> to <code>mm/dd/yyyy</code>. Has anyone else encountered the same problem?</p>
|
[
{
"answer_id": 191765,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "strSQL=\"SELECT SomeDate FROM tblT WHERE SomeDate=#\" & Format(DateVar, \"yyyy/mm/dd\") & \"#\"\n"
},
{
"answer_id": 2498581,
"author": "Dkellygb",
"author_id": 290504,
"author_profile": "https://Stackoverflow.com/users/290504",
"pm_score": 0,
"selected": false,
"text": "\"Select * from DateTable where StartDate = datevalue(\" & me!TxtStartDate & \");\""
},
{
"answer_id": 9431177,
"author": "wael helaly",
"author_id": 1230803,
"author_profile": "https://Stackoverflow.com/users/1230803",
"pm_score": 1,
"selected": false,
"text": "stLinkCriteria = \"[ProjectDate] Between #\" & Format(CDate(Me![txtDateFrom]), \"mm/dd/yyyy\") & \"# And #\" & Format(CDate(Me![txtDateTo]), \"mm/dd/yyyy\") & \"#\"\n"
},
{
"answer_id": 30810092,
"author": "R114",
"author_id": 4198858,
"author_profile": "https://Stackoverflow.com/users/4198858",
"pm_score": 1,
"selected": false,
"text": "sentenciaSQL = \"UPDATE Numeraciones \" & _\n\"SET Valor = \" & Valor & \", \" & _\n\"Fecha = #\" & **Format(fecha,\"mm/dd/yyyy HH:nn:ss\") & \"#, \" &** _\n\"Id_Usuario = \" & Id_Usuario & _\n\" WHERE Nombre = '\" & Nombre & \"'\"\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6613/"
] |
186,657
|
<p>When I disable ViewState for the page. It does not allow any other control to use ViewState .. even if I set EnableViewState="true" for that particular control ..</p>
<p>is it possible to enable ViewState for a control when ViewState is disabled for the page itself?</p>
<p>if not how can disable viewstate for controls on page except for few without specifying EnableViewState="false" explicitly .. typing the same into so many controls is hectic ..</p>
|
[
{
"answer_id": 186732,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "List<string> allowedControls = new List<string> { \"Control1\", \"Control3\" };\nIEnumerable<Control> controlsWithoutViewState = Page.Controls.Where(c => !allowedControls.Contains(c.ID));\nforeach(Control c controlsWithoutViewState){\n if(c is WebControl) ((WebControl)c).EnableViewState = false;\n}\n IEnumerable<Control> controlsWithoutViewState = Page.Controls.Cast<Control>().Where(c => !allowedControls.Contains(c.ID));\n"
},
{
"answer_id": 530029,
"author": "Armstrongest",
"author_id": 26931,
"author_profile": "https://Stackoverflow.com/users/26931",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// All pages inherit this page\n/// </summary>\npublic class BasePage : System.Web.UI.Page {\n\n protected override void OnLoad(EventArgs e) {\n base.OnLoad(e);\n }\n\n public bool ViewStateEnabled {\n get {\n return Page.EnableViewState;\n }\n set {\n Page.EnableViewState = value;\n }\n }\n\n public BasePage() {\n // Disable ViewState By Default\n ViewStateEnabled = false;\n }\n}\n public partial class Products_Default : BasePage {\n protected void Page_Load(object sender, EventArgs e) {\n this.ViewStateEnabled = true;\n }\n}\n"
},
{
"answer_id": 1843033,
"author": "Adam",
"author_id": 212188,
"author_profile": "https://Stackoverflow.com/users/212188",
"pm_score": 0,
"selected": false,
"text": "Public Shared Sub DisableViewState(ByVal cntrl As Control)\n If TypeOf cntrl Is Label Then\n cntrl.EnableViewState = False\n ElseIf TypeOf cntrl Is Literal Then\n cntrl.EnableViewState = False\n ElseIf TypeOf cntrl Is Button Then\n cntrl.EnableViewState = False\n Else\n If cntrl.Controls IsNot Nothing Then\n For Each subControl As Control In cntrl.Controls\n DisableViewState(subControl)\n Next\n End If\n End If\nEnd Sub\n"
},
{
"answer_id": 4110130,
"author": "Georgios Politis",
"author_id": 421128,
"author_profile": "https://Stackoverflow.com/users/421128",
"pm_score": 3,
"selected": false,
"text": "using System.Web.UI;\nusing System.Web.UI.Adapters;\n\nnamespace Playground.Web.UI.Adapters\n{\n public class PageAdapter: System.Web.UI.Adapters.PageAdapter\n {\n protected override void OnLoad(EventArgs e)\n {\n ViewStateMode = ViewStateMode.Disabled;\n base.OnLoad(e);\n }\n }\n}\n <browser refID=\"default\">\n <controladapters>\n <adapter controlType=\"System.Web.UI.Page\" adapterType=\"Playground.Web.UI.Adapters.PageAdapter\" />\n </controladapters>\n</browser>\n"
},
{
"answer_id": 10478694,
"author": "Amitabh Phogat",
"author_id": 1379219,
"author_profile": "https://Stackoverflow.com/users/1379219",
"pm_score": 2,
"selected": false,
"text": "namespace BB.Common.UI.Adapters\n{\n [AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]\n public class DisableViewStateControl : System.Web.UI.Adapters.ControlAdapter\n {\n protected override void OnInit(EventArgs e)\n {\n if (Control.ViewStateMode == ViewStateMode.Inherit)\n Control.ViewStateMode = ViewStateMode.Disabled;\n base.OnInit(e);\n }\n }\n}\n <browsers>\n <browser refID=\"Default\" >\n <controlAdapters>\n <adapter\n controlType=\"System.Web.UI.WebControls.Label\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" />\n <adapter\n controlType=\"System.Web.UI.WebControls.HyperLink\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" />\n <adapter\n controlType=\"System.Web.UI.WebControls.ImageButton\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" />\n <adapter\n controlType=\"System.Web.UI.WebControls.Button\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" />\n <adapter\n controlType=\"System.Web.UI.WebControls.TextBox\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" />\n <adapter\n controlType=\"System.Web.UI.WebControls.CheckBox\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" /> \n <adapter\n controlType=\"System.Web.UI.WebControls.HiddenField\"\n adapterType=\"Fiserv.Common.UI.Adapters.DisableViewStateControl\" /> \n </controlAdapters>\n </browser>\n</browsers>\n"
},
{
"answer_id": 11106341,
"author": "BornToCode",
"author_id": 1057791,
"author_profile": "https://Stackoverflow.com/users/1057791",
"pm_score": 2,
"selected": false,
"text": "<%@ Page Language=\"C#\" EnableViewState=\"true\" ViewStateMode=\"Disabled\" %>\n <asp:yourcontrol EnableViewState=\"true\" ViewStateMode=\"Enabled\">\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25138/"
] |
186,671
|
<p>What avenues are there for using an XSD to generate message instances? I seem to remember reading about generating classes from XSD, but can't find anything specific now. I know you can generate classes and datasets from XSD, but I'm looking for a pattern for automating the actual generation of the messages.</p>
<p>BTW, SO is my knowledge sharer of choice, not Google.</p>
|
[
{
"answer_id": 186684,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": true,
"text": "xsd /c yourschema.xsd > yourschema.cs\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
186,718
|
<p>I have some really complicated legacy code I've been working on that crashes when collecting big chunks of data. I've been unable to find the exact reason for the crashes and am trying different ways to solve it or at least recover nicely. The last thing I did was enclose the crashing code in a</p>
<pre><code>try
...
except
cleanup();
end;
</code></pre>
<p>just to make it behave. But the cleanup never gets done. Under what circumstances does an exception not get caught? This might be due to some memory overflow or something since the app is collecting quite a bit of data.</p>
<p>Oh and the exception I got before adding the <code>try</code> was "Access violation" (what else?) and the CPU window points to very low addresses. Any ideas or pointers would be much appreciated!</p>
|
[
{
"answer_id": 188331,
"author": "Gustavo",
"author_id": 2015,
"author_profile": "https://Stackoverflow.com/users/2015",
"pm_score": 1,
"selected": false,
"text": "try\n...\nexcept\non E: EOleException do\n...\nend;\n"
},
{
"answer_id": 188733,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 1,
"selected": false,
"text": "try\n OutputDebugString('entering part abc');\n ... // part abc code here\nexcept\n OutputDebugString('horror in part abc');\n raise;\nend;\n... \ntry\n OutputDebugString('entering in part xyz');\n ... // part xyz code here\nexcept\n OutputDebugString('horror in part xyz');\n raise;\nend;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9077/"
] |
186,734
|
<p>Mobile Safari is a very capable browser, and it can handle my website as it is perfectly. However, there are a few elements on my page that could be optimized for browsing using this device; such as serving specific thumbnails that are smaller than the desktop counterparts to help fit more content into the screen.</p>
<p>I would like to know how I can detect Mobile Safari (all versions, preferably) using PHP, so then I can serve a) a specific css file and b) different sized image thumbnails.</p>
|
[
{
"answer_id": 186742,
"author": "GavinCattell",
"author_id": 21644,
"author_profile": "https://Stackoverflow.com/users/21644",
"pm_score": 2,
"selected": false,
"text": "$_SERVER['HTTP_USER_AGENT'] \n"
},
{
"answer_id": 186779,
"author": "different",
"author_id": 3654,
"author_profile": "https://Stackoverflow.com/users/3654",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n/* detect Mobile Safari */\n\n$browserAsString = $_SERVER['HTTP_USER_AGENT'];\n\nif (strstr($browserAsString, \" AppleWebKit/\") && strstr($browserAsString, \" Mobile/\"))\n{\n $browserIsMobileSafari = true;\n}\n\n?>\n"
},
{
"answer_id": 17144264,
"author": "Sebastian Witeczek",
"author_id": 2217427,
"author_profile": "https://Stackoverflow.com/users/2217427",
"pm_score": 0,
"selected": false,
"text": "<?php\n\n// detect Safari only!\n\n$string = $_SERVER['HTTP_USER_AGENT'];\n\nif (strstr($string, \" AppleWebKit/\") && strstr($string, \" Safari/\") && !strstr($string, \" CriOS\"))\n {\n echo 'See in Safari only';\n }\n\n?> \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3654/"
] |
186,737
|
<p>I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders? </p>
<p>Other details:</p>
<ul>
<li>I don't care about the recycle bin.</li>
<li>It's an NTFS drive.</li>
</ul>
|
[
{
"answer_id": 186748,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 10,
"selected": true,
"text": "rmdir /s /q folder\n powershell -Command \"Remove-Item -LiteralPath 'folder' -Force -Recurse\"\n del rmdir"
},
{
"answer_id": 629219,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "rmdir /s /q \"My Apps\" \nrmdir /s /q \"My Documents\" \nrmdir /s /q \"My Pictures\" \nrmdir /s /q \"My Work Files\"\n X: \ndeletefiles.bat\n"
},
{
"answer_id": 6208144,
"author": "Hugo",
"author_id": 724176,
"author_profile": "https://Stackoverflow.com/users/724176",
"pm_score": 10,
"selected": false,
"text": "rmdir /s/q foldername del /f/s/q foldername del /f/s/q foldername > nul\nrmdir /s/q foldername\n rmdir del+rmdir del+rmdir del /f /s /q rmdir /s /q"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11766/"
] |
186,756
|
<p>How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?</p>
<p>For example:</p>
<pre><code>nr
1
2
3
4
5
</code></pre>
<p>I would like to use only MySQL for this (not PHP or other languages).</p>
|
[
{
"answer_id": 186780,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "DECLARE i INT DEFAULT 0;\n\nWHILE i < 6 DO\n /* insert into table... */\n SET i = i + 1;\nEND WHILE;\n"
},
{
"answer_id": 186814,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 6,
"selected": true,
"text": "CREATE TABLE `incr` (\n `Id` int(11) NOT NULL auto_increment,\n PRIMARY KEY (`Id`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8;\n DELIMITER ;;\nCREATE PROCEDURE dowhile()\nBEGIN\n DECLARE v1 INT DEFAULT 5;\n WHILE v1 > 0 DO\n INSERT incr VALUES (NULL);\n SET v1 = v1 - 1;\n END WHILE;\nEND;;\nDELIMITER ;\n CALL dowhile();\nSELECT * FROM incr;\n Id\n1\n2\n3\n4\n5\n"
},
{
"answer_id": 187410,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 6,
"selected": false,
"text": "INSERT INTO\n myTable\n (\n nr\n )\nSELECT\n SEQ.SeqValue\nFROM\n(\nSELECT\n (HUNDREDS.SeqValue + TENS.SeqValue + ONES.SeqValue) SeqValue\nFROM\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 1 SeqValue\n UNION ALL\n SELECT 2 SeqValue\n UNION ALL\n SELECT 3 SeqValue\n UNION ALL\n SELECT 4 SeqValue\n UNION ALL\n SELECT 5 SeqValue\n UNION ALL\n SELECT 6 SeqValue\n UNION ALL\n SELECT 7 SeqValue\n UNION ALL\n SELECT 8 SeqValue\n UNION ALL\n SELECT 9 SeqValue\n ) ONES\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 10 SeqValue\n UNION ALL\n SELECT 20 SeqValue\n UNION ALL\n SELECT 30 SeqValue\n UNION ALL\n SELECT 40 SeqValue\n UNION ALL\n SELECT 50 SeqValue\n UNION ALL\n SELECT 60 SeqValue\n UNION ALL\n SELECT 70 SeqValue\n UNION ALL\n SELECT 80 SeqValue\n UNION ALL\n SELECT 90 SeqValue\n ) TENS\nCROSS JOIN\n (\n SELECT 0 SeqValue\n UNION ALL\n SELECT 100 SeqValue\n UNION ALL\n SELECT 200 SeqValue\n UNION ALL\n SELECT 300 SeqValue\n UNION ALL\n SELECT 400 SeqValue\n UNION ALL\n SELECT 500 SeqValue\n UNION ALL\n SELECT 600 SeqValue\n UNION ALL\n SELECT 700 SeqValue\n UNION ALL\n SELECT 800 SeqValue\n UNION ALL\n SELECT 900 SeqValue\n ) HUNDREDS\n) SEQ\n"
},
{
"answer_id": 8349837,
"author": "David Ehrmann",
"author_id": 1076480,
"author_profile": "https://Stackoverflow.com/users/1076480",
"pm_score": 6,
"selected": false,
"text": "SELECT\n (TWO_1.SeqValue + TWO_2.SeqValue + TWO_4.SeqValue + TWO_8.SeqValue + TWO_16.SeqValue) SeqValue\nFROM\n (SELECT 0 SeqValue UNION ALL SELECT 1 SeqValue) TWO_1\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 2 SeqValue) TWO_2\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 4 SeqValue) TWO_4\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 8 SeqValue) TWO_8\n CROSS JOIN (SELECT 0 SeqValue UNION ALL SELECT 16 SeqValue) TWO_16;\n"
},
{
"answer_id": 8497960,
"author": "JaredC",
"author_id": 339532,
"author_profile": "https://Stackoverflow.com/users/339532",
"pm_score": 5,
"selected": false,
"text": "INSERT INTO pivot100 \nSELECT @ROW := @ROW + 1 AS ROW\n FROM someOtherTable t\n join (SELECT @ROW := 0) t2\n LIMIT 100\n;\n"
},
{
"answer_id": 21286493,
"author": "Jakob Eriksson",
"author_id": 956415,
"author_profile": "https://Stackoverflow.com/users/956415",
"pm_score": 3,
"selected": false,
"text": "SELECT\n id % 12 + 1 as one_to_twelve\nFROM\n any_large_table\nGROUP BY\n one_to_twelve\n;\n"
},
{
"answer_id": 42613456,
"author": "Paul Spiegel",
"author_id": 5563083,
"author_profile": "https://Stackoverflow.com/users/5563083",
"pm_score": 1,
"selected": false,
"text": "information_schema.COLUMNS DROP TABLE IF EXISTS seq;\nCREATE TABLE seq (i MEDIUMINT AUTO_INCREMENT PRIMARY KEY)\n SELECT NULL AS i\n FROM information_schema.COLUMNS t1\n JOIN information_schema.COLUMNS t2\n JOIN information_schema.COLUMNS t3\n LIMIT 100000; -- <- set your limit here\n 0 AUTO_INCEMENT ALTER TABLE seq ALTER i DROP DEFAULT;\nALTER TABLE seq MODIFY i MEDIUMINT;\n 0 INSERT INTO seq (i) VALUES (0);\n INSERT INTO seq (i) SELECT -i FROM seq WHERE i <> 0;\n SELECT MIN(i), MAX(i), COUNT(*) FROM seq;\n"
},
{
"answer_id": 48798014,
"author": "Csongor Halmai",
"author_id": 3823826,
"author_profile": "https://Stackoverflow.com/users/3823826",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE _numbers (num int);\nINSERT _numbers VALUES (0), (1), (2), (3), ...;\n _numbers SELECT number, substr(name, num, 1) \n FROM users\n JOIN _numbers ON num < length(name)\n WHERE user_id = 1234\n ORDER BY num;\n SELECT n1.num * 10000 + n2.num\n FROM _numbers n1\n JOIN _numbers n2\n WHERE n1 < 100 \n ORDER BY n1.num * 10000 + n2.num; -- or just ORDER BY 1 meaning the first column\n"
},
{
"answer_id": 53125278,
"author": "elyalvarado",
"author_id": 3236163,
"author_profile": "https://Stackoverflow.com/users/3236163",
"pm_score": 2,
"selected": false,
"text": "WITH WITH DIGITS (N) AS (\n SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL\n SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL\n SELECT 8 UNION ALL SELECT 9)\nSELECT \n UNITS.N + TENS.N*10 + HUNDREDS.N*100 + THOUSANDS.N*1000 \nFROM \n DIGITS AS UNITS, DIGITS AS TENS, DIGITS AS HUNDREDS, DIGITS AS THOUSANDS;\n"
},
{
"answer_id": 60173743,
"author": "dannymac",
"author_id": 2009581,
"author_profile": "https://Stackoverflow.com/users/2009581",
"pm_score": 1,
"selected": false,
"text": "SELECT x1.N + x10.N*10 + x100.N*100 + x1000.N*1000\n FROM (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x1,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x10,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x100,\n (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) x1000\n WHERE x1.N + x10.N*10 + x100.N*100 + x1000.N*1000 <= @max;\n @max"
},
{
"answer_id": 63543993,
"author": "Justin Levene",
"author_id": 1938802,
"author_profile": "https://Stackoverflow.com/users/1938802",
"pm_score": 2,
"selected": false,
"text": "set @amount = 55; # How many numbers from zero you want to generate\n\nselect `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i` as `offset`\nfrom\n(select 0 `i` union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) `t0`,\n(select 0 `i` union select 10 union select 20 union select 30 union select 40 union select 50 union select 60 union select 70 union select 80 union select 90) `t1`,\n(select 0 `i` union select 100 union select 200 union select 300 union select 400 union select 500 union select 600 union select 700 union select 800 union select 900) `t2`,\n(select 0 `i` union select 1000 union select 2000 union select 3000 union select 4000 union select 5000 union select 6000 union select 7000 union select 8000 union select 9000) `t3`\nwhere `t3`.`i`<@amount\nand `t2`.`i`<@amount\nand `t1`.`i`<@amount\nand `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i`<@amount;\n"
},
{
"answer_id": 66226974,
"author": "Liam",
"author_id": 3714181,
"author_profile": "https://Stackoverflow.com/users/3714181",
"pm_score": 1,
"selected": false,
"text": "set @noRows = 100;\nSELECT tt.rowid - 1 AS value\n FROM JSON_TABLE(CONCAT('[{}', REPEAT(',{}', @noRows - 1), ']'),\n \"$[*]\" COLUMNS(rowid FOR ORDINALITY)\n ) AS tt; \n"
},
{
"answer_id": 67980354,
"author": "Naresh",
"author_id": 13535919,
"author_profile": "https://Stackoverflow.com/users/13535919",
"pm_score": 0,
"selected": false,
"text": " with recursive rnums as (\n select 1 as n\n union all\n select n+1 as n from rnums\n where n <10\n )\n select * from rnums\n ;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14635/"
] |
186,789
|
<p>What security best-practices would you strongly recommend in maintaining a Linux server? <br />(i.e. bring up a firewall, disable unnecessary services, beware of suid executables, and so on.)</p>
<p>Also: is there a definitive reference on Selinux?</p>
<p>EDIT: Yes, I'm planning to put the machine on the Internet, with at least openvpn, ssh and apache (at the moment, without dynamic content), and to provide shell access to some people.</p>
|
[
{
"answer_id": 58243905,
"author": "RtmY",
"author_id": 1103953,
"author_profile": "https://Stackoverflow.com/users/1103953",
"pm_score": 0,
"selected": false,
"text": "/home /tmp /var nosuid setuid auditd"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
186,798
|
<p>The log levels WARN, ERROR and FATAL are pretty clear. But when is something DEBUG, and when INFO? </p>
<p>I've seen some projects that are annoyingly verbose on the INFO level, but I've also seen code that favors the DEBUG level too much. In both cases, useful information is hidden in the noise.</p>
<p>What are the criteria for determining log levels? </p>
|
[
{
"answer_id": 186826,
"author": "slashnick",
"author_id": 21030,
"author_profile": "https://Stackoverflow.com/users/21030",
"pm_score": 2,
"selected": false,
"text": "debug info info debug"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6400/"
] |
186,799
|
<p>When using JDBC, I often come across constructs like </p>
<pre><code>ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
// Some other actions
}
</code></pre>
<p>I asked myself (and authors of code too) why not to use labels for retrieving column values: </p>
<pre><code>int id = rs.getInt("CUSTOMER_ID");
</code></pre>
<p>The best explanation I've heard is something concerning performance. But actually, does it make processing extremely fast? I don't believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.<br>
So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)? </p>
|
[
{
"answer_id": 186821,
"author": "Sietse",
"author_id": 6400,
"author_profile": "https://Stackoverflow.com/users/6400",
"pm_score": 2,
"selected": false,
"text": "String int int String ints"
},
{
"answer_id": 187425,
"author": "Martin Klinke",
"author_id": 1793,
"author_profile": "https://Stackoverflow.com/users/1793",
"pm_score": 7,
"selected": true,
"text": "int i = 1; \ncustomerId = resultSet.getInt(i++); \ncustomerName = resultSet.getString(i++); \ncustomerAddress = resultSet.getString(i++);\n customerId = resultSet.getInt(\"customer_id\"); \ncustomerName = resultSet.getString(\"customer_name\"); \ncustomerAddress = resultSet.getString(\"customer_address\");\n"
},
{
"answer_id": 2197441,
"author": "Kevin Brock",
"author_id": 219394,
"author_profile": "https://Stackoverflow.com/users/219394",
"pm_score": 3,
"selected": false,
"text": "ResultSet"
},
{
"answer_id": 74154693,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "CREATE TABLE author (\n id BIGINT PRIMARY KEY,\n first_name TEXT, ...\n);\n\nCREATE TABLE book (\n id BIGINT PRIMARY KEY,\n author_id BIGINT REFERENCES author,\n title TEXT, ...\n);\n SELECT *\nFROM author\nJOIN book ON author.id = book.author_id\n ID"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11732/"
] |
186,800
|
<p>I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can't find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:</p>
<pre><code><defaultProxy useDefaultCredentials="false">
<proxy usesystemdefault="true" proxyaddress="<proxy address>" bypassonlocal="true" />
</defaultProxy>
</code></pre>
<p>I know you can do this via code, but the software the website is running is a closed-source CMS so I can't do this.</p>
<p>Is there any way to do this? MSDN isn't helping me much..</p>
|
[
{
"answer_id": 194414,
"author": "Jérôme Laban",
"author_id": 26346,
"author_profile": "https://Stackoverflow.com/users/26346",
"pm_score": 8,
"selected": true,
"text": "namespace SomeNameSpace\n{\n public class MyProxy : IWebProxy\n {\n public ICredentials Credentials\n {\n get { return new NetworkCredential(\"user\", \"password\"); }\n //or get { return new NetworkCredential(\"user\", \"password\",\"domain\"); }\n set { }\n }\n\n public Uri GetProxy(Uri destination)\n {\n return new Uri(\"http://my.proxy:8080\");\n }\n\n public bool IsBypassed(Uri host)\n {\n return false;\n }\n }\n}\n <defaultProxy enabled=\"true\" useDefaultCredentials=\"false\">\n <module type = \"SomeNameSpace.MyProxy, SomeAssembly\" />\n</defaultProxy>\n"
},
{
"answer_id": 875700,
"author": "Scott Ferguson",
"author_id": 5007,
"author_profile": "https://Stackoverflow.com/users/5007",
"pm_score": 4,
"selected": false,
"text": " <system.net>\n <defaultProxy useDefaultCredentials=\"true\">\n <proxy proxyaddress=\"proxyAddress\" usesystemdefault=\"True\"/>\n </defaultProxy>\n </system.net>\n"
},
{
"answer_id": 31082422,
"author": "Silas Humberto Souza",
"author_id": 3964740,
"author_profile": "https://Stackoverflow.com/users/3964740",
"pm_score": 3,
"selected": false,
"text": "<system.net> \n<defaultProxy enabled=\"true\" useDefaultCredentials=\"true\"> \n<proxy usesystemdefault=\"True\" /> \n</defaultProxy> \n</system.net>\n"
},
{
"answer_id": 72569636,
"author": "Malik",
"author_id": 5891307,
"author_profile": "https://Stackoverflow.com/users/5891307",
"pm_score": 0,
"selected": false,
"text": "public class MyProxy : IWebProxy\n{\n public ICredentials Credentials\n {\n //get { return new NetworkCredential(\"user\", \"password\"); }\n get { return new NetworkCredential(\"user\", \"password\",\"domain\"); }\n set { }\n }\n\n public Uri GetProxy(Uri destination)\n {\n return new Uri(\"http://my.proxy:8080\");\n }\n\n public bool IsBypassed(Uri host)\n {\n return false;\n }\n}\n services.AddHttpClient(\"Lynx\", client =>\n {\n client.BaseAddress = new Uri(Configuration.GetSection(\"LynxUrl\").Value);\n }).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new MyProxy()});\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5793/"
] |
186,802
|
<p>I have named_scope which is reused in multiple ActiveRecord models.
For example:</p>
<pre><code> named_scope :limit, lambda {|limit| {:limit => limit}}
</code></pre>
<p>What is the best practice to extract this code to be shared across models.
Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?</p>
|
[
{
"answer_id": 187097,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 4,
"selected": false,
"text": "module CommonScopes\n def self.included(base)\n base.class_eval do\n named_scope :limit, lambda {|limit| {:limit => limit}}\n end\n end\nend\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18715/"
] |
186,822
|
<p>How do I invoke a console application from my .NET application and capture all the output generated in the console? </p>
<p>(Remember, I don't want to save the information first in a file and then relist as I would love to receive it as live.)</p>
|
[
{
"answer_id": 186833,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 8,
"selected": true,
"text": "Process compiler = new Process();\ncompiler.StartInfo.FileName = \"csc.exe\";\ncompiler.StartInfo.Arguments = \"/r:System.dll /out:sample.exe stdstr.cs\";\ncompiler.StartInfo.UseShellExecute = false;\ncompiler.StartInfo.RedirectStandardOutput = true;\ncompiler.Start(); \n\nConsole.WriteLine(compiler.StandardOutput.ReadToEnd());\n\ncompiler.WaitForExit();\n"
},
{
"answer_id": 2850784,
"author": "livetogogo",
"author_id": 343246,
"author_profile": "https://Stackoverflow.com/users/343246",
"pm_score": 1,
"selected": false,
"text": "Process p = new Process(); // Create new object\np.StartInfo.UseShellExecute = false; // Do not use shell\np.StartInfo.RedirectStandardOutput = true; // Redirect output\np.StartInfo.FileName = \"c:\\\\python26\\\\python.exe\"; // Path of our Python compiler\np.StartInfo.Arguments = \"c:\\\\python26\\\\Hello_C_Python.py\"; // Path of the .py to be executed\n"
},
{
"answer_id": 15725442,
"author": "SlavaGu",
"author_id": 319170,
"author_profile": "https://Stackoverflow.com/users/319170",
"pm_score": 3,
"selected": false,
"text": "// Run simplest shell command and return its output.\npublic static string GetWindowsVersion()\n{\n return ConsoleApp.Run(\"cmd\", \"/c ver\").Output.Trim();\n}\n // Run ping.exe asynchronously and return roundtrip times back to the caller in a callback\npublic static void PingUrl(string url, Action<string> replyHandler)\n{\n var regex = new Regex(\"(time=|Average = )(?<time>.*?ms)\", RegexOptions.Compiled);\n var app = new ConsoleApp(\"ping\", url);\n app.ConsoleOutput += (o, args) =>\n {\n var match = regex.Match(args.Line);\n if (match.Success)\n {\n var roundtripTime = match.Groups[\"time\"].Value;\n replyHandler(roundtripTime);\n }\n };\n app.Run();\n}\n"
},
{
"answer_id": 32487747,
"author": "Sergei Zinovyev",
"author_id": 5145258,
"author_profile": "https://Stackoverflow.com/users/5145258",
"pm_score": 1,
"selected": false,
"text": "process.StartInfo.**CreateNoWindow** = true; timeout private static void CaptureConsoleAppOutput(string exeName, string arguments, int timeoutMilliseconds, out int exitCode, out string output)\n{\n using (Process process = new Process())\n {\n process.StartInfo.FileName = exeName;\n process.StartInfo.Arguments = arguments;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.CreateNoWindow = true;\n process.Start();\n\n output = process.StandardOutput.ReadToEnd();\n\n bool exited = process.WaitForExit(timeoutMilliseconds);\n if (exited)\n {\n exitCode = process.ExitCode;\n }\n else\n {\n exitCode = -1;\n }\n }\n}\n"
},
{
"answer_id": 39624153,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 6,
"selected": false,
"text": "ReadToEnd() BeginxxxReadLine() Start() using System.Diagnostics;\n\nProcess process = new Process();\n\nvoid LaunchProcess()\n{\n process.EnableRaisingEvents = true;\n process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);\n process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);\n process.Exited += new System.EventHandler(process_Exited);\n\n process.StartInfo.FileName = \"some.exe\";\n process.StartInfo.Arguments = \"param1 param2\";\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.RedirectStandardError = true;\n process.StartInfo.RedirectStandardOutput = true;\n\n process.Start();\n process.BeginErrorReadLine();\n process.BeginOutputReadLine(); \n\n //below line is optional if we want a blocking call\n //process.WaitForExit();\n}\n\nvoid process_Exited(object sender, EventArgs e)\n{\n Console.WriteLine(string.Format(\"process exited with code {0}\\n\", process.ExitCode.ToString()));\n}\n\nvoid process_ErrorDataReceived(object sender, DataReceivedEventArgs e)\n{\n Console.WriteLine(e.Data + \"\\n\");\n}\n\nvoid process_OutputDataReceived(object sender, DataReceivedEventArgs e)\n{\n Console.WriteLine(e.Data + \"\\n\");\n}\n"
},
{
"answer_id": 59373604,
"author": "3dGrabber",
"author_id": 141397,
"author_profile": "https://Stackoverflow.com/users/141397",
"pm_score": 2,
"selected": false,
"text": "onStdOut onStdErr public static Int32 RunProcess(String path,\n String args,\n Action<String> onStdOut = null,\n Action<String> onStdErr = null)\n {\n var readStdOut = onStdOut != null;\n var readStdErr = onStdErr != null;\n\n var process = new Process\n {\n StartInfo =\n {\n FileName = path,\n Arguments = args,\n CreateNoWindow = true,\n UseShellExecute = false,\n RedirectStandardOutput = readStdOut,\n RedirectStandardError = readStdErr,\n }\n };\n\n process.Start();\n\n if (readStdOut) Task.Run(() => ReadStream(process.StandardOutput, onStdOut));\n if (readStdErr) Task.Run(() => ReadStream(process.StandardError, onStdErr));\n\n process.WaitForExit();\n\n return process.ExitCode;\n }\n\n private static void ReadStream(TextReader textReader, Action<String> callback)\n {\n while (true)\n {\n var line = textReader.ReadLine();\n if (line == null)\n break;\n\n callback(line);\n }\n }\n executable args RunProcess(\n executable,\n args,\n s => { Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(s); },\n s => { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(s); } \n);\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17519/"
] |
186,827
|
<p>I need to send email through an (external) SMTP server from Java however this server will only accept CRAM-MD5 authentication, which is not supported by JavaMail.</p>
<p>What would be a good way to get these emails to send? (It must be in Java.)</p>
|
[
{
"answer_id": 186906,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "mail.imap.sasl.enable true mail.smtp.sasl.enable"
},
{
"answer_id": 187254,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "C: AUTH CRAM-MD5\nS: 334 BASE64(NONCE)\nC: BASE64(USERNAME, \" \", MD5((SECRET XOR opad),MD5((SECRET XOR ipad), NONCE)))\nS: 235 Authentication succeeded\n C: AUTH CRAM-MD5\nS: 334 PDQ1MDMuMTIyMzU1Nzg2MkBtYWlsMDEuZXhhbXBsZS5jb20+\nC: dXNlckBleGFtcGxlLmNvbSA4YjdjODA5YzQ0NTNjZTVhYTA5N2VhNWM4OTlmNGY4Nw==\nS: 235 Authentication succeeded\n S: 334 BASE64(\"<4503.1223557862@mail01.example.com>\")\nC: BASE64(\"user@example.com 8b7c809c4453ce5aa097ea5c899f4f87\")\n S: 334 BASE64(\"<4503.1223557862@mail01.example.com>\")\nC: BASE64(\"user@example.com \", MD5((\"password\" XOR opad),MD5((\"password\" XOR ipad), \"<4503.1223557862@mail01.example.com>\")))\n"
},
{
"answer_id": 403602,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "import java.security.*;\n\nclass CRAMMD5Test\n{\npublic static void main(String[] args) throws Exception\n{\n // This represents the BASE64 encoded timestamp sent by the POP server\n String dataString = Base64Decoder.decode(\"PDAwMDAuMDAwMDAwMDAwMEBteDEuc2VydmVyLmNvbT4=\");\n byte[] data = dataString.getBytes();\n\n // The password to access the account\n byte[] key = new String(\"password\").getBytes();\n\n // The address of the e-mail account\n String user = \"client@server.com\";\n\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\n md5.reset();\n\n if (key.length > 64)\n key = md5.digest(key);\n\n byte[] k_ipad = new byte[64];\n byte[] k_opad = new byte[64];\n\n System.arraycopy(key, 0, k_ipad, 0, key.length);\n System.arraycopy(key, 0, k_opad, 0, key.length);\n\n for (int i=0; i<64; i++)\n {\n k_ipad[i] ^= 0x36;\n k_opad[i] ^= 0x5c;\n }\n\n byte[] i_temp = new byte[k_ipad.length + data.length];\n\n System.arraycopy(k_ipad, 0, i_temp, 0, k_ipad.length);\n System.arraycopy(data, 0, i_temp, k_ipad.length, data.length);\n\n i_temp = md5.digest(i_temp);\n\n byte[] o_temp = new byte[k_opad.length + i_temp.length];\n\n System.arraycopy(k_opad, 0, o_temp, 0, k_opad.length);\n System.arraycopy(i_temp, 0, o_temp, k_opad.length, i_temp.length);\n\n byte[] result = md5.digest(o_temp);\n StringBuffer hexString = new StringBuffer();\n\n for (int i=0;i < result.length; i++) {\n hexString.append(Integer.toHexString((result[i] >>> 4) & 0x0F));\n hexString.append(Integer.toHexString(0x0F & result[i]));\n }\n\n\n System.out.println(Base64Encoder.encode(user + \" \" + hexString.toString()));\n }\n}\n"
},
{
"answer_id": 509203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "for (int i=0; i<result.length; i++)\n hexString.append(Integer.toHexString(0xFF & result[i]));\n for (int i=0;i < result.length; i++) {\n hexString.append(Integer.toHexString((result[i] >>> 4) & 0x0F));\n hexString.append(Integer.toHexString(0x0F & result[i]));\n}\n"
},
{
"answer_id": 12110971,
"author": "Alexey Ogarkov",
"author_id": 57588,
"author_profile": "https://Stackoverflow.com/users/57588",
"pm_score": 4,
"selected": true,
"text": "props.put(\"mail.smtp.auth.mechanisms\", \"CRAM-MD5\")\n"
},
{
"answer_id": 12155965,
"author": "Pumuckline",
"author_id": 987281,
"author_profile": "https://Stackoverflow.com/users/987281",
"pm_score": 3,
"selected": false,
"text": "props.put(\"mail.smtp.sasl.enable\", \"true\");"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15355/"
] |
186,829
|
<p>Conventional IPv4 dotted quad notation separates the address from the port with a colon, as in this example of a webserver on the loopback interface:</p>
<pre><code>127.0.0.1:80
</code></pre>
<p>but with IPv6 notation the address itself can contain colons. For example, this is the short form of the loopback address:</p>
<pre><code>::1
</code></pre>
<p>How are ports (or their functional equivalent) expressed in a textual representation of an IPv6 address/port endpoint? </p>
|
[
{
"answer_id": 186848,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 9,
"selected": true,
"text": "[] http://[1fff:0:a88:85a3::ac1f]:8001/index.html"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1715673/"
] |
186,840
|
<p>My company runs a webmail service, and we were trying to diagnose a problem with Word downloads not opening automatically - the same *.doc file download from Yahoo Mail would open, but one from ours would not.</p>
<p>In the course of investigating the headers we saw this coming from Yahoo:</p>
<pre><code>content-disposition attachment; filename*="utf-8''word document.doc";
</code></pre>
<p>Whereas our headers were like this:</p>
<pre><code>content-disposition attachment; filename="word document.doc";
</code></pre>
<p>What exactly is Yahoo doing with the additional asterisk and utf-8'' designation?</p>
|
[
{
"answer_id": 186886,
"author": "Alphager",
"author_id": 21684,
"author_profile": "https://Stackoverflow.com/users/21684",
"pm_score": 0,
"selected": false,
"text": " disposition := \"Content-Disposition\" \":\"\n disposition-type\n *(\";\" disposition-parm)\n\n disposition-type := \"inline\"\n / \"attachment\"\n / extension-token\n ; values are not case-sensitive\n\n disposition-parm := filename-parm\n / creation-date-parm\n / modification-date-parm\n / read-date-parm\n / size-parm\n / parameter\n\n filename-parm := \"filename\" \"=\" value\n\n creation-date-parm := \"creation-date\" \"=\" quoted-date-time\n\n modification-date-parm := \"modification-date\" \"=\" quoted-date-time\n\n read-date-parm := \"read-date\" \"=\" quoted-date-time\n\n size-parm := \"size\" \"=\" 1*DIGIT\n\n quoted-date-time := quoted-string\n ; contents MUST be an RFC 822 `date-time'\n ; numeric timezones (+HHMM or -HHMM) MUST be used\n"
},
{
"answer_id": 187331,
"author": "z7q2",
"author_id": 25487,
"author_profile": "https://Stackoverflow.com/users/25487",
"pm_score": 2,
"selected": false,
"text": " Content-Type: application/x-stuff;\n title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25487/"
] |
186,854
|
<p>I can hookup to <code>AppDomain.CurrentDomain.UnhandledException</code> to log exceptions from background threads, but how do I prevent them terminating the runtime?</p>
|
[
{
"answer_id": 186879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<configuration>\n <runtime>\n <!-- the following setting prevents the host from closing when an unhandled exception is thrown -->\n <legacyUnhandledExceptionPolicy enabled=\"1\" />\n </runtime>\n</configuration>\n"
},
{
"answer_id": 186896,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "delegate void ExceptionCallback(Exception ex);\n\nvoid MyExceptionCallback(Exception ex)\n{\n throw ex; // Handle/re-throw if necessary\n}\n\nvoid BackgroundThreadProc(Object obj)\n{\n try \n { \n throw new Exception(); \n }\n catch (Exception ex)\n { \n this.BeginInvoke(new ExceptionCallback(MyExceptionCallback), ex); \n }\n}\n\nprivate void Test()\n{\n ThreadPool.QueueUserWorkItem(new WaitCallback(BackgroundThreadProc));\n}\n"
},
{
"answer_id": 1056573,
"author": "bohdan_trotsenko",
"author_id": 58768,
"author_profile": "https://Stackoverflow.com/users/58768",
"pm_score": 3,
"selected": false,
"text": "class Program\n{\n void Run()\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n\n Console.WriteLine(\"Press enter to exit.\");\n\n do\n {\n (new Thread(delegate()\n {\n throw new ArgumentException(\"ha-ha\");\n })).Start();\n\n } while (Console.ReadLine().Trim().ToLowerInvariant() == \"x\");\n\n\n Console.WriteLine(\"last good-bye\");\n }\n\n int r = 0;\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n Interlocked.Increment(ref r);\n Console.WriteLine(\"handled. {0}\", r);\n Console.WriteLine(\"Terminating \" + e.IsTerminating.ToString());\n\n Thread.CurrentThread.IsBackground = true;\n Thread.CurrentThread.Name = \"Dead thread\"; \n\n while (true)\n Thread.Sleep(TimeSpan.FromHours(1));\n //Process.GetCurrentProcess().Kill();\n }\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"...\");\n (new Program()).Run();\n }\n}\n Process.GetCurrentProcess().Kill();"
},
{
"answer_id": 47960142,
"author": "Evgeny Gorbovoy",
"author_id": 2362847,
"author_profile": "https://Stackoverflow.com/users/2362847",
"pm_score": 2,
"selected": false,
"text": " AppDomain.CurrentDomain.UnhandledException += (sender, e2) =>\n {\n Thread.CurrentThread.Join();\n };\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5978/"
] |
186,857
|
<p>I have a string that looks like this:</p>
<pre><code>"Name1=Value1;Name2=Value2;Name3=Value3"
</code></pre>
<p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p>
<pre><code>dict = {
"Name1": "Value1",
"Name2": "Value2",
"Name3": "Value3"
}
</code></pre>
<p>I have looked through the modules available but can't seem to find anything that matches.</p>
<hr>
<p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p>
<p>I'll do it myself then.</p>
|
[
{
"answer_id": 186873,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": true,
"text": "s= \"Name1=Value1;Name2=Value2;Name3=Value3\"\ndict(item.split(\"=\") for item in s.split(\";\"))\n >>> s = \"Name1='Value=2';Name2=Value2;Name3=Value3\"\n\n>>> dict(csv.reader([item], delimiter='=', quotechar=\"'\").next() \n for item in csv.reader([s], delimiter=';', quotechar=\"'\").next())\n\n{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}\n"
},
{
"answer_id": 5149981,
"author": "Kyle Gibson",
"author_id": 513197,
"author_profile": "https://Stackoverflow.com/users/513197",
"pm_score": 3,
"selected": false,
"text": ">>> import urlparse\n>>> urlparse.parse_qs(\"Name1=Value1;Name2=Value2;Name3=Value3\")\n{'Name2': ['Value2'], 'Name3': ['Value3'], 'Name1': ['Value1']}\n"
},
{
"answer_id": 15649648,
"author": "easytiger",
"author_id": 316957,
"author_profile": "https://Stackoverflow.com/users/316957",
"pm_score": -1,
"selected": false,
"text": "easytiger $ cat test.out test.py | sed 's/^/ /'\np_easytiger_quoting:1.84563302994\n{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'}\np_brian:2.30507516861\n{'Name2': 'Value2', 'Name3': \"'Value3'\", 'Name1': 'Value1'}\np_kyle:7.22536420822\n{'Name2': ['Value2'], 'Name3': [\"'Value3'\"], 'Name1': ['Value1']}\nimport timeit\nimport urlparse\n\ns = \"Name1=Value1;Name2=Value2;Name3='Value3'\"\n\ndef p_easytiger_quoting(s):\n d = {}\n s = s.replace(\"'\", \"\")\n for x in s.split(';'):\n k, v = x.split('=')\n d[k] = v\n return d\n\n\ndef p_brian(s):\n return dict(item.split(\"=\") for item in s.split(\";\"))\n\ndef p_kyle(s):\n return urlparse.parse_qs(s)\n\n\n\nprint \"p_easytiger_quoting:\" + str(timeit.timeit(lambda: p_easytiger_quoting(s)))\nprint p_easytiger_quoting(s)\n\n\nprint \"p_brian:\" + str(timeit.timeit(lambda: p_brian(s)))\nprint p_brian(s)\n\nprint \"p_kyle:\" + str(timeit.timeit(lambda: p_kyle(s)))\nprint p_kyle(s)\n"
},
{
"answer_id": 16189504,
"author": "Rabarberski",
"author_id": 50899,
"author_profile": "https://Stackoverflow.com/users/50899",
"pm_score": -1,
"selected": false,
"text": "dict() eval() >>> s= \"Name1=1;Name2=2;Name3='string'\"\n>>> print eval('dict('+s.replace(';',',')+')')\n{'Name2: 2, 'Name3': 'string', 'Name1': 1}\n dict() dict(Name1=1, Name2=2,Name3='string')"
},
{
"answer_id": 27619606,
"author": "vijay",
"author_id": 601310,
"author_profile": "https://Stackoverflow.com/users/601310",
"pm_score": 1,
"selected": false,
"text": "\",\".join([\"%s=%s\" % x for x in d.items()]) >>d = {'a':1, 'b':2}\n>>','.join(['%s=%s'%x for x in d.items()])\n>>'a=1,b=2'\n"
},
{
"answer_id": 54984224,
"author": "D. Om",
"author_id": 11148339,
"author_profile": "https://Stackoverflow.com/users/11148339",
"pm_score": 2,
"selected": false,
"text": "s1 = \"Name1=Value1;Name2=Value2;Name3=Value3\"\n\ndict(map(lambda x: x.split('='), s1.split(';')))\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
186,867
|
<p>I need to stream a file to the Response for saving on the end user's machine. The file is plain text, so what content type can I use to prevent the text being displayed in the browser?</p>
|
[
{
"answer_id": 186871,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "Content-Disposition: attachment"
},
{
"answer_id": 186872,
"author": "Andrew Moore",
"author_id": 26210,
"author_profile": "https://Stackoverflow.com/users/26210",
"pm_score": 5,
"selected": false,
"text": "Content-type: application/octet-stream\nContent-Disposition: attachment; filename=\"myfile.txt\"\n application/octet-stream"
},
{
"answer_id": 186898,
"author": "Mun",
"author_id": 775,
"author_profile": "https://Stackoverflow.com/users/775",
"pm_score": 6,
"selected": true,
"text": "Content-Type: application/octet-stream\nContent-Disposition: attachment;filename=\\\"My Text File.txt\\\"\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741/"
] |
186,876
|
<p>The following works in Firefox, but breaks in IE7 & 8:</p>
<pre><code>$("#my-first-div, #my-second-div").hide();
</code></pre>
<p>so I have to do this:</p>
<pre><code>$("#my-first-div").hide();
$("#my-second-div").hide();
</code></pre>
<p>Is this normal?</p>
<p>EDIT: ok, my actual real-life code is this:</p>
<pre><code>$("#charges-gsm,#charges-gsm-faq,#charges-gsm-prices").html(html);
</code></pre>
<p>and my error is this</p>
<pre><code>( IE8): Message: 'nodeName' is null or not an object
Line: 19 Char: 150 Code: 0
URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js
</code></pre>
|
[
{
"answer_id": 187126,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "Message: 'nodeName' is null or not an object\n Line: 19 Char: 150 Code: 0\n URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\n nodeName:function(elem,name){\n return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();\n}\n jQuery.extend() <html>\n <head>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"#charges-gsm,#charges-gsm-faq,#charges-gsm-prices\").html(\"xx\")\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <a href=\"http://jquery.com/\">jQuery</a>\n <hr>\n <div id=\"charges-gsm\">CHARGES-GSM</div>\n <div id=\"charges-gsm-faq\">CHARGES-GSM-FAQ</div>\n <div id=\"charges-gsm-prices\">CHARGES-GSM-PRICES</div>\n </body>\n</html>\n"
},
{
"answer_id": 316942,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<div id=\"foo\">\n <div id=\"bar\"> \n <div id=\"baz\">\n </div>\n</div>\n $(\"#foo,#bar,#baz\").html(\"xx\"); \n try { \n $(\"#foo,#bar,#baz\").html(\"xx\"); \n}\ncatch( e ) \n{\n /* DO NOTHING D: */ \n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
186,883
|
<p>When deploying a ready to use erlang application I <strong>don't</strong> want the user to </p>
<ul>
<li>Find the right erl release on the
internet.</li>
<li>Install the erl vm</li>
<li>unzip and decide a location for the beam files (with the application)</li>
<li>read a readme</li>
<li>modify anything that even looks like a config file</li>
</ul>
<p>I have a couple of ideas of what could be a way but I would like to get some input.</p>
|
[
{
"answer_id": 187126,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "Message: 'nodeName' is null or not an object\n Line: 19 Char: 150 Code: 0\n URI: http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\n nodeName:function(elem,name){\n return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();\n}\n jQuery.extend() <html>\n <head>\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"#charges-gsm,#charges-gsm-faq,#charges-gsm-prices\").html(\"xx\")\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <a href=\"http://jquery.com/\">jQuery</a>\n <hr>\n <div id=\"charges-gsm\">CHARGES-GSM</div>\n <div id=\"charges-gsm-faq\">CHARGES-GSM-FAQ</div>\n <div id=\"charges-gsm-prices\">CHARGES-GSM-PRICES</div>\n </body>\n</html>\n"
},
{
"answer_id": 316942,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 0,
"selected": false,
"text": "<div id=\"foo\">\n <div id=\"bar\"> \n <div id=\"baz\">\n </div>\n</div>\n $(\"#foo,#bar,#baz\").html(\"xx\"); \n try { \n $(\"#foo,#bar,#baz\").html(\"xx\"); \n}\ncatch( e ) \n{\n /* DO NOTHING D: */ \n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15638/"
] |
186,891
|
<p>If I am passing an object to a method, why should I use the ref keyword? Isn't this the default behaviour anyway?</p>
<p>For example:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
TestRef t = new TestRef();
t.Something = "Foo";
DoSomething(t);
Console.WriteLine(t.Something);
}
static public void DoSomething(TestRef t)
{
t.Something = "Bar";
}
}
public class TestRef
{
public string Something { get; set; }
}
</code></pre>
<p>The output is "Bar" which means that the object was passed as a reference.</p>
|
[
{
"answer_id": 186904,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "ref static public void DoSomething(ref TestRef t)\n{\n t = new TestRef();\n}\n"
},
{
"answer_id": 186907,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 9,
"selected": true,
"text": "ref TestRef t = new TestRef();\nt.Something = \"Foo\";\nDoSomething(ref t);\n\nvoid DoSomething(ref TestRef t)\n{\n t = new TestRef();\n t.Something = \"Not just a changed t, but a completely different TestRef object\";\n}\n t new TestRef string string ref ref ref ref int int x = 1;\nChange(ref x);\nDebug.Assert(x == 5);\nWillNotChange(x);\nDebug.Assert(x == 5); // Note: x doesn't become 10\n\nvoid Change(ref int x)\n{\n x = 5;\n}\n\nvoid WillNotChange(int x)\n{\n x = 10;\n}\n"
},
{
"answer_id": 186911,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 2,
"selected": false,
"text": "ref out ref"
},
{
"answer_id": 186949,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 6,
"selected": false,
"text": "public void Method1(object obj) { \n obj = new Object(); \n}\n\npublic void Method2(object obj) { \n obj = _privateObject; \n}\n using System;\n\n class Program\n {\n static void Main(string[] args)\n {\n TestRef t = new TestRef();\n t.Something = \"Foo\";\n\n DoSomething(t);\n Console.WriteLine(t.Something);\n\n }\n\n static public void DoSomething(TestRef t)\n {\n t = new TestRef();\n t.Something = \"Bar\";\n }\n }\n\n\n\n public class TestRef\n {\n private string s;\n public string Something \n { \n get {return s;} \n set { s = value; }\n }\n }\n"
},
{
"answer_id": 30156549,
"author": "guneysus",
"author_id": 1766716,
"author_profile": "https://Stackoverflow.com/users/1766716",
"pm_score": 2,
"selected": false,
"text": "ref"
},
{
"answer_id": 31480539,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "foo List<T> foo = new List<int> {1,5,7,9}; foo foo.Length foo.Length foo ref foo.Length foo foo ref foo foo foo"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93743/"
] |
186,894
|
<p>I am looking for the best way to test if a website is alive from a C# application.</p>
<h3>Background</h3>
<p>My application consists of a <em>Winforms UI</em>, a backend <em>WCF service</em> and a <em>website</em> to publish content to the UI and other consumers. To prevent the situation where the UI starts up and fails to work properly because of a missing WCF service or website being down I have added an app startup check to ensure that all everything is alive.</p>
<p>The application is being written in C#, .NET 3.5, Visual Studio 2008</p>
<h3>Current Solution</h3>
<p>Currently I am making a web request to a test page on the website that will inturn test the web site and then display a result.</p>
<pre><code>WebRequest request = WebRequest.Create("http://localhost/myContentSite/test.aspx");
WebResponse response = request.GetResponse();
</code></pre>
<p>I am assuming that if there are no exceptions thown during this call then all is well and the UI can start.</p>
<h3>Question</h3>
<p>Is this the simplest, right way or is there some other sneaky call that I don't know about in C# or a better way to do it.</p>
|
[
{
"answer_id": 186931,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 8,
"selected": true,
"text": "HttpWebResponse response = (HttpWebResponse)request.GetResponse();\nif (response == null || response.StatusCode != HttpStatusCode.OK)\n HttpClient client = new HttpClient();\nvar checkingResponse = await client.GetAsync(url);\nif (!checkingResponse.IsSuccessStatusCode)\n{\n return false;\n}\n"
},
{
"answer_id": 186951,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "public override bool WebSiteIsAvailable(string Url)\n{\n string Message = string.Empty;\n HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url);\n\n // Set the credentials to the current user account\n request.Credentials = System.Net.CredentialCache.DefaultCredentials;\n request.Method = \"GET\";\n\n try\n {\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n // Do nothing; we're only testing to see if we can get the response\n }\n }\n catch (WebException ex)\n {\n Message += ((Message.Length > 0) ? \"\\n\" : \"\") + ex.Message;\n }\n\n return (Message.Length == 0);\n}\n"
},
{
"answer_id": 3939689,
"author": "Maxymus",
"author_id": 447358,
"author_profile": "https://Stackoverflow.com/users/447358",
"pm_score": 4,
"selected": false,
"text": "HttpWebRequest req = (HttpWebRequest)WebRequest.Create(sURL);\nHttpWebResponse response = (HttpWebResponse)req.GetResponse();\n// your code here\nresponse.Close();\n"
},
{
"answer_id": 26860825,
"author": "NoloMokgosi",
"author_id": 2787567,
"author_profile": "https://Stackoverflow.com/users/2787567",
"pm_score": -1,
"selected": false,
"text": "var ping = new System.Net.NetworkInformation.Ping();\n\nvar result = ping.Send(\"https://www.stackoverflow.com\");\n\nif (result.Status != System.Net.NetworkInformation.IPStatus.Success)\n return;\n"
},
{
"answer_id": 48791943,
"author": "Yanga",
"author_id": 3173214,
"author_profile": "https://Stackoverflow.com/users/3173214",
"pm_score": 3,
"selected": false,
"text": "HttpClient Client = new HttpClient();\nvar result = await Client.GetAsync(\"https://stackoverflow.com\");\nint StatusCode = (int)result.StatusCode;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/231/"
] |
186,895
|
<p>Is there a way in Visual Studio (a hotkey) to automatically import a type (or choosing between known namespaces) like the <kbd>Ctrl</kbd> + <kbd>O</kbd> in Eclipse?</p>
|
[
{
"answer_id": 186920,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 6,
"selected": false,
"text": "using using"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/68336/"
] |
186,916
|
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p>
<p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p>
<p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (& <> and so on...).</p>
<p>Do you have any idea of what could be a good way of accomplishing this?</p>
<p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
|
[
{
"answer_id": 187011,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "[\n(\"file .* does not exist\", \"file not found\"),\n(\"user .* not authorized\", \"authorization error\")\n]\n f = open(\"messages.py\")\nmessages = eval(f.read()) # caution: you must be sure of what's in that file\nf.close()\nmessages = [(re.compile(r), m) for (r,m) in messages]\n"
},
{
"answer_id": 187045,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 5,
"selected": false,
"text": "config.py config = {\n 'name': 'hello',\n 'see?': 'world'\n}\n from config import config\nconfig['name']\nconfig['see?']\n"
},
{
"answer_id": 187135,
"author": "davidavr",
"author_id": 8247,
"author_profile": "https://Stackoverflow.com/users/8247",
"pm_score": 2,
"selected": false,
"text": "patterns = {\n 'file .* does not exist': 'file not found',\n 'user .* not found': 'authorization error',\n}\n import config\n\nfor pattern in config.patterns:\n if re.search(pattern, log_message):\n print config.patterns[pattern]\n"
},
{
"answer_id": 187628,
"author": "Aaron Hays",
"author_id": 26505,
"author_profile": "https://Stackoverflow.com/users/26505",
"pm_score": 6,
"selected": true,
"text": "[sections] key : value key = value file .* does not exist : file not found\nuser .* not found : authorization error\n { file .* does not exist: file not found,\n user .* not found: authorization error }\n import yaml\n\nerrors = yaml.load(open('my.yaml'))\n errors -\n - file .* does not exist \n - file not found\n-\n - user .* not found\n - authorization error\n [ [file .* does not exist, file not found],\n [user .* not found, authorization error]]\n yaml.load"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15622/"
] |
186,917
|
<p>I'm trying to catch a ClassCastException when deserializing an object from xml.</p>
<p>So,</p>
<pre><code>try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
</code></pre>
<p>And yet this won't as the exception doesn't get caught. What would you suggest?</p>
|
[
{
"answer_id": 186977,
"author": "yanchenko",
"author_id": 15187,
"author_profile": "https://Stackoverflow.com/users/15187",
"pm_score": 0,
"selected": false,
"text": "instanceof public T restore(String from){\n...\nrestoredItem = (T) decoder.readObject();\n...\n}\n"
},
{
"answer_id": 187061,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 5,
"selected": true,
"text": "class MyReader<T> {\n private final Class<T> clazz;\n MyReader(Class<T> clazz) {\n if (clazz == null) {\n throw new NullPointerException();\n }\n this.clazz = clazz;\n }\n public T restore(String from) {\n ...\n try {\n restoredItem = clazz.cast(decoder.readObject());\n ...\n return restoredItem;\n } catch (ClassCastException exc) {\n ...\n }\n }\n}\n public <T> T restore(Class<T> clazz, String from) {\n ...\n try {\n restoredItem = clazz.cast(decoder.readObject());\n ...\n"
},
{
"answer_id": 187113,
"author": "Tobias Schulte",
"author_id": 969,
"author_profile": "https://Stackoverflow.com/users/969",
"pm_score": 2,
"selected": false,
"text": "public class GenericsTest\n{\n public static void main(String[] args)\n {\n System.out.println(cast(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> cast(\"Hallo\"));\n\n System.out.println(castBaseNumber(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> castBaseNumber(Integer.valueOf(0)));\n System.out.println(GenericsTest.<Long> castBaseNumber(\"Hallo\"));\n }\n\n private static <T extends Number> T castBaseNumber(Object o)\n {\n T t = (T)o;\n return t;\n }\n\n private static <T> T cast(Object o)\n {\n T t = (T)o;\n return t;\n }\n}\n String s = GenericsTest.<Long> cast(\"Hallo\");\n Object o = decoder.readObject();\nif (o instanceof Something)\n restoredItem = (T) o;\nelse \n // Error handling\n public Reader<T extends Number>{...}\n\nLong l = new Reader<Long>(\"file.xml\").getValue(); // there might be the ClassCastException\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
] |
186,918
|
<p>My master page contains a list as shown here. What I'd like to do though, is add the "class=active" attribute to the list li thats currently active but I have no idea how to do this. I know that the code goes in the aspx page's page_load event, but no idea how to access the li I need to add the attribute. Please enlighten me. Many thanks.</p>
<pre><code><div id="menu">
<ul id="nav">
<li class="forcePadding"><img src="css/site-style-images/menu_corner_right.jpg" /></li>
<li id="screenshots"><a href="screenshots.aspx" title="Screenshots">Screenshots</a></li>
<li id="future"><a href="future.aspx" title="Future">Future</a></li>
<li id="news"><a href="news.aspx" title="News">News</a></li>
<li id="download"><a href="download.aspx" title="Download">Download</a></li>
<li id="home"><a href="index.aspx" title="Home">Home</a></li>
<li class="forcePadding"><img src="css/site-style-images/menu_corner_left.jpg" /></li>
</ul>
</div>
</code></pre>
|
[
{
"answer_id": 186976,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 1,
"selected": false,
"text": "ClientScript.RegisterStartupScript(this.GetType(), \"setActiveLI\", \"document.getElementById(\\\"\"+id+\"\\\").setAttribute(\\\"class\\\", \\\"active\\\");\", true);\n"
},
{
"answer_id": 187014,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 0,
"selected": false,
"text": "public GenericHtmlControl Li1\n{\n get\n {\n return this.LiWhatever;\n }\n}\n MasterPage2 asd = ((MasterPage2)Page.Master).Li1.Attributes.Add(\"class\", \"bla\");\n"
},
{
"answer_id": 187020,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 2,
"selected": false,
"text": "public static Control FindControlRecursive(Control rootControl, string id)\n{\n if (rootControl != null)\n {\n if (rootControl.ID == id)\n {\n return rootControl;\n }\n\n for (int i = 0; i < rootControl.Controls.Count; i++)\n {\n Control child;\n\n if ((child = FindControlRecursive(rootControl.Controls[i], id)) != null)\n {\n return child;\n }\n }\n }\n\n return null;\n}\n Control foundControl= FindControlRecursive(Page.Master, \"theIdOfTheControlYouWantToFind\");\n((HtmlControl)foundControl).Attributes.Add(\"class\", \"active\");\n"
},
{
"answer_id": 187023,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 6,
"selected": true,
"text": "<ul id=\"nav\" runat=\"server\">\n <li class=\"forcePadding\"><img src=\"css/site-style-images/menu_corner_right.jpg\" /></li> \n <li id=\"screenshots\"><a href=\"screenshots.aspx\" title=\"Screenshots\">Screenshots</a></li>\n <li id=\"future\"><a href=\"future.aspx\" title=\"Future\">Future</a></li>\n <li id=\"news\"><a href=\"news.aspx\" title=\"News\">News</a></li>\n <li id=\"download\"><a href=\"download.aspx\" title=\"Download\">Download</a></li>\n <li id=\"home\"><a href=\"index.aspx\" title=\"Home\">Home</a></li>\n <li class=\"forcePadding\"><img src=\"css/site-style-images/menu_corner_left.jpg\" /></li>\n</ul>\n foreach(Control ctrl in nav.controls)\n{\n if(!ctrl is HtmlAnchor)\n {\n string url = ((HtmlAnchor)ctrl).Href;\n if(url == GetCurrentPage()) // <-- you'd need to write that\n ctrl.Parent.Attributes.Add(\"class\", \"active\");\n }\n}\n"
},
{
"answer_id": 187388,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 1,
"selected": false,
"text": "<ul> <li>"
},
{
"answer_id": 193504,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 0,
"selected": false,
"text": "#navbar a:hover,\n .articles #navbar #articles a,\n .topics #navbar #topics a,\n .about #navbar #about a,\n .contact #navbar #contact a,\n .contribute #navbar #contribute a,\n .feed #navbar #feed a {\n background: url(/pix/navbarlinkbg.gif) top left repeat-x; color: #555;\n}\n\n....\n\n<body class=\"articles\" onload=\"\">\n\n<ul id=\"navbar\">\n <li id=\"articles\"><a href=\"/articles/\" title=\"Articles\">Articles</a></li>\n <li id=\"topics\"><a href=\"/topics/\" title=\"Topics\">Topics</a></li>\n <li id=\"about\"><a href=\"/about/\" title=\"About\">About</a></li>\n <li id=\"contact\"><a href=\"/contact/\" title=\"Contact\">Contact</a></li>\n <li id=\"contribute\"><a href=\"/contribute/\" title=\"Contribute\">Contribute</a></li>\n <li id=\"feed\"><a href=\"/feed/\" title=\"Feed\">Feed</a></li>\n</ul>\n"
},
{
"answer_id": 10795178,
"author": "shivanand nagarabetta",
"author_id": 1423148,
"author_profile": "https://Stackoverflow.com/users/1423148",
"pm_score": 0,
"selected": false,
"text": "((HtmlControl)this.Master.FindControl(\"dpohome1\")).Attributes.Add(\"class\", \"on\");\n"
},
{
"answer_id": 58284225,
"author": "Azum",
"author_id": 12134103,
"author_profile": "https://Stackoverflow.com/users/12134103",
"pm_score": 0,
"selected": false,
"text": "protected string SetCssClass(string page)\n{\n return Request.Url.AbsolutePath.ToLower().EndsWith(page.ToLower()) ? \"active\" : \"\";\n} <li id=\"screenshots\" class = \"<%= SetCssClass(\"screenshots.aspx\") %>\">\n<a href=\"screenshots.aspx\" title=\"Screenshots\">Screenshots</a></li> <li id=\"future\" class = \"<%= SetCssClass(\"future.aspx\") %>\">\n<a href=\"future.aspx\" title=\"Future\">Future</a></li>\n <li> SetCssClass(pagename)"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
186,921
|
<p>I am using the YUI layout manager which seems to work at an OK speed. However if the page contains a large <code><Table></code> with about 500 rows, the YUI <code>render()</code> function takes about a <strong>minute</strong> longer to run.</p>
<p>When I open the same page without the layout manager it opens in less than a second.</p>
<p>My <em>only</em> concern is with <strong>IE 7</strong>. I tried it on firefox and it only took about three seconds.</p>
<p>Any ideas on what is taking so long? Can I somehow tell the layout manager to ignore the table?</p>
|
[
{
"answer_id": 187418,
"author": "tpower",
"author_id": 18107,
"author_profile": "https://Stackoverflow.com/users/18107",
"pm_score": 4,
"selected": true,
"text": "render() style.display = 'none' style.display = 'block'"
},
{
"answer_id": 283732,
"author": "Stuart Grimshaw",
"author_id": 11470,
"author_profile": "https://Stackoverflow.com/users/11470",
"pm_score": 0,
"selected": false,
"text": "var myDataTable = new YAHOO.widget.DataTable(\"myContainer\", \n myColumnDefs, \n myDataSource, \n {renderLoopSize: 100}); \n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
186,922
|
<p>I'm looking for a log viewer with similar capablilties as Chainsaw, in which I can tail Glassfish log files over for instance SSH/SCP. Does anyone know if such a tool exist?</p>
|
[
{
"answer_id": 8538881,
"author": "Alan B. Dee",
"author_id": 848926,
"author_profile": "https://Stackoverflow.com/users/848926",
"pm_score": 3,
"selected": false,
"text": "type=log4j\npattern=[#|TIMESTAMP|LEVEL|PROP(A)|CLASS|_ThreadID=PROP(B);_ThreadName=THREAD;|MESSAGE|#]\ndateFormat=yyyy-MM-ddTHH:mm:ss.SSSZZZZ\nname=glassfish parser\ncharset=UTF-8\n"
},
{
"answer_id": 10393070,
"author": "pharsicle",
"author_id": 181506,
"author_profile": "https://Stackoverflow.com/users/181506",
"pm_score": 3,
"selected": false,
"text": "name=GlassFish Pattern\ntype=log4j\npattern=[#|TIMESTAMP|LEVEL|PROP(A)|LOGGER|_ThreadID=PROP(B);_ThreadName=THREAD;|MESSAGE\ndateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ\ncharset=UTF-8\ncustomLevels=SEVERE=FATAL,WARNING=WARN,CONFIG=INFO,FINE=DEBUG,FINER=TRACE,FINEST=TRACE,INFO=INFO\n \\n|#]"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11429/"
] |
186,923
|
<p>How do I define the Assembly folder for an Application correctly?
I tried to use the registry Key:
HKLM/SOFTWARE/Microsoft/.NET Framework/AssemblyFolders/App-Name
and use the (Default) to set this to the path where the assemblies are located.</p>
<p>Some time ago this worked fine, but as I compiled a new Version and deployed it to a PC it wont work any more.</p>
<p>Do I have to add something else or missed any task?</p>
|
[
{
"answer_id": 8538881,
"author": "Alan B. Dee",
"author_id": 848926,
"author_profile": "https://Stackoverflow.com/users/848926",
"pm_score": 3,
"selected": false,
"text": "type=log4j\npattern=[#|TIMESTAMP|LEVEL|PROP(A)|CLASS|_ThreadID=PROP(B);_ThreadName=THREAD;|MESSAGE|#]\ndateFormat=yyyy-MM-ddTHH:mm:ss.SSSZZZZ\nname=glassfish parser\ncharset=UTF-8\n"
},
{
"answer_id": 10393070,
"author": "pharsicle",
"author_id": 181506,
"author_profile": "https://Stackoverflow.com/users/181506",
"pm_score": 3,
"selected": false,
"text": "name=GlassFish Pattern\ntype=log4j\npattern=[#|TIMESTAMP|LEVEL|PROP(A)|LOGGER|_ThreadID=PROP(B);_ThreadName=THREAD;|MESSAGE\ndateFormat=yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ\ncharset=UTF-8\ncustomLevels=SEVERE=FATAL,WARNING=WARN,CONFIG=INFO,FINE=DEBUG,FINER=TRACE,FINEST=TRACE,INFO=INFO\n \\n|#]"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
186,932
|
<p>My stuff is made with several components among which some are written in C. As I would like to add some security features, I am thinking of communicating over an SSL/TLS layer.</p>
<p>Could you advise me some good lib to do this (if possible) ?</p>
|
[
{
"answer_id": 766595,
"author": "sybreon",
"author_id": 85021,
"author_profile": "https://Stackoverflow.com/users/85021",
"pm_score": 0,
"selected": false,
"text": "Internet --- [SSLTunnel] --- Your App\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26465/"
] |
186,935
|
<p>I'm writing server-side programs in PHP for an iPhone app. And I have no iPhone. :P</p>
<p>The iPhone app requests XML files from the site whenever a user runs the iPhone app. You may visit <a href="http://www.appvee.com/iphone/ads" rel="nofollow noreferrer">http://www.appvee.com/iphone/ads</a> or <a href="http://www.appvee.com/iphone/latest" rel="nofollow noreferrer">http://www.appvee.com/iphone/latest</a> for the XML files.</p>
<p>And a message box will show up with the following error messages:
"Web Site Error
Conversion of data failed. The file is not UTF-8, or in the encoding specified in XML header if XML.
"
<img src="https://farm4.static.flickr.com/3195/2925993535_bd62b7cf42.jpg?v=0" alt="alt text"></p>
<p>Maybe I must add header("Content-type: text/xml"); at the beginning of the PHP files? I didn't add this line and it worked well before.</p>
<p>Any help is greatly appreciated.</p>
|
[
{
"answer_id": 766595,
"author": "sybreon",
"author_id": 85021,
"author_profile": "https://Stackoverflow.com/users/85021",
"pm_score": 0,
"selected": false,
"text": "Internet --- [SSLTunnel] --- Your App\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23773/"
] |
186,942
|
<p>I have this script:</p>
<pre><code>select name,create_date,modify_date from sys.procedures order by modify_date desc
</code></pre>
<p>I can see what procedures were modified lately.
I will add a "where modify_date >= "
And I'd like to use some system stored procedure, that will generate me :
drop + create scripts for the (let's say 5 matching) stored procedures</p>
<p>Can i do this somehow?</p>
<p>thanks</p>
<hr>
<p>ok. i have the final version:</p>
<p><a href="http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html" rel="nofollow noreferrer">http://swooshcode.blogspot.com/2008/10/generate-stored-procedures-scripts-for.html</a></p>
<p>you guys helped a lot</p>
<p>thanks</p>
|
[
{
"answer_id": 187063,
"author": "jdecuyper",
"author_id": 296,
"author_profile": "https://Stackoverflow.com/users/296",
"pm_score": 0,
"selected": false,
"text": "DECLARE @spName NVARCHAR(128)\nDECLARE myCursor CURSOR FOR SELECT name FROM sys.procedures ORDER BY modify_date DESC\nOPEN myCursor\nFETCH NEXT FROM myCursor INTO @spName\nWHILE @@fetch_status = 0\nBEGIN\n -- Process each stored procedure with a dynamic query\n PRINT @spName\nFETCH NEXT FROM myCursor INTO @spName\nEND\nCLOSE myCursor\nDEALLOCATE myCursor\n"
},
{
"answer_id": 187095,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 3,
"selected": true,
"text": "SELECT OBJECT_DEFINITION(object_id), 'drop procedure [' + name + ']'\nFROM sys.procedures\nWHERE modify_date >= @date\n"
},
{
"answer_id": 187176,
"author": "Swoosh",
"author_id": 26472,
"author_profile": "https://Stackoverflow.com/users/26472",
"pm_score": 0,
"selected": false,
"text": "sp_helptext 'my_stored_procedure'\n"
},
{
"answer_id": 187243,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 1,
"selected": false,
"text": "DECLARE @dt AS datetime\nSET @dt = '10/1/2008'\n\nDECLARE @sql AS varchar(max)\n\nSELECT @sql = COALESCE(@sql, '')\n + '-- ' + o.name + CHAR(13) + CHAR(10)\n + 'DROP PROCEDURE ' + o.name + CHAR(13) + CHAR(10)\n + 'GO' + CHAR(13) + CHAR(10)\n + m.definition + CHAR(13) + CHAR(10)\n + 'GO' + CHAR(13) + CHAR(10)\nFROM sys.sql_modules AS m\nINNER JOIN sys.objects AS o\n ON m.object_id = o.object_id\nINNER JOIN sys.procedures AS p\n ON m.object_id = p.object_id\nWHERE p.modify_date >= @dt\n\nPRINT @sql -- or EXEC (@sql)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26472/"
] |
186,944
|
<p>I have to create a C program which will run on Linux server. It will take information from Oracle database, create a local file and then copy that file to Windows server. I know how to create a local file on Linux server. But what is the way to copy it to windows server from C?</p>
|
[
{
"answer_id": 187185,
"author": "Scott Bennett-McLeish",
"author_id": 1915,
"author_profile": "https://Stackoverflow.com/users/1915",
"pm_score": 2,
"selected": false,
"text": "smbclient //myserver/my_directory <password> -U [domain/]<my_user>\n put my_file_to_copy.dat\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
186,970
|
<p>What ReSharper 4.0 templates for <strong>C#</strong> do you use?</p>
<p>Let's share these in the following format:</p>
<hr>
<h2>[Title]</h2>
<p><em>Optional description</em> </p>
<p><strong>Shortcut:</strong> shortcut<br>
<strong>Available in:</strong> [AvailabilitySetting]</p>
<pre><code>// Resharper template code snippet
// comes here
</code></pre>
<p><strong>Macros properties</strong> (if present):</p>
<ul>
<li><strong>Macro1</strong> - Value - EditableOccurence</li>
<li><strong>Macro2</strong> - Value - EditableOccurence</li>
</ul>
<hr>
<ul>
<li>One macro per answer, please!</li>
<li>Here are some samples for <a href="https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">NUnit test fixture</a> and <a href="https://stackoverflow.com/questions/186970/what-resharper-40-templates-for-c-do-you-use#186978">Standalone NUnit test case</a> that describe live templates in the suggested format.</li>
</ul>
|
[
{
"answer_id": 186974,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "[NUnit.Framework.TestFixtureAttribute]\npublic sealed class $TypeToTest$Tests\n{\n [NUnit.Framework.TestAttribute]\n public void $Test$()\n {\n var t = new $TypeToTest$()\n $END$\n }\n}\n"
},
{
"answer_id": 186978,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "[NUnit.Framework.TestAttribute]\npublic void $Test$()\n{\n $END$\n}\n"
},
{
"answer_id": 187841,
"author": "Ed Ball",
"author_id": 23818,
"author_profile": "https://Stackoverflow.com/users/23818",
"pm_score": 5,
"selected": false,
"text": "public void Dispose()\n{\n Dispose(true);\n System.GC.SuppressFinalize(this);\n}\n\nprotected virtual void Dispose(bool disposing)\n{\n if (!disposed)\n {\n if (disposing)\n {\n if ($MEMBER$ != null)\n {\n $MEMBER$.Dispose();\n $MEMBER$ = null;\n }\n }\n\n disposed = true;\n }\n}\n\n~$CLASS$()\n{\n Dispose(false);\n}\n\nprivate bool disposed;\n"
},
{
"answer_id": 191890,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 2,
"selected": false,
"text": "[Test, Ignore]\npublic void $TestName$()\n{\n throw new NotImplementedException();\n}\n$END$\n"
},
{
"answer_id": 227019,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 2,
"selected": false,
"text": "Enforce.ArgumentNotNull($inner$, \"$inner$\");\n"
},
{
"answer_id": 259116,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "Trace.WriteLine(string.Format(\"$MASK$\",$ARGUMENT$));\n value \"{0}\""
},
{
"answer_id": 333490,
"author": "Kjetil Klaussen",
"author_id": 15599,
"author_profile": "https://Stackoverflow.com/users/15599",
"pm_score": 3,
"selected": false,
"text": "Assert.AreEqual($expected$, $actual$);$END$\n Assert.That($expected$, Is.EqualTo($actual$));$END$\n"
},
{
"answer_id": 503797,
"author": "Ian G",
"author_id": 5764,
"author_profile": "https://Stackoverflow.com/users/5764",
"pm_score": 2,
"selected": false,
"text": "[ComVisible(true)]\n[ClassInterface(ClassInterfaceType.None)]\n[Guid(\"$GUID$\")]\npublic class $NAME$ : $INTERFACE$\n{\n $END$\n}\n"
},
{
"answer_id": 609796,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "Control ISynchronizeInvoke Debug.Assert(!$SYNC_INVOKE$.InvokeRequired, \"InvokeRequired\");\n System.ComponentModel.ISynchronizeInvoke"
},
{
"answer_id": 609824,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "if (InvokeRequired)\n{\n Invoke((System.Action)delegate { $METHOD_NAME$($END$); });\n return;\n}\n void DoSomething(Type1 arg1)\n{\n if (InvokeRequired)\n {\n Invoke((Action)delegate { DoSomething(arg1); });\n return;\n }\n\n // Rest of method will only execute on the correct thread\n // ...\n}\n"
},
{
"answer_id": 639581,
"author": "Daver",
"author_id": 68095,
"author_profile": "https://Stackoverflow.com/users/68095",
"pm_score": 2,
"selected": false,
"text": "[TestMethod]\npublic void $TestName$()\n{\n throw new NotImplementedException();\n\n //Arrange.\n\n //Act.\n\n //Assert.\n}\n\n$END$\n"
},
{
"answer_id": 639618,
"author": "womp",
"author_id": 63756,
"author_profile": "https://Stackoverflow.com/users/63756",
"pm_score": 3,
"selected": false,
"text": "[ExpectedException(typeof($TYPE$))]\n"
},
{
"answer_id": 871250,
"author": "Chris Brandsma",
"author_id": 9443,
"author_profile": "https://Stackoverflow.com/users/9443",
"pm_score": 3,
"selected": false,
"text": "private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof($TYPE$));\n"
},
{
"answer_id": 1493338,
"author": "paraquat",
"author_id": 144067,
"author_profile": "https://Stackoverflow.com/users/144067",
"pm_score": 2,
"selected": false,
"text": "[NUnit.Framework.SetUp]\npublic void SetUp()\n{\n $END$\n}\n"
},
{
"answer_id": 1493361,
"author": "paraquat",
"author_id": 144067,
"author_profile": "https://Stackoverflow.com/users/144067",
"pm_score": 2,
"selected": false,
"text": "[NUnit.Framework.TearDown]\npublic void TearDown()\n{\n $END$\n}\n"
},
{
"answer_id": 1499011,
"author": "Chris Doggett",
"author_id": 64203,
"author_profile": "https://Stackoverflow.com/users/64203",
"pm_score": 3,
"selected": false,
"text": "if (null == $var$)\n{\n $END$\n}\n if (null != $var$)\n{\n $END$\n}\n"
},
{
"answer_id": 2452390,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "var mocks = new new MockRepository(); using (mocks.Record())\n{\n $END$\n}\n\nusing (mocks.Playback())\n{\n\n}\n"
},
{
"answer_id": 2627586,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 0,
"selected": false,
"text": "Expect.Call($EXPECT_CODE$).Return($RETURN_VALUE$);\n Expect.Call(delegate { $EXPECT_CODE$; });\n"
},
{
"answer_id": 2677220,
"author": "Bryce Fischer",
"author_id": 450139,
"author_profile": "https://Stackoverflow.com/users/450139",
"pm_score": 1,
"selected": false,
"text": "<typeAlias alias=\"$ALIAS$\" type=\"$TYPE$,$ASSEMBLY$\"/>\n <type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\"/>\n <type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\" name=\"$NAME$\"/>\n <type type=\"$TYPE$\" mapTo=\"$MAPTYPE$\">\n <typeConfig>\n <constructor>\n $PARAMS$\n </constructor>\n </typeConfig>\n</type>\n"
},
{
"answer_id": 3588387,
"author": "jhappoldt",
"author_id": 52307,
"author_profile": "https://Stackoverflow.com/users/52307",
"pm_score": 0,
"selected": false,
"text": "if (!Dispatcher.CheckAccess())\n{\n Dispatcher.BeginInvoke((Action)delegate { $METHOD_NAME$(sender, e); });\n return;\n}\n\n$END$\n $METHOD_NAME$"
},
{
"answer_id": 3588457,
"author": "Vaccano",
"author_id": 16241,
"author_profile": "https://Stackoverflow.com/users/16241",
"pm_score": 3,
"selected": false,
"text": "[TestMethod]\npublic void $MethodName$_$StateUnderTest$_$ExpectedBehavior$()\n{\n // Arrange\n $END$\n\n // Act\n\n\n // Assert\n\n}\n"
},
{
"answer_id": 3683058,
"author": "Igor Brejc",
"author_id": 55408,
"author_profile": "https://Stackoverflow.com/users/55408",
"pm_score": 1,
"selected": false,
"text": "<TemplatesExport family=\"Live Templates\">\n <Template uid=\"49c599bb-a1ec-4def-a2ad-01de05799843\" shortcut=\"log4\" description=\"inserts log4net XML configuration block\" text=\" <configSections>
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
 </configSections>

 <log4net debug="false">
 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
 <param name="File" value="logs\\\\$LogFileName$.log" />
 <param name="AppendToFile" value="false" />
 <param name="RollingStyle" value="Size" />
 <param name="MaxSizeRollBackups" value="5" />
 <param name="MaximumFileSize" value="5000KB" />
 <param name="StaticLogFileName" value="true" />

 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%date [%3thread] %-5level %-40logger{3} - %message%newline" />
 </layout>
 </appender>

 <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
 <layout type="log4net.Layout.PatternLayout">
 <param name="ConversionPattern" value="%message%newline" />
 </layout>
 </appender>

 <root>
 <priority value="DEBUG" />
 <appender-ref ref="LogFileAppender" />
 </root>
 </log4net>
\" reformat=\"False\" shortenQualifiedReferences=\"False\">\n <Context>\n <FileNameContext mask=\"*.config\" />\n </Context>\n <Categories />\n <Variables>\n <Variable name=\"LogFileName\" expression=\"getOutputName()\" initialRange=\"0\" />\n </Variables>\n <CustomProperties />\n </Template>\n</TemplatesExport>\n"
},
{
"answer_id": 3729088,
"author": "codekaizen",
"author_id": 58391,
"author_profile": "https://Stackoverflow.com/users/58391",
"pm_score": 2,
"selected": false,
"text": "new System.Guid(\"$GUID$\")\n"
},
{
"answer_id": 4790889,
"author": "Dmitrii Lobanov",
"author_id": 100110,
"author_profile": "https://Stackoverflow.com/users/100110",
"pm_score": 3,
"selected": false,
"text": "Initializes a new instance of the <see cref=\"$classname$\"/> class.$END$\n"
},
{
"answer_id": 5001023,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 5,
"selected": false,
"text": "x => x.$END$\n"
},
{
"answer_id": 5008117,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 4,
"selected": false,
"text": "string.IsNullOrEmpty($VAR$)\n"
},
{
"answer_id": 5008509,
"author": "Sean Kearon",
"author_id": 2608,
"author_profile": "https://Stackoverflow.com/users/2608",
"pm_score": 3,
"selected": false,
"text": "if (value != _$LOWEREDMEMBER$)\n{\n _$LOWEREDMEMBER$ = value;\n NotifyPropertyChanged(\"$MEMBER$\");\n}\n private string _dateOfBirth;\npublic string DateOfBirth\n{\n get { return _dateOfBirth; }\n set\n {\n npc<--tab from here\n }\n}\n private void NotifyPropertyChanged(String info)\n{\n if (PropertyChanged != null)\n {\n PropertyChanged(this, new PropertyChangedEventArgs(info));\n }\n}\n public decimal CircuitConductorLive\n{\n get { return _circuitConductorLive; }\n set { Set(x => x.CircuitConductorLive, ref _circuitConductorLive, value); }\n}\n"
},
{
"answer_id": 5019071,
"author": "James Kovacs",
"author_id": 251305,
"author_profile": "https://Stackoverflow.com/users/251305",
"pm_score": 3,
"selected": false,
"text": "x => x.$END$\n y => y.$END$\n z => z.$END$\n items.ForEach(x => x.Children.ForEach(y => Console.WriteLine(y.Name)));\n"
},
{
"answer_id": 5019098,
"author": "James Kovacs",
"author_id": 251305,
"author_profile": "https://Stackoverflow.com/users/251305",
"pm_score": 3,
"selected": false,
"text": "System.Console.WriteLine(\"Press <ENTER> to exit...\");\nSystem.Console.ReadLine();$END$\n"
},
{
"answer_id": 5019232,
"author": "James Kovacs",
"author_id": 251305,
"author_profile": "https://Stackoverflow.com/users/251305",
"pm_score": 1,
"selected": false,
"text": "virtual $END$\n public |string Name { get; set; }\n"
},
{
"answer_id": 5541672,
"author": "David R. Longnecker",
"author_id": 1754,
"author_profile": "https://Stackoverflow.com/users/1754",
"pm_score": 0,
"selected": false,
"text": "Protected static Exception exception;\nBecause of = () => exception = Catch.Exception(() => $something$);\n$END$\n"
},
{
"answer_id": 5543434,
"author": "David R. Longnecker",
"author_id": 1754,
"author_profile": "https://Stackoverflow.com/users/1754",
"pm_score": 3,
"selected": false,
"text": ".ForMember(d => d$property$, o => o.MapFrom(s => s$src_property$))\n$END$\n"
},
{
"answer_id": 5699815,
"author": "Jonas Van der Aa",
"author_id": 176541,
"author_profile": "https://Stackoverflow.com/users/176541",
"pm_score": 3,
"selected": false,
"text": "public static readonly System.Windows.DependencyProperty $PropertyName$Property =\n System.Windows.DependencyProperty.Register(\"$PropertyName$\",\n typeof ($PropertyType$),\n typeof ($OwnerType$));\n\n public $PropertyType$ $PropertyName$\n {\n get { return ($PropertyType$) GetValue($PropertyName$Property); }\n set { SetValue($PropertyName$Property, value); }\n }\n\n$END$\n"
},
{
"answer_id": 6595191,
"author": "Richard Dingwall",
"author_id": 91551,
"author_profile": "https://Stackoverflow.com/users/91551",
"pm_score": 0,
"selected": false,
"text": "Machine.Specifications.It $should_$ =\n () => \n {\n\n };\n"
},
{
"answer_id": 9236368,
"author": "Michael Kropat",
"author_id": 27581,
"author_profile": "https://Stackoverflow.com/users/27581",
"pm_score": 1,
"selected": false,
"text": "public override sealed bool Equals(object other) {\n return Equals(other as $TYPE$);\n}\n\npublic bool Equals($TYPE$ other) {\n return !ReferenceEquals(other, null) && $END$;\n}\n\npublic override int GetHashCode() {\n // *Always* call Equals.\n return 0;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/186970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47366/"
] |
187,000
|
<p>I have an asp.net website that allows the user to download largish files - 30mb to about 60mb. Sometimes the download works fine but often it fails at some varying point before the download finishes with the message saying that the connection with the server was reset.</p>
<p>Originally I was simply using Server.TransmitFile but after reading up a bit I am now using the code posted below. I am also setting the Server.ScriptTimeout value to 3600 in the Page_Init event.</p>
<pre><code>private void DownloadFile(string fname, bool forceDownload)
{
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "";
// set known types based on file extension
if (ext != null)
{
switch (ext.ToLower())
{
case ".mp3":
type = "audio/mpeg";
break;
case ".htm":
case ".html":
type = "text/HTML";
break;
case ".txt":
type = "text/plain";
break;
case ".doc":
case ".rtf":
type = "Application/msword";
break;
}
}
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name.Replace(" ", "_"));
}
if (type != "")
{
Response.ContentType = type;
}
else
{
Response.ContentType = "application/x-msdownload";
}
System.IO.Stream iStream = null;
// Buffer to read 10K bytes in chunk:
byte[] buffer = new Byte[10000];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new System.IO.FileStream(path, System.IO.FileMode.Open,
System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
Response.Write("Error : " + ex.Message);
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Close();
}
}
</code></pre>
|
[
{
"answer_id": 187022,
"author": "kaa",
"author_id": 2105,
"author_profile": "https://Stackoverflow.com/users/2105",
"pm_score": 2,
"selected": false,
"text": "<configuration>\n <system.web>\n <httpRuntime executionTimeout=\"3600\"/>\n </system.web>\n</configuration>\n int length;\nwhile( Response.IsClientConnected && \n (length=iStream.Read(buffer,0,buffer.Length))>0 ) \n{\n Response.OutputStream.Write(buffer,0,length);\n Response.Flush();\n}\n"
},
{
"answer_id": 12861312,
"author": "Greg Finzer",
"author_id": 52962,
"author_profile": "https://Stackoverflow.com/users/52962",
"pm_score": 0,
"selected": false,
"text": "public partial class ssl_Report_StreamReport : BaseReportPage\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n //Get the parameters\n string reportName = Utils.ParseStringRequest(Request, \"reportName\") ?? string.Empty;\n string reportGuid = Session[\"reportGuid\"].ToString();\n string path = Path.Combine(ReportPath(), Utils.GetSessionReportName(reportName, reportGuid));\n\n using (var fileStream = File.Open(path, FileMode.Open))\n {\n Response.ClearHeaders();\n Response.Clear();\n Response.ContentType = \"application/octet-stream\";\n Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\\\"\" + reportName + \"\\\"\");\n Response.AddHeader(\"Content-Length\", fileStream.Length.ToString(CultureInfo.InvariantCulture));\n StreamHelper.CopyStream(fileStream, Response.OutputStream);\n Response.Flush();\n Response.End();\n }\n\n ReportProcessor.ClearReport(Session.SessionID, path);\n }\n}\n\n\npublic static class StreamHelper\n{\n public static void CopyStream(Stream input, Stream output)\n {\n byte[] buffer = new byte[32768];\n int read;\n while ((read = input.Read(buffer, 0, buffer.Length)) > 0)\n {\n output.Write(buffer, 0, read);\n }\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10135/"
] |
187,001
|
<p>Is it possible to provide WCF with a custom proxy address and custom credentials? </p>
<p>I've found this answer on stackoverflow: <a href="https://stackoverflow.com/questions/105499/how-to-set-proxy-with-credentials-to-generated-wcf-client">How to set proxy with credentials to generated WCF client?</a>, but I've got a complication, the service I'm authenticating against uses its own authentication, so I've got to use two sets of credentials (one to get through the proxy, and the other to authenticate against the service)</p>
<p>I'm using the technique described in the answers to the other question to provide the service credentials. e.g.</p>
<pre><code>client.ClientCredentials.UserName.UserName = username;
client.ClientCredentials.UserName.Password = password;
</code></pre>
<p>I can set the address of the proxy using something like this:</p>
<pre><code>(client.Endpoint.Binding as WSHttpBinding).ProxyAddress = ...;
</code></pre>
<p>How do I set what is effectively two sets of credentials? (NB: The credentials for the proxy and the actual service are different!) Also note that the proxy details are not necessarily the default system proxy details.</p>
|
[
{
"answer_id": 2111642,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 5,
"selected": true,
"text": "// get this information from the user / config file / etc.\nUri proxyAddress;\nstring userName;\nstring password;\n\n// set this before any web requests or WCF calls\nWebRequest.DefaultWebProxy = new WebProxy(proxyAddress)\n{\n Credentials = new NetworkCredential(userName, password),\n};\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1313/"
] |
187,003
|
<p>I just need a simple JSON or YAML (or other) text based format for recording the time I spend on tasks. I prefer to do as much work as possible in my text editor (e text editor) so it is more natural to me to stay in the editor and not switch back and forth to programs like Excel (plus this way I retain portable and "open" data). The idea is that if I record all my tasks in JSON or YAML format then I could easily use IRB (interactive Ruby) or some other interactive programming session to create a work log report for myself. Also I could use this to generate reports for my clients pretty easily at the end of some particular time period. </p>
<p>It would nice if the format already exists and that the format has some mechanism for coping with the following problem: some data that I record should be for "internal use only" whereas other data could be safe for "external" use. In other words, one problem I would like to avoid is the trouble of sifting back through text work logs in order to filter items that should not be forward to the client.</p>
<p>Q: Why JSON or YAML???<br>
A: JSON or YAML seems to have a cleaner syntax than creating something with XML. Remember I am the one who has to type the log so I am not interested in typing a bunch of extra closing tags.</p>
|
[
{
"answer_id": 341113,
"author": "dreftymac",
"author_id": 42223,
"author_profile": "https://Stackoverflow.com/users/42223",
"pm_score": 2,
"selected": false,
"text": "### myyamllog.txt\n - log_entry: posted some stuff on stack overflow\n project: prj_my_personal_stuff\n datestamp: 2008-11-14 07:58\n summary: answering a question on formatted text for logs\n body: | \n you can create a \"dummy\" log entry as a text editor snippet\n and just paste a new entry every time you start a new project.\n The snippet will just contain placeholders for the parts you have\n to fill in by hand. Timestamp will be auto-populated when you paste.\n\n - log_entry: followup on SO answer\n project: prj_my_personal_stuff\n datestamp: 2008-11-14 08:10\n summary: \n body: | \n As far as a \"standardized\" format, you can pick anything you want.\n One suggestion is to just make each individual log entry a simple \n series of name-value pairs. Then combine those individual entries\n as a series of YAML sequence elements. The benefit of this is it\n reflects the layout of a single database table. The sequence elements\n are records and the name-value pairs are fields.\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20714/"
] |
187,004
|
<p>I have a large legacy system to maintain. The codebase uses threads all over the place and those threads share a lot of mutable data. I know, sounds bad. Anyway, don't answer "rewrite the whole application from scratch" or I'll vote you down :-) I have tried to run some static analysis tools on the codebase, but none of those seem to catch this case which occurs a lot in our source code: multiple threads are reading and writing variables which are not marked as volatile or synchronized at all. Typically this occurs on "runFlag"-type variables. An example of this is on Effective Java 2nd edition page 260:</p>
<pre><code>public class StopThread
{
private static boolean stopRequested;
public static void main(String[] args) throws InterruptedException
{
Thread backgroundThread = new Thread(new Runnable()
{
public void run()
{
int i = 0;
while (!stopRequested)
{
i++;
}
}
});
backgroundThread.start();
Thread.sleep(1000);
stopRequested = true;
}
}
</code></pre>
<p>This example never finishes on Windows/Linux with "-server" startup parameter given to Sun JVM. So, is there any (semi-)automatic way to find these issues, or do I have to rely totally on code reviews?</p>
|
[
{
"answer_id": 187196,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "@GuardedBy"
},
{
"answer_id": 188792,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "public class StaticInvocationFinder extends EmptyVisitor {\n\n @Override\n public void visitMethod(Method obj) {\n System.out.println(\"==========================\");\n System.out.println(\"method:\" + obj.getName());\n\n Code code = obj.getCode();\n InstructionList instructions = new InstructionList(code.getCode());\n for (Instruction instruction : instructions.getInstructions()) {\n // static field or method\n if (Constants.INVOKESTATIC == instruction.getOpcode()) {\n if (instruction instanceof InvokeInstruction) {\n InvokeInstruction invokeInstruction = (InvokeInstruction) instruction;\n ConstantPoolGen cpg = new ConstantPoolGen(obj\n .getConstantPool());\n System.out.println(\"static access:\"\n + invokeInstruction.getMethodName(cpg));\n System.out.println(\" on type:\"\n + invokeInstruction.getReferenceType(cpg));\n }\n }\n }\n instructions.dispose();\n }\n\n public static void main(String[] args) throws Exception {\n JavaClass javaClass = Repository.lookupClass(\"StopThread$1\");\n\n StaticInvocationFinder visitor = new StaticInvocationFinder();\n DescendingVisitor classWalker = new DescendingVisitor(javaClass,\n visitor);\n classWalker.visit();\n }\n\n}\n ==========================\nmethod:<init>\n==========================\nmethod:run\nstatic access:access$0\n on type:StopThread\n private void createMethod_2() {\n InstructionList il = new InstructionList();\n MethodGen method = new MethodGen(ACC_STATIC | ACC_SYNTHETIC, Type.BOOLEAN, Type.NO_ARGS, new String[] { }, \"access$0\", \"StopThread\", il, _cp);\n\n InstructionHandle ih_0 = il.append(_factory.createFieldAccess(\"StopThread\", \"stopRequested\", Type.BOOLEAN, Constants.GETSTATIC));\n il.append(_factory.createReturn(Type.INT));\n method.setMaxStack();\n method.setMaxLocals();\n _cg.addMethod(method.getMethod());\n il.dispose();\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4110/"
] |
187,005
|
<p>I'm working profesionally on a php web application which contains contacts, among other data. I was wondering how hard it would be to make this data available to external programs using the LDAP protocol.</p>
<p>Are there specific tools out there for this? I couldn't really find anything, but I can't imagine I'm the first to think about this.</p>
<hr>
<p>Edit 1:
What I'm looking for is a way to have an application (like a mail client) to be able to use a standard ldap lookup to find contacts from my data.</p>
<p>There are no limitations on using third party software or a separate ldap server on my side, but I want the clients to simply be able to use the built-in ldap connectivity of their application of choice.</p>
<p>What I could see is an ldap server which uses my database or service in my application for serving data as if my application itself is an ldap server. I'd prefer a solution like this, because I don't feel it's right to bloat the application with ldap functionality if I can use an external server for this.</p>
|
[
{
"answer_id": 187441,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 3,
"selected": true,
"text": "modifyTimestamp 20080306214429Z modifyTimestamp"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] |
187,018
|
<p>In a page, on the load event, I am dynamically creating controls for display on the page. This is all working properly. the trouble I am having is when adding extenders from the AJAX control toolkit, specifically I am trying to add rounded corners to a button control. No errors are thrown, but the AJAX Extension functionality does not appear in the displayed page.</p>
<p>Does anyone have any ideas on what I am not doing correctly, or if its even possible?</p>
<pre><code>Dim container As HtmlGenericControl
Dim edit As Button
Dim editRoundedCorners As AjaxControlToolkit.RoundedCornersExtender
For each item in items
container = New HtmlGenericControl("div")
container.ID = "container_" & item.code
edit = New Button()
edit.ID = "edit_" & item.code
edit.Text = "Edit"
edit.Style("padding") = "0 0 0 4px"
edit.SkinID = "smallEditButton"
editRoundedCorners = New AjaxControlToolkit.RoundedCornersExtender()
editRoundedCorners.BorderColor = edit.BorderColor
editRoundedCorners.ID = edit.ID & "_RoundedCorners"
editRoundedCorners.Corners = AjaxControlToolkit.BoxCorners.All
editRoundedCorners.Radius = 3
editRoundedCorners.TargetControlID = edit.ID
container.Controls.Add(editRoundedCorners)
container.Controls.Add(edit)
pageContainer.Controls.Add(container)
Next
</code></pre>
<p>(pageContainer is a div on the page)</p>
|
[
{
"answer_id": 187033,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 2,
"selected": false,
"text": "Controls.Add(editRoundedCorners)\n"
},
{
"answer_id": 189385,
"author": "Compulsion",
"author_id": 3675,
"author_profile": "https://Stackoverflow.com/users/3675",
"pm_score": 2,
"selected": false,
"text": "*parentCtrl*.Controls.Add(*extendername*);\n *controltype* *controlname* = (*controltype*)Page.LoadControl(typeof(*controltype*), new object[]{});\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16391/"
] |
187,040
|
<p>I Have an old vbs script file being kicked off by an AutoSys job. Can I, and how do I, return an int return value to indicate success or failure?</p>
|
[
{
"answer_id": 187051,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 6,
"selected": false,
"text": "WScript.Quit n\n"
},
{
"answer_id": 187055,
"author": "Philip.ie",
"author_id": 180142,
"author_profile": "https://Stackoverflow.com/users/180142",
"pm_score": 6,
"selected": true,
"text": " DIM returnValue\n returnValue = 99\n WScript.Quit(returnValue)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/180142/"
] |
187,046
|
<p>Has anyone seen a tool that will integrate code coverage results with SCM/VCS to attribute untested lines of code to developers?
For example, is there a tool that will take NCover's Coverage.Xml, combine it with SVN blame, and produce a report that tells me things like developer who commits most untested code?</p>
|
[
{
"answer_id": 187051,
"author": "Rob",
"author_id": 7872,
"author_profile": "https://Stackoverflow.com/users/7872",
"pm_score": 6,
"selected": false,
"text": "WScript.Quit n\n"
},
{
"answer_id": 187055,
"author": "Philip.ie",
"author_id": 180142,
"author_profile": "https://Stackoverflow.com/users/180142",
"pm_score": 6,
"selected": true,
"text": " DIM returnValue\n returnValue = 99\n WScript.Quit(returnValue)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26479/"
] |
187,057
|
<p>I want to know how the glBlendFunc works. For example, i have 2 gl textures, where the alpha is on tex1, i want to have alpha in my final image. Where the color is on tex1, i want the color from tex2 to be.</p>
|
[
{
"answer_id": 195803,
"author": "DavidG",
"author_id": 25893,
"author_profile": "https://Stackoverflow.com/users/25893",
"pm_score": 1,
"selected": true,
"text": "glTexCoordPointer( 2, GL_FLOAT, 0, sprite->GetTexBuffer() );\nglVertexPointer( 3, GL_FLOAT, 0, sprite->GetVertexBuffer() );\nglColorPointer( 4, GL_FLOAT, 0, sprite->GetColorBuffer() );\nglDrawArrays( GL_TRIANGLES, 0, 6 ); // Draw 2 triangles\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25893/"
] |
187,059
|
<p>I have a page with a tab control and each control has almost 15 controls. In total there are 10 tabs and about 150 controls in a page (controls like drop down list, textbox, radiobutton, listbox only).</p>
<p>My requirement is that there is a button (submit) at the bottom of the page. I need to check using JavaScript that at least 3 options are selected out of 150 controls in that page irrespective of the tabs which they choose. </p>
<p>Please suggest the simplest and easiest way which this could be done in JavaScript on my aspx page.</p>
|
[
{
"answer_id": 187222,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 3,
"selected": true,
"text": " var selectedCount = 0;\n var element;\n\n for (var i = 0; i < document.forms[0].elements.length; i++)\n {\n element = document.forms[0].elements[i];\n\n switch (element.type)\n {\n case 'text':\n if (element.value.length > 0)\n {\n selectedCount++;\n }\n break;\n case 'select-one':\n if (element.selectedIndex > 0)\n {\n selectedCount++;\n }\n break;\n //etc - add cases for checkbox, radio, etc.\n }\n }\n"
},
{
"answer_id": 193618,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 0,
"selected": false,
"text": "var inputs = $('input');\nvar selects = $('select');\n\nvar textBoxes = $(\"input[type='text']\");\n"
},
{
"answer_id": 20698325,
"author": "John Wu",
"author_id": 2791540,
"author_profile": "https://Stackoverflow.com/users/2791540",
"pm_score": 0,
"selected": false,
"text": "var count = $(\"option:selected\").length;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
187,069
|
<p>It seems the ObservableCollection only support add, remove, clear operation from the UI thread, It throw Not Support Exception if it is operated by a NO UI thread. I tried to override methods of ObservableCollection, unfortunatly, I met lots of problems.
Any one can provide me a ObservableCollection sample which can be operated by multi-threads?
Many thanks!</p>
|
[
{
"answer_id": 187081,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 4,
"selected": true,
"text": "while (!Monitor.TryEnter(_lock, 10))\n{\n DoEvents();\n}\n\ntry\n{\n //modify collection\n}\nfinally\n{\n Monitor.Exit(_lock);\n}\n this.Dispatcher.Invoke(new MyDelegate((myParam) =>\n{\n this.MyCollection.Add(myParam);\n}), state);\n"
},
{
"answer_id": 187096,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "Public Delegate Sub AddItemDelegate(ByVal item As T)\n\nPublic Sub AddItem(ByVal item As T)\n If Application.Current.Dispatcher.CheckAccess() Then\n Me.Add(item)\n Else\n Application.Current.Dispatcher.Invoke(Threading.DispatcherPriority.Normal, New AddItemDelegate(AddressOf AddItem), item)\n End If\nEnd Sub\n"
},
{
"answer_id": 13389450,
"author": "Jesse Chisholm",
"author_id": 1456887,
"author_profile": "https://Stackoverflow.com/users/1456887",
"pm_score": 2,
"selected": false,
"text": "_dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;\n_data = new ObservableCollection<MyDataItemClass>();\n _dispatcher.Invoke(new Action(() => { _data.Add(dataItem); }));\n"
},
{
"answer_id": 14298053,
"author": "Richard Griffiths",
"author_id": 1864489,
"author_profile": "https://Stackoverflow.com/users/1864489",
"pm_score": 2,
"selected": false,
"text": "please note public class ObservableCollectionEx<T> : ObservableCollection<T>\n{\n // Override the event so this class can access it\n public override event System.Collections.Specialized.NotifyCollectionChangedEventHandler \n CollectionChanged;\n\n protected override void OnCollectionChanged (System.Collections.Specialized.NotifyCollectionChangedEventArgs e)\n {\n // Be nice - use BlockReentrancy like MSDN said\n using (BlockReentrancy())\n {\n System.Collections.Specialized.NotifyCollectionChangedEventHandler eventHandler = CollectionChanged;\n if (eventHandler == null)\n return;\n\n Delegate[] delegates = eventHandler.GetInvocationList();\n // Walk thru invocation list\n foreach (System.Collections.Specialized.NotifyCollectionChangedEventHandler handler in delegates)\n {\n DispatcherObject dispatcherObject = handler.Target as DispatcherObject;\n // If the subscriber is a DispatcherObject and different thread\n if (dispatcherObject != null && dispatcherObject.CheckAccess() == false)\n {\n // Invoke handler in the target dispatcher's thread\n dispatcherObject.Dispatcher.Invoke(DispatcherPriority.DataBind, handler, this, e);\n }\n else // Execute handler as is\n handler(this, e);\n }\n }\n}\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
187,073
|
<p>I'm using the sortable function in jquery to sequence a faq list. Needless to say, i'm new to this concept. Anybody have any good examples of the backend for this. I have the front working fine, but updating the sequence in the database is another story. My backend is ColdFusion btw.</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 187111,
"author": "Tomasz Tybulewicz",
"author_id": 17405,
"author_profile": "https://Stackoverflow.com/users/17405",
"pm_score": 5,
"selected": true,
"text": "<div id=\"faq\">\n <div id=\"q1\">...</div>\n <div id=\"q2\">...</div>\n (...)\n <div id=\"q100\">..</div>\n</div>\n <script type=\"text/javascript\">\n $(\"#faq\").sortable();\n</script>\n <form action=\"...\" id=\"faq_form\">\n <input type=\"hidden\" name=\"faqs\" id=\"faqs\" />\n ...\n</form>\n <script type=\"text/javascript>\n $(\"#faq_form\").submit(function() {\n $(\"#faqs\").val($(\"#faq\").sortable('toArray'))\n })\n</script>\n"
},
{
"answer_id": 3228140,
"author": "Mohammad Faheem",
"author_id": 389205,
"author_profile": "https://Stackoverflow.com/users/389205",
"pm_score": 2,
"selected": false,
"text": " <link href=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css\" rel=\"stylesheet\" type=\"text/css\"/>` <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"></script>`<script src=\"http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js\"></script>``\n <div id=\"target\">\n <div style=\"cursor: move;\" class=\"entity\">\n <div class=\"digit\"><span>1</span><tab /> First Item </div> \n </div> \n <div style=\"cursor: move;\" class=\"entity\">\n <div class=\"digit\"><span>2</span> Second Item</div> \n </div> \n <div style=\"cursor: move;\" class=\"entity\">\n <div class=\"digit\"><span>3</span> Third Item</div> \n </div>\n <div style=\"cursor: move;\" class=\"entity\">\n <div class=\"digit\"><span>4</span> Fourth Item</div> \n </div>\n <div style=\"cursor: move;\" class=\"entity\">\n <div class=\"digit\"><span>5</span> Fifth Item</div> \n </div>\n</div>\n $(document).ready(function() {\n $('#target').sortable({\n items:'div.entity', //the div which we want to make sortable \n scroll:true, //If set to true, the page \n //scrolls when coming to an edge.\n update:function(event,ui){ renumber(); } //This event is triggered when the user \n //stopped sorting and the DOM position has changed.\n });\n});\n function renumber()\n{\n $('.digit span').each(function(index,element) {\n $(element).html(index+1);\n });\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
187,076
|
<p>I have a CSV file that holds about 200,000 - 300,000 records. Most of the records can be separated and inserted into a MySQL database with a simple </p>
<pre><code>$line = explode("\n", $fileData);
</code></pre>
<p>and then the values separated with</p>
<pre><code>$lineValues = explode(',', $line);
</code></pre>
<p>and then inserted into the database using the proper data type i.e int, float, string, text, etc.</p>
<p>However, some of the records have a text column that includes a \n in the string. Which breaks when using the $line = explode("\n", $fileData); method. Each line of data that needs to be inserted into the database has approximately 216 columns. not every line has a record with a \n in the string. However, each time a \n is found in the line it is enclosed between a pair of single quotes (')</p>
<p>each line is set up in the following format:</p>
<pre><code>id,data,data,data,text,more data
</code></pre>
<p>example:</p>
<pre><code>1,0,0,0,'Hello World,0
2,0,0,0,'Hello
World',0
3,0,0,0,'Hi',0
4,0,0,0,,0
</code></pre>
<p>As you can see from the example, most records can be easily split with the methods shown above. Its the second record in the example that causes the problem.</p>
<p>New lines are only \n and the file does not include \r in the file at all.</p>
|
[
{
"answer_id": 187091,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": -1,
"selected": false,
"text": "// Replace all new-line then id patterns with new-line 0+id\n$line = preg_replace('/\\n(\\d)/',\"\\n0$1\",$line);\n\n// Split on new-line then id\n$linevalues = preg_split(\"/\\n\\d/\",$data);\n preg_split"
},
{
"answer_id": 187101,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 2,
"selected": true,
"text": "# Split file into physical lines (records may span lines)\n$lines = explode(\"\\n\", $fileData);\n\n# Re-assemble records\n$records = array ();\n$record = '';\n$lineSep = '';\nforeach ($lines as $line) {\n # Escape @ symbol so we can use it as a marker (as it does not conflict with\n # any special CSV character.)\n $line = str_replace('@', '@a', $line);\n\n # Escape commas as we don't yet know which ones are separators\n $line = str_replace(',', '@c', $line);\n\n # Escape quotes in a form that uses no special characters\n $line = str_replace(\"\\\\'\", '@q', $line);\n $line = str_replace('\\\\', '@b', $line);\n\n $record .= $lineSep . $line;\n $lineSep = \"\\n\";\n\n # Must have an even number of quotes in a complete record!\n if (substr_count($record, \"'\") % 2 == 0) {\n $records[] = $record;\n $record = '';\n $lineSep = '';\n }\n}\nif (strlen($record) > 0) {\n $records[] = $record;\n}\n\n$rows = array ();\n\nforeach ($records as $record) {\n $chunks_in = explode(\"'\", $record);\n $chunks_out = array ();\n\n # Decode escaped quotes/backslashes.\n # Decode field-separating commas (unless quoted)\n foreach ($chunks_in as $i => $chunk) {\n # Unescape quotes & backslashes\n $chunk = str_replace('@q', \"'\", $chunk);\n $chunk = str_replace('@b', '\\\\', $chunk);\n if ($i % 2 == 0) {\n # Unescape commas\n $chunk = str_replace('@c', ',', $chunk);\n }\n $chunks_out[] = $chunk;\n }\n\n # Join back together, discarding unescaped quotes\n $record = join('', $chunks_out);\n\n $chunks_in = explode(',', $record);\n $row = array ();\n foreach ($chunks_in as $chunk) {\n $chunk = str_replace('@c', ',', $chunk);\n $chunk = str_replace('@a', '@', $chunk);\n $row[] = $chunk;\n }\n $rows[] = $row;\n}\n"
},
{
"answer_id": 187122,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 1,
"selected": false,
"text": "explode()"
},
{
"answer_id": 187186,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 0,
"selected": false,
"text": "fgetcsv"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24802/"
] |
187,098
|
<p>I am writing a dhtml application that creates an interactive simulation of a system. The data for the simulation is generated from another tool, and there is already a very large amount of legacy data.</p>
<p>Some steps in the simulation require that we play "voice-over" clips of audio. I've been unable to find an easy way to accomplish this across multiple browsers. </p>
<p><a href="http://www.schillmania.com/projects/soundmanager2/" rel="noreferrer">Soundmanager2</a> comes pretty close to what I need, but it will only play mp3 files, and the legacy data may contain some .wav files as well. </p>
<p>Does anyone have any other libraries that might help?</p>
|
[
{
"answer_id": 187415,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 7,
"selected": true,
"text": "//======================================================================\nvar soundEmbed = null;\n//======================================================================\nfunction soundPlay(which)\n {\n if (!soundEmbed)\n {\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n }\n else\n {\n document.body.removeChild(soundEmbed);\n soundEmbed.removed = true;\n soundEmbed = null;\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n }\n soundEmbed.removed = false;\n document.body.appendChild(soundEmbed);\n }\n//======================================================================\n"
},
{
"answer_id": 1935187,
"author": "joshoreefe",
"author_id": 235405,
"author_profile": "https://Stackoverflow.com/users/235405",
"pm_score": 3,
"selected": false,
"text": "var soundEmbed = null;\n//=====================================================================\n\nfunction soundPlay(which)\n{\n if (soundEmbed)\n document.body.removeChild(soundEmbed);\n soundEmbed = document.createElement(\"embed\");\n soundEmbed.setAttribute(\"src\", \"/snd/\"+which+\".wav\");\n soundEmbed.setAttribute(\"hidden\", true);\n soundEmbed.setAttribute(\"autostart\", true);\n document.body.appendChild(soundEmbed);\n}\n"
},
{
"answer_id": 3885939,
"author": "Alon Gubkin",
"author_id": 140937,
"author_profile": "https://Stackoverflow.com/users/140937",
"pm_score": 3,
"selected": false,
"text": "<audio>"
},
{
"answer_id": 7760017,
"author": "Howard",
"author_id": 459778,
"author_profile": "https://Stackoverflow.com/users/459778",
"pm_score": 3,
"selected": false,
"text": "function Play(sound) {\n $(\"#sound_\").remove()\n $('body').append('<embed id=\"sound_\" autostart=\"true\" hidden=\"true\" src=\"/static/sound/' + sound + '.wav\" />');\n}\n"
},
{
"answer_id": 13807759,
"author": "Andrew Mackenzie",
"author_id": 573149,
"author_profile": "https://Stackoverflow.com/users/573149",
"pm_score": 2,
"selected": false,
"text": "<audio controls>\n <source src=\"horse.ogg\" type=\"audio/ogg\">\n <source src=\"horse.mp3\" type=\"audio/mpeg\">\nYour browser does not support the audio element.\n</audio>\n"
},
{
"answer_id": 59308578,
"author": "Hugo",
"author_id": 3214497,
"author_profile": "https://Stackoverflow.com/users/3214497",
"pm_score": 0,
"selected": false,
"text": "<audio> <embed>"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22383/"
] |
187,100
|
<p>I have an object that needs a test if the object data is valid. The validation itself would be called from the thread that instatiated the object, it looks like this:</p>
<pre><code> {
if (_step.Equals(string.Empty)) return false;
if (_type.Equals(string.Empty)) return false;
if (_setup.Equals(string.Empty)) return false;
return true;
}
</code></pre>
<p>Would it be better to implement this as a property, or as a method, and why? I have read the answers to a <a href="https://stackoverflow.com/questions/164023/what-guidelines-are-appropriate-for-determining-when-to-implement-a-class-membe">related question</a>, but I don't think this specific question is covered there.</p>
|
[
{
"answer_id": 187110,
"author": "Gregor",
"author_id": 26153,
"author_profile": "https://Stackoverflow.com/users/26153",
"pm_score": 1,
"selected": false,
"text": "if(something.IsValid) { ...\n if(something.IsValid()) { ...\n"
},
{
"answer_id": 187118,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "if (_step == \"\")) return false;\nif (_type == \"\")) return false;\nif (_setup == \"\")) return false;\n null if (string.IsNullOrEmpty(_step)) return false;\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
] |
187,120
|
<p>I cannot add workflow item to my WPF project.</p>
<p>I create a new WPF project and want to add a sequential workflow. When I do "Add new item" there is no item template to select.</p>
<p>Any hints?</p>
|
[
{
"answer_id": 2583629,
"author": "Nitin Mohnani",
"author_id": 309857,
"author_profile": "https://Stackoverflow.com/users/309857",
"pm_score": 1,
"selected": false,
"text": "devenv /installvstemplates\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2374/"
] |
187,125
|
<p>Trying to create a user account in a test. But getting a Object reference is not set to an instanve of an object error when running it.</p>
<p>Here's my MemberShip provider class, it's in a class library MyCompany.MyApp.Domain.dll:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Web.Security;
namespace MyCompany.MyApp.Domain
{
public class MyMembershipProvider : SqlMembershipProvider
{
const int defaultPasswordLength = 8;
private int resetPasswordLength;
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
resetPasswordLength = defaultPasswordLength;
string resetPasswordLengthConfig = config["resetPasswordLength"];
if (!String.IsNullOrEmpty(resetPasswordLengthConfig))
{
config.Remove("resetPasswordLength");
if (!int.TryParse(resetPasswordLengthConfig, out resetPasswordLength))
{
resetPasswordLength = defaultPasswordLength;
}
}
base.Initialize(name, config);
}
public override string GeneratePassword()
{
return Utils.PasswordGenerator.GeneratePasswordAsWord(resetPasswordLength);
}
}
}
</code></pre>
<p>Here's my App.Config for my seperate Test Class Library MyCompany.MyApp.Doman.Test.dll that references my business domain library above:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SqlServer" connectionString="data source=mycomp\SQL2008;Integrated Security=SSPI;Initial Catalog=myDatabase" providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership defaultProvider="MyMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear/>
<add name="MyMembershipProvider"
type="MyCompany.MyApp.Domain.MyMembershipProvider,MyCompany.MyApp.Domain"
connectionStringName="SqlServer"
applicationName="MyApp"
minRequiredNonalphanumericCharacters="0"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"/>
</providers>
</membership>
</system.web>
</configuration>
</code></pre>
<p>Here's my method that throws "Object reference is not set to an instanve of an object"</p>
<pre><code>public class MemberTest
{
public static void CreateAdminMemberIfNotExists()
{
MembershipCreateStatus status;
status = MembershipCreateStatus.ProviderError;
MyMembershipProvider provider = new MyMembershipProvider();
provider.CreateUser("Admin", "password", "someone@somewhere.co.uk", "Question", "Answer", true, Guid.NewGuid(), out status);
}
}
</code></pre>
<p>it throws on the provider.CreateUser line</p>
|
[
{
"answer_id": 190658,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 1,
"selected": false,
"text": "public class MemberTest\n {\n public static void CreateAdminMemberIfNotExists()\n {\n MembershipCreateStatus status;\n MembershipUser member = Membership.CreateUser(\"Admin\", \"password\", \"email@somewhere.co.uk\", \"Question\", \"Answer\", true, out status);\n }\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2083160/"
] |
187,137
|
<p>This is my query:</p>
<pre><code>$query = $this->db->query('
SELECT archives.id, archives.signature, type_of_source.description, media_type.description, origin.description
FROM archives, type_of_source, media_type, origin
WHERE archives.type_of_source_id = type_of_source.id
AND type_of_source.media_type_id = media_type.id
AND archives.origin_id = origin.id
ORDER BY archives.id ASC
');
</code></pre>
<p>But how to output the result? This works, but only gets the last description (origin.description):</p>
<pre><code>foreach ($query->result_array() as $row)
{
echo $row['description'];
}
</code></pre>
<p>This doesn't work: </p>
<pre><code>foreach ($query->result_array() as $row)
{
echo $row['type_of_source.description'];
}
</code></pre>
<p>Or should I rename the columns (e.g. type_of_source_description)?</p>
|
[
{
"answer_id": 187175,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 4,
"selected": true,
"text": "\"AS\" select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....\n"
},
{
"answer_id": 187376,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "\"SELECT\""
},
{
"answer_id": 289871,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "AS"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187137",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4196/"
] |
187,138
|
<p>How would you store formatted blocks of text (line breaks, tabs, lists - etc.) in a database (nothing specific) to be displayed on the web (XHTML) while maintaining a level of abstraction so that the data can be used in other applications or if the structure of the website were to change in the future?</p>
|
[
{
"answer_id": 187175,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 4,
"selected": true,
"text": "\"AS\" select type_of_source.description as type_of_source_description, origin.descripotion as origin_descripotion from ....\n"
},
{
"answer_id": 187376,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 2,
"selected": false,
"text": "\"SELECT\""
},
{
"answer_id": 289871,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "AS"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23746/"
] |
187,146
|
<p>Why is the order of tables important when combining an outer & an inner join ?
the following fails with postgres:</p>
<pre><code>SELECT grp.number AS number,
tags.value AS tag
FROM groups grp,
insrel archiverel
LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber
LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber
WHERE archiverel.snumber = 11128188 AND
archiverel.dnumber = grp.number
</code></pre>
<p>with result:</p>
<pre><code>ERROR: invalid reference to FROM-clause entry for table "grp" LINE 5: LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.d...
^ HINT: There is an entry for table "grp", but it cannot be referenced from this part of the query.
</code></pre>
<p>when the groups are reversed in the FROM it all works:</p>
<pre><code>SELECT grp.number AS number,
tags.value AS tag
FROM insrel archiverel,
groups grp
LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber
LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber
WHERE archiverel.snumber = 11128188 AND
archiverel.dnumber = grp.number
</code></pre>
|
[
{
"answer_id": 187184,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "SELECT grp.number AS number, \n tags.value AS tag \nFROM groups grp\nJOIN insrel archiverel ON archiverel.dnumber = grp.number\nLEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \nWHERE archiverel.snumber = 11128188\n"
},
{
"answer_id": 187275,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM a, b JOIN c ON a.x = c.x\n SELECT * FROM a, (b JOIN c on a.x = c.x)\n SELECT * FROM b, (a JOIN c on a.x = c.x)\n"
},
{
"answer_id": 187277,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 5,
"selected": true,
"text": "FROM groups grp,\n insrel archiverel \nLEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \n FROM groups grp,\n(\n (\n insrel archiverel \n LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \n )\nLEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber\n)\n FROM groups grp\n JOIN insrel archiverel ON archiverel.dnumber = grp.number\n LEFT OUTER JOIN ownrel ownrel ON grp.number = ownrel.dnumber \n LEFT OUTER JOIN tags tags ON tags.number = ownrel.snumber \nWHERE archiverel.snumber = 11128188\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26486/"
] |
187,188
|
<p>We are hosting a site for a client and they want us to include the header they have on their server into the pages we are hosting. So whenever they change it, it will automatically change on our site.</p>
<p>We are attempting to use the "include" tag in our JSP code. The code we are using is as follows:</p>
<p><code><%@ include file="www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %></code></p>
<p>We also tried </p>
<p><code><%@ include file="**http://**www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html" %></code></p>
<p>Unfortunately these aren't working for us. What seems to be happening is that the code is ONLY looking locally for this file and never seems to go "outside" to look for it.</p>
<p>We are able to pull the header into our page when we use an iframe but because of the way the header is constructed/coded the mouse over drop-down menus aren't working
as they should when we use the iframe. The drop-down menus are "cascading" underneath the rest of the content on the page and we weren't able to bring
them to the "top". </p>
<p>As a temporary work around, were are hosting the HTML on our own servers.</p>
<p>Any ideas? </p>
|
[
{
"answer_id": 187201,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 1,
"selected": false,
"text": "out include"
},
{
"answer_id": 187230,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 3,
"selected": true,
"text": "public static String fetchSourceHtml( String urlString ) {\n\n try {\n HttpClient httpClient = new HttpClient();\n GetMethod getMethod = new GetMethod( urlString );\n getMethod.setFollowRedirects( true );\n\n int httpStatus = httpClient.executeMethod( getMethod );\n\n if (httpStatus >= 400) {\n return \"\";\n }\n\n String sourceHtml = getMethod.getResponseBodyAsString();\n return sourceHtml;\n }\n catch (IOException e) {\n return \"\";\n }\n}\n"
},
{
"answer_id": 187338,
"author": "Keeg",
"author_id": 21059,
"author_profile": "https://Stackoverflow.com/users/21059",
"pm_score": 1,
"selected": false,
"text": "<c:import url=\"http://www.CLIENT.com/CLIENT2/MiddlePageFiles/Vendor_header.html\" />\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26488/"
] |
187,198
|
<p>I was thinking earlier today about an idea for a small game and stumbled upon how to implement it. The idea is that the player can make a series of moves that cause a little effect, but if done in a specific sequence would cause a greater effect. So far so good, this I know how to do. Obviously, I had to make it be more complicated (because we love to make it more complicated), so I thought that there could be more than one possible path for the sequence that would both cause greater effects, albeit different ones. Also, part of some sequences could be the beggining of other sequences, or even whole sequences could be contained by other bigger sequences. Now I don't know for sure the best way to implement this. I had some ideas, though.</p>
<p>1) I could implement a circular n-linked list. But since the list of moves never end, I fear it might cause a stack overflow ™. The idea is that every node would have n children and upon receiving a command, it might lead you to one of his children or, if no children was available to such command, lead you back to the beggining. Upon arrival on any children, a couple of functions would be executed causing the small and big effect. This might, though, lead to a lot of duplicated nodes on the tree to cope up with all the possible sequences ending on that specific move with different effects, which might be a pain to maintain but I am not sure. I never tried something this complex on code, only theoretically. Does this algorithm exist and have a name? Is it a good idea?</p>
<p>2) I could implement a state machine. Then instead of wandering around a linked list, I'd have some giant nested switch that would call functions and update the machine state accordingly. Seems simpler to implement, but... well... doesn't seem fun... nor ellegant. Giant switchs always seem ugly to me, but would this work better? </p>
<p>3) Suggestions? I am good, but I am far inexperienced. The good thing of the coding field is that no matter how weird your problem is, someone solved it in the past, but you must know where to look. Someone might have a better idea than those I had, and I really wanted to hear suggestions.</p>
|
[
{
"answer_id": 187350,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 3,
"selected": true,
"text": "MagicSequence fireworks = new MagicSequence(new FireworksAction(), 1, 1, 7);\nMagicSequence playMusic = new MagicSequence(new MusicAction(), 4, 6, 8);\nMagicSequence fixUserADrink = new MagicSequence(new ManhattanAction(), 4, 1, 1, 7, 9, 9);\n\nCollection<MagicSequence> sequences = ... all of the above ...;\n\nwhile (true) {\n int num = readNumberFromUser();\n for (MagicSequence seq : sequences) {\n seq.handleNumber(num);\n }\n}\n Action action = ... populated from constructor ...;\nint[] sequence = ... populated from constructor ...;\nint position = 0;\n\npublic void handleNumber(int num) {\n if (num == sequence[position]) {\n // They've entered the next number in the sequence\n position++;\n if (position == sequence.length) {\n // They've got it all!\n action.fire();\n position = 0; // Or disable this Sequence from accepting more numbers if it's a once-off\n }\n } else {\n position = 0; // missed a number, start again!\n }\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5954/"
] |
187,216
|
<p>What is the best way for converting phone numbers into international format (E.164) using Java?</p>
<p>Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number.</p>
<p>I am sure I can do it by hand quite easily - but I would not be sure it would work correctly in all situations.</p>
<p>Which Java framework/library/utility would you recommend to accomplish this?</p>
<p>P.S. The 'phone number' could be anything identifiable by the general public - such as</p>
<pre><code>* (510) 786-0404
* 1-800-GOT-MILK
* +44-(0)800-7310658
</code></pre>
<p>that last one is my favourite - it is how some people write their number in the UK and means that you should either use the +44 or you should use the 0.</p>
<p>The E.164 format number should be all numeric, and use the full international country code (e.g.+44)</p>
|
[
{
"answer_id": 195093,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 0,
"selected": false,
"text": "CC AREA_CODE AREA_CODE_LENGTH SUBSCRIBER SUBSCRIBER_LENGTH\n64 1 7\n64 21 2 7\n64 275 3 6\n"
},
{
"answer_id": 5264810,
"author": "Collin Peters",
"author_id": 354767,
"author_profile": "https://Stackoverflow.com/users/354767",
"pm_score": 7,
"selected": true,
"text": "String swissNumberStr = \"044 668 18 00\"\nPhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();\ntry {\n PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, \"CH\");\n} catch (NumberParseException e) {\n System.err.println(\"NumberParseException was thrown: \" + e.toString());\n}\n\n// Produces \"+41 44 668 18 00\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.INTERNATIONAL));\n// Produces \"044 668 18 00\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.NATIONAL));\n// Produces \"+41446681800\"\nSystem.out.println(phoneUtil.format(swissNumberProto, PhoneNumberFormat.E164));\n"
},
{
"answer_id": 7687504,
"author": "arksoft",
"author_id": 312939,
"author_profile": "https://Stackoverflow.com/users/312939",
"pm_score": 2,
"selected": false,
"text": "public static String FixPhoneNumber(Context ctx, String rawNumber)\n{\n String fixedNumber = \"\";\n\n // get current location iso code\n TelephonyManager telMgr = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);\n String curLocale = telMgr.getNetworkCountryIso().toUpperCase();\n\n PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();\n Phonenumber.PhoneNumber phoneNumberProto;\n\n // gets the international dialling code for our current location\n String curDCode = String.format(\"%d\", phoneUtil.getCountryCodeForRegion(curLocale));\n String ourDCode = \"\";\n\n if(rawNumber.indexOf(\"+\") == 0)\n {\n int bIndex = rawNumber.indexOf(\"(\");\n int hIndex = rawNumber.indexOf(\"-\");\n int eIndex = rawNumber.indexOf(\" \");\n\n if(bIndex != -1)\n {\n ourDCode = rawNumber.substring(1, bIndex);\n }\n else if(hIndex != -1) \n { \n ourDCode = rawNumber.substring(1, hIndex);\n }\n else if(eIndex != -1)\n {\n ourDCode = rawNumber.substring(1, eIndex);\n }\n else\n {\n ourDCode = curDCode;\n } \n }\n else\n {\n ourDCode = curDCode;\n }\n\n try \n {\n phoneNumberProto = phoneUtil.parse(rawNumber, curLocale);\n } \n\n catch (NumberParseException e) \n {\n return rawNumber;\n }\n\n if(curDCode.compareTo(ourDCode) == 0)\n fixedNumber = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.NATIONAL);\n else\n fixedNumber = phoneUtil.format(phoneNumberProto, PhoneNumberFormat.INTERNATIONAL);\n\n return fixedNumber.replace(\" \", \"\");\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15452/"
] |
187,219
|
<p>I'm using ccl/openmcl on Mac OS X. (latest versions of both). When the lisp prompt is displayed, using the cursor keys to navigate the current line results in escape codes, rather than movement, eg:</p>
<p><code>Welcome to Clozure Common Lisp Version 1.2-r9226-RC1 (DarwinX8664)!<br>
? (^[[D</code></p>
<p>Here I've pressed the <code>(</code> key, and then the <code>left cursor</code> key.</p>
<p>When I run ccl/openmcl on a Debian Etch box, the cursor behaves as expected, and moves the insert point one position left.</p>
<p>I guess this is some sort of terminal configuration option?</p>
|
[
{
"answer_id": 187393,
"author": "Matthias Benkard",
"author_id": 15517,
"author_profile": "https://Stackoverflow.com/users/15517",
"pm_score": 3,
"selected": true,
"text": "rlwrap openmcl\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10019/"
] |
187,229
|
<p>Why does this work:</p>
<pre><code>$(window).keydown(function(event){
alert(event.keyCode);
});
</code></pre>
<p>but not this:</p>
<pre><code>$('#ajaxSearchText').keydown(function(event){
alert(event.keyCode);
});
</code></pre>
<p>I'm testing with Firefox 3.
Interestingly, neither of them work in IE7.</p>
|
[
{
"answer_id": 187262,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": 1,
"selected": false,
"text": "$('#ajaxSearchText').keyup(function(event){\n alert(event.keyCode);\n});\n"
},
{
"answer_id": 190205,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 4,
"selected": true,
"text": "<html> \n <head> \n <script type=\"text/javascript\" src=\"jquery-1.2.6.js\"></script> \n <script type=\"text/javascript\"> \n $(function() \n {\n $(\"#ajaxSearchText\").keydown(function(event)\n {\n alert(event.keyCode);\n });\n });\n </script> \n </head> \n <body> \n <input type=\"text\" id=\"ajaxSearchText\"></input>\n </body> \n</html> \n"
},
{
"answer_id": 338157,
"author": "Rik Heywood",
"author_id": 4012,
"author_profile": "https://Stackoverflow.com/users/4012",
"pm_score": 2,
"selected": false,
"text": "$(function() \n{\n $(document).keydown(function(event){\n alert(event.keyCode);\n });\n});\n $(document)"
},
{
"answer_id": 6114797,
"author": "Kristian",
"author_id": 680578,
"author_profile": "https://Stackoverflow.com/users/680578",
"pm_score": 0,
"selected": false,
"text": "$('#searchInput').keydown(function() {\n alert('testing');\n});\n $(function()\n{\n $('#searchInput').keydown(function() {\n alert('testing');\n });\n});\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
187,231
|
<p>I'm having trouble selecting elements that are part of an specific namespace. My xpath expression works in XMLSpy but fails when using the Xalan libraries..</p>
<pre><code><item>
<media:content attrb="xyz">
<dcterms:valid>VALUE</dcterms:valid>
</media:content>
</item>
</code></pre>
<p>My expression is <code>./item/media:content/dcterms:valid</code>. I've already added both namespace definitions to my XSLT. Again, this selects the right values in XMLSpy but fails when running through Xalan library.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 187339,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 0,
"selected": false,
"text": "<item xmlns:dcterms=\"http://dcterms.example\" xmlns:media=\"http://media.example\">\n <media:content attrb=\"xyz\">\n <dcterms:valid>VALUE</dcterms:valid>\n </media:content>\n</item>\n"
},
{
"answer_id": 195816,
"author": "Michael Hall",
"author_id": 7156,
"author_profile": "https://Stackoverflow.com/users/7156",
"pm_score": 1,
"selected": false,
"text": "org.apache.xml.utils.PrefixResolver XPath javax.xml.namespace.NamespaceContext"
},
{
"answer_id": 195831,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 0,
"selected": false,
"text": "/*[local-name()='NewHireList' and namespace-uri()='http://BRE.NewHireList']/*[local-name()='Record' and namespace-uri()='']\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10913/"
] |
187,237
|
<p>I have a .NET string which is Base64 encoded representation of an array of encrypted bytes. It is produced like this:</p>
<pre><code>String Encrypt( String message )
{
CryptoStream cryptostream = ...
StreamWriter stream = new StreamWriter( cryptostream );
...
return Convert.ToBase64String( ... );
}
</code></pre>
<p>Now I want a decryption function like</p>
<pre><code>String Decrypt( String cypher )
{
TextReader reader = new StringReader( cypher );
byte[] buffer = new byte[ cypher.Length ];
for( int i = 0; i < cypher.Length; ++i )
{
buffer[ i ] = (byte) reader.Read();
}
FromBase64Transform transformer = new FromBase64Transform();
MemoryStream raw = new MemoryStream
(
transformer.TransformFinalBlock( buffer, 0, buffer.Length )
);
...
}
</code></pre>
<p>Is there a way to use FromBase64Transform <em>directly</em> with CryptoStream (as the .NET documentation suggests), instead of manually converting the string to bytes, then manually decoding the bytes, and finally decrypting the decoded bytes?</p>
|
[
{
"answer_id": 191630,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 2,
"selected": true,
"text": " public static string DeCryptString(string s) {\n byte[] b = System.Convert.FromBase64String(s);\n\n using (MemoryStream ms = new MemoryStream(b)) \n using (CryptoStream cs = /* Create decrypting stream here */)\n using (StreamReader sr = new StreamReader(cs)) {\n string buf = sr.ReadToEnd();\n return buf;\n }\n } // DeCryptString\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13372/"
] |
187,245
|
<p>Where I work, we maintain an FTP site that needs occasional cleanup.</p>
<p>Are there any tools out there to create a site map of an FTP site? It would greatly simplify clean up tasks.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 191630,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 2,
"selected": true,
"text": " public static string DeCryptString(string s) {\n byte[] b = System.Convert.FromBase64String(s);\n\n using (MemoryStream ms = new MemoryStream(b)) \n using (CryptoStream cs = /* Create decrypting stream here */)\n using (StreamReader sr = new StreamReader(cs)) {\n string buf = sr.ReadToEnd();\n return buf;\n }\n } // DeCryptString\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1145/"
] |
187,255
|
<p>I'm trying to make a select that calculates affiliate payouts.</p>
<p>my approach is pretty simple.</p>
<pre><code>SELECT
month(payments.timestmap)
,sum(if(payments.amount>=29.95,4,0)) As Tier4
,sum(if(payments.amount>=24.95<=29.94,3,0)) As Tier3
,sum(if(payments.amount>=19.95<=24.94,2,0)) As Tier2
FROM payments
GROUP BY month(payments.timestamp)
</code></pre>
<p>The above does not work because MySQL is not evaluating the second part of the condition. Btw it does not cause a syntax error and the select will return results.</p>
<p>Before the above I tried what I was assuming would work like "<code>amount between 24.94 AND 29.94</code>" this caused an error. so then I tried "<code>amount >= 24.94 AND <= 29.94</code>" </p>
<p>So is it possible to have a range comparison using IF in MySql?</p>
|
[
{
"answer_id": 187270,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "AND SELECT\n month(payments.timestmap)\n,sum(if(payments.amount>=29.95,4,0)) As Tier4\n,sum(if(payments.amount>=24.95 AND payments.amount<=29.94,3,0)) As Tier3\n,sum(if(payments.amount>=19.95 AND payments.amount<=24.94,2,0)) As Tier2\nFROM payments\nGROUP BY month(payments.timestamp)\n between"
},
{
"answer_id": 187285,
"author": "KernelM",
"author_id": 22328,
"author_profile": "https://Stackoverflow.com/users/22328",
"pm_score": 1,
"selected": false,
"text": "amount >= 24.94 and amount <= 29.94"
},
{
"answer_id": 7584892,
"author": "geilt",
"author_id": 849560,
"author_profile": "https://Stackoverflow.com/users/849560",
"pm_score": 1,
"selected": false,
"text": "SELECT\nmonth( payments.timestamp )\n,sum( if( payments.amount >= 29.95, 4, 0 ) ) As Tier4\n,sum( if( payments.amount BETWEEN 24.95 AND 29.94, 3, 0 ) ) As Tier3\n,sum( if( payments.amount BETWEEN 19.95 AND 24.94, 2, 0 ) ) As Tier2\nFROM payments\nGROUP BY month( payments.timestamp )\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
187,273
|
<p>Building on <a href="https://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. </p>
<pre><code>def num_bin(N, places=8):
def bit_at_p(N, p):
''' find the bit at place p for number n '''
two_p = 1 << p # 2 ^ p, using bitshift, will have exactly one
# bit set, at place p
x = N & two_p # binary composition, will be one where *both* numbers
# have a 1 at that bit. this can only happen
# at position p. will yield two_p if N has a 1 at
# bit p
return int(x > 0)
bits = ( bit_at_p(N,x) for x in xrange(places))
return "".join( (str(x) for x in bits) )
# or, more consisely
# return "".join([str(int((N & 1 << x)>0)) for x in xrange(places)])
</code></pre>
|
[
{
"answer_id": 187536,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "def _bin(x, width):\n return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1))\n _conv_table = [_bin(x,8) for x in range(256)]\n def bin(x):\n if x == 0: \n return '0' #Special case: Don't strip leading zero if no other digits\n elif x < 0:\n sign='-'\n x*=-1\n else:\n sign = ''\n l=[]\n while x:\n l.append(_conv_table[x & 0xff])\n x >>= 8\n return sign + ''.join(reversed(l)).lstrip(\"0\")\n Num Bits: 8 16 32 64 128 256\n---------------------------------------------------------------------\nbin 0.544 0.586 0.744 1.942 1.854 3.357 \nbin16 0.542 0.494 0.592 0.773 1.150 1.886\nconstantin_bin 2.238 3.803 7.794 17.869 34.636 94.799\nnum_bin 3.712 5.693 12.086 32.566 67.523 128.565\nPython3's bin 0.079 0.045 0.062 0.069 0.212 0.201 \n"
},
{
"answer_id": 189579,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 2,
"selected": false,
"text": ">>> def bin(x):\n... sign = '-' if x < 0 else ''\n... x = abs(x)\n... bits = []\n... while x:\n... x, rmost = divmod(x, 2)\n... bits.append(rmost)\n... return sign + ''.join(str(b) for b in reversed(bits or [0]))\n num_bin >>> import timeit\n>>> t_bin = timeit.Timer('bin(0xf0)', 'from __main__ import bin')\n>>> print t_bin.timeit(number=100000)\n4.19453350997\n>>> t_num_bin = timeit.Timer('num_bin(0xf0)', 'from __main__ import num_bin')\n>>> print t_num_bin.timeit(number=100000)\n4.70694716882\n >>> bin(1)\n'1'\n>>> num_bin(1)\n'10000000'\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15842/"
] |
187,279
|
<p>I want to create a simple box with a header bar containing a title and some tool buttons. I have the following markup:</p>
<pre><code><div style="float:left">
<div style="background-color:blue; padding: 1px; height: 20px;">
<div style="float: left; background-color:green;">title</div>
<div style="float: right; background-color:yellow;">toolbar</div>
</div>
<div style="clear: both; width: 200px; background-color: red;">content</div>
</div>
</code></pre>
<p>This renders fine in Firefox and Chrome:</p>
<p><a href="http://www.boplicity.nl/images/firefox.jpg">http://www.boplicity.nl/images/firefox.jpg</a></p>
<p>However IE7 totally messes up and puts the right floated element to the right of the page:</p>
<p><a href="http://www.boplicity.nl/images/ie7.jpg">http://www.boplicity.nl/images/ie7.jpg</a></p>
<p>Can this be fixed?</p>
|
[
{
"answer_id": 187311,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": -1,
"selected": false,
"text": "<div style=\"background-color:blue; padding: 1px; height: 20px;> clear:all"
},
{
"answer_id": 187313,
"author": "Marko Dumic",
"author_id": 5817,
"author_profile": "https://Stackoverflow.com/users/5817",
"pm_score": 6,
"selected": true,
"text": "<div style=\"float:left; width: 200px;\">\n <div style=\"background-color:blue; padding: 1px; height: 20px;\">\n <div style=\"float: left; background-color:green;\">title</div>\n <div style=\"float: right; background-color:yellow;\">toolbar</div>\n </div>\n <div style=\"clear: both; background-color: red;\">content</div>\n</div>\n"
},
{
"answer_id": 187860,
"author": "Sam Murray-Sutton",
"author_id": 2977,
"author_profile": "https://Stackoverflow.com/users/2977",
"pm_score": 2,
"selected": false,
"text": "<div style=\"float:left; min-width: 200px;\">\n <div style=\"background-color:blue; padding: 1px; height: 20px;\">\n <div style=\"float: left; background-color:green;\">title</div>\n <div style=\"float: right; background-color:yellow;\">toolbar</div>\n </div>\n <div style=\"clear: both; background-color: red;\">content</div>\n</div>\n"
},
{
"answer_id": 1040518,
"author": "Kees de Kooter",
"author_id": 26496,
"author_profile": "https://Stackoverflow.com/users/26496",
"pm_score": 2,
"selected": false,
"text": " // IE fix for div widths - size header to width of content\n if (!$.support.cssFloat) {\n $(\"div:has(.boxheader) > table\").each(function () {\n $(this).parent().width($(this).width());\n });\n }\n"
},
{
"answer_id": 4174335,
"author": "Toni",
"author_id": 506928,
"author_profile": "https://Stackoverflow.com/users/506928",
"pm_score": 1,
"selected": false,
"text": "position:relative;"
},
{
"answer_id": 8760056,
"author": "Premanshu",
"author_id": 987695,
"author_profile": "https://Stackoverflow.com/users/987695",
"pm_score": 1,
"selected": false,
"text": "<div style=\"background-color:blue; padding: 1px; height: 20px;\">\n <div style=\"float: right; background-color:green;\">title</div>\n <div style=\"float: left; background-color:yellow;\">toolbar</div>\n</div>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26496/"
] |
187,284
|
<p>I have log4net running on my AsP.NET site. I'm able to log messages to my DB Table, but it isn't logging the ThreadContext properties. For example:</p>
<pre><code>ThreadContext.Properties["Url"] = HttpContext.Current.Request.Url.ToString();
ThreadContext.Properties["HttpReferer"] = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
</code></pre>
<p>My log4net.config adds those values as parameters into my SQL DB table:</p>
<pre><code><parameter>
<parameterName value="@URL"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{log4net:Url}"/>
</layout>
</parameter>
<parameter>
<parameterName value="@HttpReferer"/>
<dbType value="String"/>
<size value="512"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%property{log4net:HttpReferer}"/>
</layout>
</parameter>
</code></pre>
<p>As I debug, I see that those ThreadContext properties are being set, but they aren't getting into the DB. </p>
<p>How can I get that to work?</p>
|
[
{
"answer_id": 188730,
"author": "sgwill",
"author_id": 1204,
"author_profile": "https://Stackoverflow.com/users/1204",
"pm_score": 5,
"selected": true,
"text": "<conversionPattern value=\"%property{log4net:HttpReferer}\"/>\n <conversionPattern value=\"%property{HttpReferer}\"/>\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1204/"
] |
187,289
|
<p>Code lines per file, methods per class, cyclomatic complexity and so on. Developers resist and workaround most if not all of them! There is a good <a href="http://www.joelonsoftware.com/items/2006/08/09.html" rel="noreferrer">Joel article</a> on it (no time to find it now).</p>
<p>What code metric(s) you recommend for use to <strong>automatically</strong> identify "crappy code"?</p>
<p>What can convince most (you can't convince all of us to some crappy metric! :O) ) of developers that this code is "crap".</p>
<p>Only metrics that can be automatically measured counts!</p>
|
[
{
"answer_id": 187298,
"author": "Dandikas",
"author_id": 23436,
"author_profile": "https://Stackoverflow.com/users/23436",
"pm_score": 2,
"selected": false,
"text": "CC | TC\n\n 2 | 0% - good anyway, cyclomatic complexity too small\n\n10 | 70% - good\n\n10 | 50% - could be better\n\n10 | 20% - bad\n\n20 | 85% - good\n\n20 | 70% - could be better\n\n20 | 50% - bad\n\n...\n"
},
{
"answer_id": 187336,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 2,
"selected": false,
"text": "'Set i to 1'\nDim i as Integer = 1\n"
},
{
"answer_id": 187346,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "value > 1 -> bad (too many comments) value < 0.1 -> bad (not enough comments)"
},
{
"answer_id": 187571,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": " object num = GetABoxedInt();\n// long myLong = (long) num; // throws exception\n long myLong = Int64.Parse(num.ToString());\n long myLong = (long)(int)num;\n"
},
{
"answer_id": 187810,
"author": "Marc Bernier",
"author_id": 23569,
"author_profile": "https://Stackoverflow.com/users/23569",
"pm_score": 1,
"selected": false,
"text": "void mdLicense::SetWindows(bool Option) {\n _windows = (Option ? true: false);\n}\n"
},
{
"answer_id": 1818202,
"author": "n002213f",
"author_id": 67796,
"author_profile": "https://Stackoverflow.com/users/67796",
"pm_score": 0,
"selected": false,
"text": "TODO:"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23436/"
] |
187,295
|
<p>How do I distribute a small amount of data in a random order in a much larger volume of data?</p>
<p>For example, I have several thousand lines of 'real' data, and I want to insert a dozen or two lines of control data in a random order throughout the 'real' data.</p>
<p>Now I am not trying to ask how to use random number generators, I am asking a statistical question, I know how to generate random numbers, but my question is how do I ensure that this the data is inserted in a random order while at the same time being fairly evenly scattered through the file.</p>
<p>If I just rely on generating random numbers there is a possibility (albeit a very small one) that all my control data, or at least clumps of it, will be inserted within a fairly narrow selection of 'real' data. What is the best way to stop this from happening?</p>
<p>To phrase it another way, I want to insert control data throughout my real data without there being a way for a third party to calculate which rows are control and which are real.
<hr />
Update: I have made this a 'community wiki' so if anyone wants to edit my question so it makes more sense then go right ahead.
<hr />
Update: Let me try an example (I do not want to make this language or platform dependent as it is not a coding question, it is a statistical question).</p>
<ul><li>I have 3000 rows of 'real' data (this amount will change from run to run, depending on the amount of data the user has).</li>
<li>I have 20 rows of 'control' data (again, this will change depending on the number of control rows the user wants to use, anything from zero upwards).</li></ul>
<p>I now want to insert these 20 'control' rows <em>roughly</em> after every 150 rows or 'real' data has been inserted (3000/20 = 150). However I do not want it to be as accurate as that as I do not want the control rows to be identifiable simply based on their location in the output data.</p>
<p>Therefore I do not mind <em>some</em> of the 'control' rows being clumped together or for there to be <em>some</em> sections with very few or no 'control' rows at all, but generally I want the 'control' rows fairly evenly distributed throughout the data.</p>
|
[
{
"answer_id": 187351,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 3,
"selected": true,
"text": "N x i N/(x+1) * i + r r N/x r i 1<=i<x"
},
{
"answer_id": 187354,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 0,
"selected": false,
"text": "for (int i=0; i<numberOfExistingRows; i++)\n{ \n int r = random();\n if (r > 0.5)\n {\n InsertRandomData();\n } \n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23387/"
] |
187,305
|
<p>I am using a FormView to update an existing SQL Server record. The rows from the sqldatasource display fine in the FormView and I can edit them. When I click Update, I get the ItemUpdating event but not the ItemUpdated event and the revisions are not written to the database. </p>
<p>Can anyone help me in this please. </p>
|
[
{
"answer_id": 227942,
"author": "Matt V",
"author_id": 30456,
"author_profile": "https://Stackoverflow.com/users/30456",
"pm_score": 1,
"selected": false,
"text": "protected void myFormView_ItemUpdating(object sender, FormViewUpdateEventArgs e)\n {\n\n // remove the old values\n e.Keys.Clear();\n e.OldValues.Clear();\n e.NewValues.Clear();\n\n // set the parameter for the key\n e.Keys.Add(\"@key\", valueGoesHere);\n\n // set other parameters\n e.NewValues.Add(\"@param1\", aValue);\n e.NewValues.Add(\"@param2\", anotherValue);\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14752/"
] |
187,319
|
<p>I could use some help writing a regular expression. In my Django application, users can hit the following URL:</p>
<pre><code>http://www.example.com/A1/B2/C3
</code></pre>
<p>I'd like to create a regular expression that allows accepts any of the following as a valid URL:</p>
<pre><code>http://www.example.com/A1
http://www.example.com/A1/B2
http://www.example.com/A1/B2/C3
</code></pre>
<p>I'm guessing I need to use the "OR" conditional, but I'm having trouble getting my regex to validate. Any thoughts?</p>
<p><strong>UPDATE</strong>: Here is the regex so far. Note that I have not included the "<a href="http://www.example.com" rel="nofollow noreferrer">http://www.example.com</a>" portion -- Django handles that for me. I'm just concerned with validating 1,2, or 3 subdirectories.</p>
<pre><code>^(\w{1,20})|((\w{1,20})/(\w{1,20}))|((\w{1,20})/(\w{1,20})/(\w{1,20}))$
</code></pre>
|
[
{
"answer_id": 187392,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "http://www\\.example\\.com/A1(/B2(/C3)?)?\n"
},
{
"answer_id": 187395,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 4,
"selected": true,
"text": "| ? () http://www\\.example\\.com/A1(/B2(/C3)?)? http://www\\.example\\.com/[^/]*(/[^/]*(/[^/]*)?)? http://www.example.com/A1 /B2 /C3 /C3 /B2 [^/]* http://www\\.example\\.com/([^/]*)(/([^/]*)(/([^/]*))?)? groupnumber: content matches: 0: (http://www.example.com/dir1/dir2/dir3)\n1: (dir1)\n2: (/dir2/dir3)\n3: (dir2)\n4: (/dir3)\n5: (dir3)\n"
},
{
"answer_id": 187404,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 1,
"selected": false,
"text": " ^(\\w{1,20})(/\\w{1,20})*\n ^(\\w{1,20})(/\\w{1,20}){0,2}\n"
},
{
"answer_id": 187409,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 1,
"selected": false,
"text": "^((\\w{1,20})|((\\w{1,20})/(\\w{1,20}))|((\\w{1,20})/(\\w{1,20})/(\\w{1,20})))$\n"
},
{
"answer_id": 206123,
"author": "akaihola",
"author_id": 15770,
"author_profile": "https://Stackoverflow.com/users/15770",
"pm_score": 1,
"selected": false,
"text": "reverse() {% url %}"
},
{
"answer_id": 1167804,
"author": "Adam Nelson",
"author_id": 26235,
"author_profile": "https://Stackoverflow.com/users/26235",
"pm_score": 2,
"selected": false,
"text": "urlpatterns = patterns('',\n url(r'^(?P<object_slug1>\\w{2}/(?P<object_slug2>\\w{2}/(?P<object_slug3>\\w{2})$', direct_to_template, {\"template\": \"two_levels_deep.html\"}, name=\"two_deep\"),\n url(r'^(?P<object_slug1>\\w{2}/(?P<object_slug2>\\w{2})$', direct_to_template, {\"template\": \"one_level_deep.html\"}, name=\"one_deep\"),\n url(r'^(?P<object_slug1>\\w{2})$', direct_to_template, {\"template\": \"homepage.html\"}, name=\"home\"),\n)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
187,357
|
<p>Consider this:</p>
<pre><code>var query = from r in this._db.Recipes
where r.RecipesID == recipeID
select new { r.RecipesID, r.RecipesName };
</code></pre>
<p>How would i get individual columns in my <code>query</code> object without using a for-loop?</p>
<p>Basicly: how do I translate <code>DataTable.Rows[0]["ColumnName"]</code> into Linq syntax?</p>
|
[
{
"answer_id": 187401,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 0,
"selected": false,
"text": "\nquery.First().ColumnName\n \nvar obj = query.FirstOrDefault();\nif (obj != null)\n obj.ColumnName;\n \nvar query = from r in yourTable.AsEnumerable()\nselect r.Field<string>(\"ColumnName\");\n"
},
{
"answer_id": 187413,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "var rows = query.ToList();\nstring name = rows[0].RecipesName;\n"
},
{
"answer_id": 187507,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 2,
"selected": false,
"text": "string name = this._db.Recipes.Single(r => r.RecipesID == recipeID).RecipesName;\n"
},
{
"answer_id": 189527,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 2,
"selected": true,
"text": "DataContext dc = new DataContext();\n\nvar recipe = (from r in dc.Recipes \n where r.RecipesID == 1\n select r).FirstOrDefault();\n\nif (recipe != null)\n{\n id = recipe.RecipesID;\n name = recipe.RecipesName;\n}\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20946/"
] |
187,359
|
<p>We use Visual Studio 2008 and Surround SCM for source control. SCM drops files into each directory named ".MySCMServerInfo" which are user specific data files that shouldn't be checked into source control. They are similar to the .scc files dropped by Visual Source Safe. We also have several WAPs (Web Application Projects) that we develop. All these .MySCMServerInfo files show up in the solution tree and the Pending Checkins window when they should not. There has to be some way to force VS to ignore files of a given extension because it ignores .scc files. How do I get VS to ignore .MySCMServerInfo files within a WAP?</p>
|
[
{
"answer_id": 296353,
"author": "Charles",
"author_id": 24898,
"author_profile": "https://Stackoverflow.com/users/24898",
"pm_score": 3,
"selected": true,
"text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0\\Packages\\\n{8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\\IgnorableFiles\\.MySCMServerInfo]\n [HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\8.0\\Packages\\\n{8FF02D1A-C177-4ac8-A62F-88FC6EA65F57}\\IgnorableFiles\\.MySCMServerInfo]\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24898/"
] |
187,406
|
<pre><code>private string? typeOfContract
{
get { return (string?)ViewState["typeOfContract"]; }
set { ViewState["typeOfContract"] = value; }
}
</code></pre>
<p>Later in the code I use it like this:</p>
<pre><code>typeOfContract = Request.QueryString["type"];
</code></pre>
<p>I am getting the following error at the declaration of <code>typeOfContract</code> line stating:</p>
<blockquote>
<p>The type 'string' must be a non-nullable value type in order to use
it as parameter 'T' in the generic type or method
'System.Nullable<T>'</p>
</blockquote>
<p>Any ideas? Basically, I want to make sure that <code>"type"</code> exists in the <code>QueryString</code> before performing an action.</p>
|
[
{
"answer_id": 187419,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 5,
"selected": false,
"text": "string ?"
},
{
"answer_id": 187430,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 4,
"selected": false,
"text": "string s = null; \n private string typeOfContract\n {\n get { return ViewState[\"typeOfContract\"] as string; }\n set { ViewState[\"typeOfContract\"] = value; }\n }\n"
},
{
"answer_id": 187431,
"author": "csgero",
"author_id": 21764,
"author_profile": "https://Stackoverflow.com/users/21764",
"pm_score": 4,
"selected": false,
"text": "Nullable<T>"
},
{
"answer_id": 10620020,
"author": "James Oravec",
"author_id": 1190934,
"author_profile": "https://Stackoverflow.com/users/1190934",
"pm_score": 2,
"selected": false,
"text": "?"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187406",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4144/"
] |
187,414
|
<p>I don't really <em>get</em> lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the <code>=></code> syntax, people in my world (.NET) are talking about lamdba expressions more and more.</p>
<p>I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing?</p>
<p>Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.</p>
|
[
{
"answer_id": 187432,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": " // Only include children - a predicate\nvar query = dataSource.Where(person => person.Age < 18) \n // Transform to sequence of names - a projection\n .Select(person => person.Name);\n"
},
{
"answer_id": 187442,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 2,
"selected": false,
"text": "[2*x for x in list]\n def double(x):\n return 2*x\nmap(double, list) # iirc\n double = lambda x : 2*x\nmap(double, list)\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7565/"
] |
187,421
|
<p>I am using a List Control to display a representation of elements within a vector. When the list is clicked on another control shows information about that element. The index of the element is currently determined by its index in the control, however if I wish to sort or filter the results this will no longer work.</p>
<p>I have been told that I could use a virtual list control, but the MSDN is not very friendly, can someone run me through how I could use a virtual list control for this?</p>
|
[
{
"answer_id": 187525,
"author": "NotJarvis",
"author_id": 16268,
"author_profile": "https://Stackoverflow.com/users/16268",
"pm_score": 4,
"selected": true,
"text": "YourListCtrl.SetItemData((DWORDPTR)&YourData); DataTypeYouWant* pData = (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem));"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
187,434
|
<p>I need to create a cherrypy main page that has a login area. I want the login area to be secure, but not the rest of the page. How can I do this in CherryPy?</p>
<p>Ideally, any suggestions will be compatible with <a href="http://web.archive.org/web/20170210040849/http://tools.cherrypy.org:80/wiki/AuthenticationAndAccessRestrictions" rel="nofollow noreferrer">http://web.archive.org/web/20170210040849/http://tools.cherrypy.org:80/wiki/AuthenticationAndAccessRestrictions</a></p>
|
[
{
"answer_id": 187525,
"author": "NotJarvis",
"author_id": 16268,
"author_profile": "https://Stackoverflow.com/users/16268",
"pm_score": 4,
"selected": true,
"text": "YourListCtrl.SetItemData((DWORDPTR)&YourData); DataTypeYouWant* pData = (DataTypeYouWant*)(YourListCtrl.GetItemData(indexofselecteditem));"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
187,438
|
<p>I have currently an installed pgsql instance that is running on port <code>1486</code>. I want to change this port to <code>5433</code>, how should I proceed for this?</p>
|
[
{
"answer_id": 187457,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 9,
"selected": true,
"text": "postgresql.conf port = 1486\n /etc/postgresql/8.3/main/ C:\\Program Files\\PostgreSQL\\9.3\\data sudo service postgresql restart"
},
{
"answer_id": 2530381,
"author": "Frank Heikens",
"author_id": 271959,
"author_profile": "https://Stackoverflow.com/users/271959",
"pm_score": 5,
"selected": false,
"text": "$ pg_ctl -o \"-F -p 5433\" start\n $ postgres -p 5433\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22554/"
] |
187,448
|
<p>Using OpenXML SDK, I want to insert basic HTML snippets into a Word document.</p>
<p>How would you do this:</p>
<ul>
<li>Manipulating XML directly ?</li>
<li>Using an XSLT ?</li>
<li>using AltChunk ?</li>
</ul>
<p>Moreover, C# or VB examples are more than welcome :)</p>
|
[
{
"answer_id": 317064,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 3,
"selected": false,
"text": " void ConvertHTML(string htmlFileName, string docFileName)\n {\n // Create a Wordprocessing document. \n using (WordprocessingDocument package = WordprocessingDocument.Create(docFileName, WordprocessingDocumentType.Document))\n {\n // Add a new main document part. \n package.AddMainDocumentPart();\n\n // Create the Document DOM. \n package.MainDocumentPart.Document = new Document(new Body());\n Body body = package.MainDocumentPart.Document.Body;\n\n XPathDocument htmlDoc = new XPathDocument(htmlFileName);\n\n XPathNavigator navigator = htmlDoc.CreateNavigator();\n XmlNamespaceManager mngr = new XmlNamespaceManager(navigator.NameTable);\n mngr.AddNamespace(\"xhtml\", \"http://www.w3.org/1999/xhtml\");\n\n XPathNodeIterator ni = navigator.Select(\"//xhtml:p\", mngr);\n while (ni.MoveNext())\n {\n body.AppendChild<Paragraph>(new Paragraph(new Run(new Text(ni.Current.Value))));\n }\n\n // Save changes to the main document part. \n package.MainDocumentPart.Document.Save();\n }\n }\n"
}
] |
2008/10/09
|
[
"https://Stackoverflow.com/questions/187448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22970/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.