qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
19,096
|
<p>I have a project that utilizes the javax.mail.internet.MimeMessage and other related classes that does mime parsing for emails that we receive. This needs to be ported to .NET.</p>
<p>What .Net 3rd party or built in library can I use to replace the Java classes that I'm using?</p>
<p>EDIT: Anything change in the last 9 months since I asked this question?</p>
|
[
{
"answer_id": 2644678,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 0,
"selected": false,
"text": "using(Imap imap = new Imap())\n{\n imap.Connect(\"imapServer\");\n imap.UseBestLogin(\"user\", \"password\");\n\n imap.SelectInbox();\n List<long> uids = imap.SearchFlag(Flag.Unseen);\n\n foreach (long uid in uids)\n {\n byte[] eml = imap.GetMessageByUID(uid);\n IMail message = new MailBuilder()\n .CreateFromEml(eml);\n\n Console.WriteLine(message.Subject);\n }\n imap.Close();\n}\n"
}
] |
2008/08/20
|
[
"https://Stackoverflow.com/questions/19096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
19,127
|
<p>I have a page using <code><ul></code> lists for navigation (Javascript changes the styling to display or not on mouseover).</p>
<p>This is working fine for me <em>except</em> in IE6 and IE7 when I have a Google Map on the page.</p>
<p>In this case the drop-down simply does not work. However, the page continues to work in FireFox 2.</p>
<p>I have done a little bit of research and discovered that this may be an example of the IE Select Box Bug, but I am not sure as the Google Map appears to be using a <code><div></code>, not an <code><iframe></code>.</p>
<p>Has anyone else encountered a problem similar to this, and if so do they have any recommendations on the best way to overcome this problem?</p>
|
[
{
"answer_id": 19279,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "$(function () {\n $(\"#primary-nav\").appendTo(\"#footer\");\n});\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
19,132
|
<p>I'm asking with regards to c#, but I assume its the same in most other languages.</p>
<p>Does anyone have a good definition of <em>expressions</em> and <em>statements</em> and what the differences are?</p>
|
[
{
"answer_id": 19139,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 4,
"selected": false,
"text": "1 + 2 * 4 * foo.bar() //Expression\nfoo.voidFunc(1); //Statement\n"
},
{
"answer_id": 19224,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 10,
"selected": true,
"text": "1 + 2 / X\n"
},
{
"answer_id": 19362,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 5,
"selected": false,
"text": "statement\n : labeled_statement\n | compound_statement\n | expression_statement\n | selection_statement\n | iteration_statement\n | jump_statement\n ;\n\nexpression_statement\n : ';'\n | expression ';'\n ;\n"
},
{
"answer_id": 379882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "(FOR i = 1 TO 10 DO (print i))"
},
{
"answer_id": 646331,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "void"
},
{
"answer_id": 5439795,
"author": "ncmathsadist",
"author_id": 467379,
"author_profile": "https://Stackoverflow.com/users/467379",
"pm_score": 0,
"selected": false,
"text": "x = 5\n"
},
{
"answer_id": 8450398,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": -1,
"selected": false,
"text": "Void"
},
{
"answer_id": 12285190,
"author": "Andaquin",
"author_id": 1038008,
"author_profile": "https://Stackoverflow.com/users/1038008",
"pm_score": 2,
"selected": false,
"text": "for\ngoto\nreturn\nif\n"
},
{
"answer_id": 12458901,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 1,
"selected": false,
"text": "bool IsPositive(int number)\n{\n if (number > 0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n"
},
{
"answer_id": 16422689,
"author": "vfclists",
"author_id": 172406,
"author_profile": "https://Stackoverflow.com/users/172406",
"pm_score": 1,
"selected": false,
"text": "statement"
},
{
"answer_id": 30960293,
"author": "Ely",
"author_id": 1566187,
"author_profile": "https://Stackoverflow.com/users/1566187",
"pm_score": 2,
"selected": false,
"text": "statement:\n labeled-statement\n expression-statement <-- can be zero or more expressions\n compound-statement\n selection-statement\n iteration-statement\n jump-statement\n declaration-statement\n try-block\n"
},
{
"answer_id": 32057203,
"author": "Shelby Moore III",
"author_id": 615784,
"author_profile": "https://Stackoverflow.com/users/615784",
"pm_score": -1,
"selected": false,
"text": "void"
},
{
"answer_id": 57619680,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 2,
"selected": false,
"text": "sizeof"
},
{
"answer_id": 62324086,
"author": "Xwtek",
"author_id": 5784051,
"author_profile": "https://Stackoverflow.com/users/5784051",
"pm_score": 0,
"selected": false,
"text": "throw new Exception(\"\")"
},
{
"answer_id": 63378331,
"author": "Gk Mohammad Emon",
"author_id": 7200133,
"author_profile": "https://Stackoverflow.com/users/7200133",
"pm_score": 0,
"selected": false,
"text": "if(a>=0)\nprintf(\"Hello Humen,I'm a statement\");\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
19,147
|
<p>Using C# and WPF under .NET (rather than <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> or console), what is the correct way to create an application that can only be run as a single instance?</p>
<p>I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.</p>
<p>The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.</p>
|
[
{
"answer_id": 19165,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 7,
"selected": false,
"text": "class OneAtATimePlease {\n\n // Use a name unique to the application (eg include your company URL)\n static Mutex mutex = new Mutex (false, \"oreilly.com OneAtATimeDemo\");\n\n static void Main()\n {\n // Wait 5 seconds if contended – in case another instance\n // of the program is in the process of shutting down.\n if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))\n {\n Console.WriteLine(\"Another instance of the app is running. Bye!\");\n return;\n }\n\n try\n { \n Console.WriteLine(\"Running - press Enter to exit\");\n Console.ReadLine();\n }\n finally\n {\n mutex.ReleaseMutex();\n } \n } \n}\n"
},
{
"answer_id": 19326,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 7,
"selected": false,
"text": "public class SingleInstanceApplication : System.Windows.Application\n{\n protected override void OnStartup(System.Windows.StartupEventArgs e)\n {\n // Call the OnStartup event on our base class\n base.OnStartup(e);\n\n // Create our MainWindow and show it\n MainWindow window = new MainWindow();\n window.Show();\n }\n\n public void Activate()\n {\n // Reactivate the main window\n MainWindow.Activate();\n }\n}\n"
},
{
"answer_id": 522874,
"author": "Matt Davis",
"author_id": 51170,
"author_profile": "https://Stackoverflow.com/users/51170",
"pm_score": 10,
"selected": true,
"text": "static class Program\n{\n static Mutex mutex = new Mutex(true, \"{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}\");\n [STAThread]\n ...\n}\n"
},
{
"answer_id": 2295625,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 4,
"selected": false,
"text": "static void Main()\n{\n using (SingleInstanceMutex sim = new SingleInstanceMutex())\n {\n if (sim.IsOtherInstanceRunning)\n {\n Application.Exit();\n }\n\n // Initialize program here.\n }\n}\n"
},
{
"answer_id": 2769924,
"author": "Peter",
"author_id": 331895,
"author_profile": "https://Stackoverflow.com/users/331895",
"pm_score": 3,
"selected": false,
"text": "var m = new Mutex(...);\n...\nGC.KeepAlive(m);\n"
},
{
"answer_id": 3089321,
"author": "Sergey Aldoukhov",
"author_id": 58463,
"author_profile": "https://Stackoverflow.com/users/58463",
"pm_score": 2,
"selected": false,
"text": "public partial class App\n{\n [DllImport(\"user32\")]\n private static extern int OpenIcon(IntPtr hWnd);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetForegroundWindow(IntPtr hWnd);\n\n protected override void OnStartup(StartupEventArgs e)\n {\n base.OnStartup(e);\n var p = Process\n .GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n foreach (var t in p.Where(t => t.MainWindowHandle != IntPtr.Zero))\n {\n OpenIcon(t.MainWindowHandle);\n SetForegroundWindow(t.MainWindowHandle);\n Current.Shutdown();\n return;\n }\n\n // there is a chance the user tries to click on the icon repeatedly\n // and the process cannot be discovered yet\n bool createdNew;\n var mutex = new Mutex(true, \"MyAwesomeApp\", \n out createdNew); // must be a variable, though it is unused - \n // we just need a bit of time until the process shows up\n if (!createdNew)\n {\n Current.Shutdown();\n return;\n }\n\n new Bootstrapper().Run();\n }\n }\n"
},
{
"answer_id": 3808173,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 6,
"selected": false,
"text": "'Another instance of the app is running. Bye'"
},
{
"answer_id": 5536495,
"author": "Mikhail Semenov",
"author_id": 653772,
"author_profile": "https://Stackoverflow.com/users/653772",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing Microsoft.VisualBasic.ApplicationServices;\n\n\nnamespace SingleInstanceController_NET\n{\n public class SingleInstanceController\n : WindowsFormsApplicationBase\n {\n public delegate Form CreateMainForm();\n public delegate void StartNextInstanceDelegate(Form mainWindow);\n CreateMainForm formCreation;\n StartNextInstanceDelegate onStartNextInstance;\n public SingleInstanceController(CreateMainForm formCreation, StartNextInstanceDelegate onStartNextInstance)\n {\n // Set whether the application is single instance\n this.formCreation = formCreation;\n this.onStartNextInstance = onStartNextInstance;\n this.IsSingleInstance = true;\n\n this.StartupNextInstance += new StartupNextInstanceEventHandler(this_StartupNextInstance); \n }\n\n void this_StartupNextInstance(object sender, StartupNextInstanceEventArgs e)\n {\n if (onStartNextInstance != null)\n {\n onStartNextInstance(this.MainForm); // This code will be executed when the user tries to start the running program again,\n // for example, by clicking on the exe file.\n } // This code can determine how to re-activate the existing main window of the running application.\n }\n\n protected override void OnCreateMainForm()\n {\n // Instantiate your main application form\n this.MainForm = formCreation();\n }\n\n public void Run()\n {\n string[] commandLine = new string[0];\n base.Run(commandLine);\n }\n }\n}\n"
},
{
"answer_id": 5919904,
"author": "Nathan Moinvaziri",
"author_id": 610692,
"author_profile": "https://Stackoverflow.com/users/610692",
"pm_score": 4,
"selected": false,
"text": "public partial class App : Application\n{\n private static Mutex SingleMutex;\n public static uint MessageId;\n\n private void Application_Startup(object sender, StartupEventArgs e)\n {\n IntPtr Result;\n IntPtr SendOk;\n Win32.COPYDATASTRUCT CopyData;\n string[] Args;\n IntPtr CopyDataMem;\n bool AllowMultipleInstances = false;\n\n Args = Environment.GetCommandLineArgs();\n\n // TODO: Replace {00000000-0000-0000-0000-000000000000} with your application's GUID\n MessageId = Win32.RegisterWindowMessage(\"{00000000-0000-0000-0000-000000000000}\");\n SingleMutex = new Mutex(false, \"AppName\");\n\n if ((AllowMultipleInstances) || (!AllowMultipleInstances && SingleMutex.WaitOne(1, true)))\n {\n new Main();\n }\n else if (Args.Length > 1)\n {\n foreach (Process Proc in Process.GetProcesses())\n {\n SendOk = Win32.SendMessageTimeout(Proc.MainWindowHandle, MessageId, IntPtr.Zero, IntPtr.Zero,\n Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n 2000, out Result);\n\n if (SendOk == IntPtr.Zero)\n continue;\n if ((uint)Result != MessageId)\n continue;\n\n CopyDataMem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.COPYDATASTRUCT)));\n\n CopyData.dwData = IntPtr.Zero;\n CopyData.cbData = Args[1].Length*2;\n CopyData.lpData = Marshal.StringToHGlobalUni(Args[1]);\n\n Marshal.StructureToPtr(CopyData, CopyDataMem, false);\n\n Win32.SendMessageTimeout(Proc.MainWindowHandle, Win32.WM_COPYDATA, IntPtr.Zero, CopyDataMem,\n Win32.SendMessageTimeoutFlags.SMTO_BLOCK | Win32.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG,\n 5000, out Result);\n\n Marshal.FreeHGlobal(CopyData.lpData);\n Marshal.FreeHGlobal(CopyDataMem);\n }\n\n Shutdown(0);\n }\n }\n}\n\npublic partial class Main : Window\n{\n private void Window_Loaded(object sender, RoutedEventArgs e)\n {\n HwndSource Source;\n\n Source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);\n Source.AddHook(new HwndSourceHook(Window_Proc));\n }\n\n private IntPtr Window_Proc(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam, ref bool Handled)\n {\n Win32.COPYDATASTRUCT CopyData;\n string Path;\n\n if (Msg == Win32.WM_COPYDATA)\n {\n CopyData = (Win32.COPYDATASTRUCT)Marshal.PtrToStructure(lParam, typeof(Win32.COPYDATASTRUCT));\n Path = Marshal.PtrToStringUni(CopyData.lpData, CopyData.cbData / 2);\n\n if (WindowState == WindowState.Minimized)\n {\n // Restore window from tray\n }\n\n // Do whatever we want with information\n\n Activate();\n Focus();\n }\n\n if (Msg == App.MessageId)\n {\n Handled = true;\n return new IntPtr(App.MessageId);\n }\n\n return IntPtr.Zero;\n }\n}\n\npublic class Win32\n{\n public const uint WM_COPYDATA = 0x004A;\n\n public struct COPYDATASTRUCT\n {\n public IntPtr dwData;\n public int cbData;\n public IntPtr lpData;\n }\n\n [Flags]\n public enum SendMessageTimeoutFlags : uint\n {\n SMTO_NORMAL = 0x0000,\n SMTO_BLOCK = 0x0001,\n SMTO_ABORTIFHUNG = 0x0002,\n SMTO_NOTIMEOUTIFNOTHUNG = 0x0008\n }\n\n [DllImport(\"user32.dll\", SetLastError=true, CharSet=CharSet.Auto)]\n public static extern uint RegisterWindowMessage(string lpString);\n [DllImport(\"user32.dll\")]\n public static extern IntPtr SendMessageTimeout(\n IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam,\n SendMessageTimeoutFlags fuFlags, uint uTimeout, out IntPtr lpdwResult);\n}\n"
},
{
"answer_id": 7183246,
"author": "CharithJ",
"author_id": 591656,
"author_profile": "https://Stackoverflow.com/users/591656",
"pm_score": 5,
"selected": false,
"text": "[DllImport(\"user32.dll\")]\nprivate static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n\nprivate const int SW_SHOWMAXIMIZED = 3;\n\nstatic void Main() \n{\n Process currentProcess = Process.GetCurrentProcess();\n var runningProcess = (from process in Process.GetProcesses()\n where\n process.Id != currentProcess.Id &&\n process.ProcessName.Equals(\n currentProcess.ProcessName,\n StringComparison.Ordinal)\n select process).FirstOrDefault();\n if (runningProcess != null)\n {\n ShowWindow(runningProcess.MainWindowHandle, SW_SHOWMAXIMIZED);\n return; \n }\n}\n"
},
{
"answer_id": 13646352,
"author": "carlito",
"author_id": 1865565,
"author_profile": "https://Stackoverflow.com/users/1865565",
"pm_score": 3,
"selected": false,
"text": "private void Application_Startup(object sender, StartupEventArgs e)\n{\n Process thisProc = Process.GetCurrentProcess();\n if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)\n {\n MessageBox.Show(\"Application running\");\n Application.Current.Shutdown();\n return;\n }\n\n var wLogin = new LoginWindow();\n\n if (wLogin.ShowDialog() == true)\n {\n var wMain = new Main();\n wMain.WindowState = WindowState.Maximized;\n wMain.Show();\n }\n else\n {\n Application.Current.Shutdown();\n }\n}\n"
},
{
"answer_id": 14337614,
"author": "Tommaso Belluzzo",
"author_id": 796085,
"author_profile": "https://Stackoverflow.com/users/796085",
"pm_score": 0,
"selected": false,
"text": "[STAThread]\npublic static void Main()\n{\n String assemblyName = Assembly.GetExecutingAssembly().GetName().Name;\n\n using (Mutex mutex = new Mutex(false, assemblyName))\n {\n if (!mutex.WaitOne(0, false))\n {\n Boolean shownProcess = false;\n Process currentProcess = Process.GetCurrentProcess();\n\n foreach (Process process in Process.GetProcessesByName(currentProcess.ProcessName))\n {\n if (!process.Id.Equals(currentProcess.Id) && process.MainModule.FileName.Equals(currentProcess.MainModule.FileName) && !process.MainWindowHandle.Equals(IntPtr.Zero))\n {\n IntPtr windowHandle = process.MainWindowHandle;\n\n if (NativeMethods.IsIconic(windowHandle))\n NativeMethods.ShowWindow(windowHandle, ShowWindowCommand.Restore);\n\n NativeMethods.SetForegroundWindow(windowHandle);\n\n shownProcess = true;\n }\n }\n\n if (!shownProcess)\n MessageBox.Show(String.Format(CultureInfo.CurrentCulture, \"An instance of {0} is already running!\", assemblyName), assemblyName, MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0);\n }\n else\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form());\n }\n }\n}\n"
},
{
"answer_id": 16097909,
"author": "Dan",
"author_id": 1507012,
"author_profile": "https://Stackoverflow.com/users/1507012",
"pm_score": 3,
"selected": false,
"text": "System.Windows.StartupEventHandler"
},
{
"answer_id": 16522305,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 4,
"selected": false,
"text": "static class Program\n{\n public static readonly SingleInstance Singleton = new SingleInstance(typeof(Program).FullName);\n\n [STAThread]\n static void Main(string[] args)\n {\n // NOTE: if this always return false, close & restart Visual Studio\n // this is probably due to the vshost.exe thing\n Singleton.RunFirstInstance(() =>\n {\n SingleInstanceMain(args);\n });\n }\n\n public static void SingleInstanceMain(string[] args)\n {\n // standard code that was in Main now goes here\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n"
},
{
"answer_id": 19470753,
"author": "Cornel Marian",
"author_id": 736113,
"author_profile": "https://Stackoverflow.com/users/736113",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\nusing System.Threading;\n\nnamespace OneAndOnlyOne\n{\nstatic class Program\n{\n static String _mutexID = \" // generate guid\"\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n\n Boolean _isNotRunning;\n using (Mutex _mutex = new Mutex(true, _mutexID, out _isNotRunning))\n {\n if (_isNotRunning)\n {\n Application.Run(new Form1());\n }\n else\n {\n MessageBox.Show(\"An instance is already running.\");\n return;\n }\n }\n }\n}\n}\n"
},
{
"answer_id": 20278491,
"author": "Jason Lim",
"author_id": 1973634,
"author_profile": "https://Stackoverflow.com/users/1973634",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"user32.dll\")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\nstatic readonly string guid = \"<Application Guid>\";\n\nstatic void Main()\n{\n Mutex mutex = null;\n if (!CreateMutex(out mutex))\n return;\n\n // Application startup code.\n\n Environment.SetEnvironmentVariable(guid, null, EnvironmentVariableTarget.User);\n}\n\nstatic bool CreateMutex(out Mutex mutex)\n{\n bool createdNew = false;\n mutex = new Mutex(false, guid, out createdNew);\n\n if (createdNew)\n {\n Process process = Process.GetCurrentProcess();\n string value = process.Id.ToString();\n\n Environment.SetEnvironmentVariable(guid, value, EnvironmentVariableTarget.User);\n }\n else\n {\n string value = Environment.GetEnvironmentVariable(guid, EnvironmentVariableTarget.User);\n Process process = null;\n int processId = -1;\n\n if (int.TryParse(value, out processId))\n process = Process.GetProcessById(processId);\n\n if (process == null || !SetForegroundWindow(process.MainWindowHandle))\n MessageBox.Show(\"Unable to start application. An instance of this application is already running.\");\n }\n\n return createdNew;\n}\n"
},
{
"answer_id": 20412588,
"author": "Eric Ouellet",
"author_id": 452845,
"author_profile": "https://Stackoverflow.com/users/452845",
"pm_score": 2,
"selected": false,
"text": "public class SingleInstanceApp\n{\n [STAThread]\n public static void Main(string[] args)\n {\n Mutex _mutexSingleInstance = new Mutex(true, \"MonitorMeSingleInstance\");\n\n if (_mutexSingleInstance.WaitOne(TimeSpan.Zero, true))\n {\n try\n {\n var app = new App();\n app.InitializeComponent();\n app.Run();\n\n }\n finally\n {\n _mutexSingleInstance.ReleaseMutex();\n _mutexSingleInstance.Close();\n }\n }\n else\n {\n MessageBox.Show(\"One instance is already running.\");\n\n var processes = Process.GetProcessesByName(Assembly.GetEntryAssembly().GetName().Name);\n {\n if (processes.Length > 1)\n {\n foreach (var process in processes)\n {\n if (process.Id != Process.GetCurrentProcess().Id)\n {\n WindowHelper.SetForegroundWindow(process.MainWindowHandle);\n }\n }\n }\n }\n }\n }\n}\n"
},
{
"answer_id": 28146800,
"author": "Martin Bech",
"author_id": 1677634,
"author_profile": "https://Stackoverflow.com/users/1677634",
"pm_score": 2,
"selected": false,
"text": "class NativeMethods\n{\n public const int HWND_BROADCAST = 0xffff;\n public static readonly int WM_SHOWME = RegisterWindowMessage(\"WM_SHOWME\");\n [DllImport(\"user32\")]\n public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n [DllImport(\"user32\")]\n public static extern int RegisterWindowMessage(string message);\n}\n"
},
{
"answer_id": 38212569,
"author": "Code Scratcher",
"author_id": 4342676,
"author_profile": "https://Stackoverflow.com/users/4342676",
"pm_score": 0,
"selected": false,
"text": "Protected Overrides Sub OnStartup(e As StartupEventArgs)\n Const appName As String = \"TestApp\"\n Dim createdNew As Boolean\n _mutex = New Mutex(True, appName, createdNew)\n If Not createdNew Then\n 'app is already running! Exiting the application\n MessageBox.Show(\"Application is already running.\")\n Application.Current.Shutdown()\n End If\n MyBase.OnStartup(e)\nEnd Sub\n"
},
{
"answer_id": 38306338,
"author": "Siarhei Kuchuk",
"author_id": 212746,
"author_profile": "https://Stackoverflow.com/users/212746",
"pm_score": 1,
"selected": false,
"text": "public enum ApplicationSingleInstanceMode\n{\n CurrentUserSession,\n AllSessionsOfCurrentUser,\n Pc\n}\n\npublic class ApplicationSingleInstancePerUser: IDisposable\n{\n private readonly EventWaitHandle _event;\n\n /// <summary>\n /// Shows if the current instance of ghost is the first\n /// </summary>\n public bool FirstInstance { get; private set; }\n\n /// <summary>\n /// Initializes \n /// </summary>\n /// <param name=\"applicationName\">The application name</param>\n /// <param name=\"mode\">The single mode</param>\n public ApplicationSingleInstancePerUser(string applicationName, ApplicationSingleInstanceMode mode = ApplicationSingleInstanceMode.CurrentUserSession)\n {\n string name;\n if (mode == ApplicationSingleInstanceMode.CurrentUserSession)\n name = $\"Local\\\\{applicationName}\";\n else if (mode == ApplicationSingleInstanceMode.AllSessionsOfCurrentUser)\n name = $\"Global\\\\{applicationName}{Environment.UserDomainName}\";\n else\n name = $\"Global\\\\{applicationName}\";\n\n try\n {\n bool created;\n _event = new EventWaitHandle(false, EventResetMode.ManualReset, name, out created);\n FirstInstance = created;\n }\n catch\n {\n }\n }\n\n public void Dispose()\n {\n _event.Dispose();\n }\n}\n"
},
{
"answer_id": 38853721,
"author": "pStan",
"author_id": 1221380,
"author_profile": "https://Stackoverflow.com/users/1221380",
"pm_score": 1,
"selected": false,
"text": " // Process already running ? \n if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)\n {\n\n // Show your error message\n MessageBox.Show(\"xxx is already running. \\r\\n\\r\\nIf the original process is hung up you may need to restart your computer, or kill the current xxx process using the task manager.\", \"xxx is already running!\", MessageBoxButton.OK, MessageBoxImage.Exclamation);\n\n // This process \n Process currentProcess = Process.GetCurrentProcess();\n\n // Get all processes running on the local computer.\n Process[] localAll = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName);\n\n // ID of this process... \n int temp = currentProcess.Id;\n MessageBox.Show(\"This Process ID: \" + temp.ToString());\n\n for (int i = 0; i < localAll.Length; i++)\n {\n // Find the other process \n if (localAll[i].Id != currentProcess.Id)\n {\n MessageBox.Show(\"Original Process ID (Switching to): \" + localAll[i].Id.ToString());\n\n // Switch to it... \n SetForegroundWindow(localAll[i].MainWindowHandle);\n\n }\n }\n\n Application.Current.Shutdown();\n\n }\n"
},
{
"answer_id": 39160390,
"author": "kakopappa",
"author_id": 192901,
"author_profile": "https://Stackoverflow.com/users/192901",
"pm_score": 0,
"selected": false,
"text": " static class Program\n {\n [STAThread]\n static void Main()\n {\n bool createdNew;\n using (new Mutex(true, \"MyApp\", out createdNew))\n {\n if (createdNew) {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n var mainClass = new SynGesturesLogic();\n Application.ApplicationExit += mainClass.tray_exit;\n Application.Run();\n }\n else\n {\n var current = Process.GetCurrentProcess();\n foreach (var process in Process.GetProcessesByName(current.ProcessName).Where(process => process.Id != current.Id))\n {\n NativeMethods.SetForegroundWindow(process.MainWindowHandle);\n break;\n }\n }\n }\n }\n }\n"
},
{
"answer_id": 39775932,
"author": "Pete",
"author_id": 2833784,
"author_profile": "https://Stackoverflow.com/users/2833784",
"pm_score": 0,
"selected": false,
"text": " static class Program {\n [DllImport(\"user32.dll\")]\n private static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);\n [DllImport(\"User32.dll\")]\n public static extern Int32 SetForegroundWindow(IntPtr hWnd);\n [STAThread]\n static void Main() {\n Process currentProcess = Process.GetCurrentProcess();\n foreach (var process in Process.GetProcesses()) {\n try {\n if ((process.Id != currentProcess.Id) && \n (process.ProcessName == currentProcess.ProcessName) &&\n (process.MainModule.FileName == currentProcess.MainModule.FileName)) {\n ShowWindow(process.MainWindowHandle, 5); // const int SW_SHOW = 5; //Activates the window and displays it in its current size and position. \n SetForegroundWindow(process.MainWindowHandle);\n return;\n }\n } catch (Exception ex) {\n //ignore Exception \"Access denied \"\n }\n }\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n"
},
{
"answer_id": 41390636,
"author": "newbieguy",
"author_id": 4477797,
"author_profile": "https://Stackoverflow.com/users/4477797",
"pm_score": 2,
"selected": false,
"text": "System.Diagnostics; \n...\nstring thisprocessname = Process.GetCurrentProcess().ProcessName;\n\nif (Process.GetProcesses().Count(p => p.ProcessName == thisprocessname) > 1)\n return;\n"
},
{
"answer_id": 41599502,
"author": "Divins Mathew",
"author_id": 3201403,
"author_profile": "https://Stackoverflow.com/users/3201403",
"pm_score": 0,
"selected": false,
"text": "StreamWriter"
},
{
"answer_id": 45778772,
"author": "A.T.",
"author_id": 2734629,
"author_profile": "https://Stackoverflow.com/users/2734629",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.IO;\n\nnamespace TestCs\n{\n public class Program\n {\n // The app id must be unique. Generate a new guid for your application. \n public static string AppId = \"01234567-89ab-cdef-0123-456789abcdef\";\n\n // The stream is stored globally to ensure that it won't be disposed before the application terminates.\n public static FileStream UniqueInstanceStream;\n\n public static int Main(string[] args)\n {\n EnsureUniqueInstance();\n\n // Your code here.\n\n return 0;\n }\n\n private static void EnsureUniqueInstance()\n {\n // Note: If you want the check to be per-user, use Environment.SpecialFolder.ApplicationData instead.\n string lockDir = Path.Combine(\n Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),\n \"UniqueInstanceApps\");\n string lockPath = Path.Combine(lockDir, $\"{AppId}.unique\");\n\n Directory.CreateDirectory(lockDir);\n\n try\n {\n // Create the file with exclusive write access. If this fails, then another process is executing.\n UniqueInstanceStream = File.Open(lockPath, FileMode.Create, FileAccess.Write, FileShare.None);\n\n // Although only the line above should be sufficient, when debugging with a vshost on Visual Studio\n // (that acts as a proxy), the IO exception isn't passed to the application before a Write is executed.\n UniqueInstanceStream.Write(new byte[] { 0 }, 0, 1);\n UniqueInstanceStream.Flush();\n }\n catch\n {\n throw new Exception(\"Another instance of the application is already running.\");\n }\n }\n }\n}\n"
},
{
"answer_id": 47849014,
"author": "Legends",
"author_id": 2581562,
"author_profile": "https://Stackoverflow.com/users/2581562",
"pm_score": 2,
"selected": false,
"text": "createdNew"
},
{
"answer_id": 48657296,
"author": "A.J.Bauer",
"author_id": 1278334,
"author_profile": "https://Stackoverflow.com/users/1278334",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\n// needs reference to Microsoft.VisualBasic\nusing Microsoft.VisualBasic.ApplicationServices; \n\nnamespace YourNamespace\n{\n public class SingleInstanceController : WindowsFormsApplicationBase\n {\n public SingleInstanceController()\n {\n this.IsSingleInstance = true;\n }\n\n protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)\n {\n e.BringToForeground = true;\n base.OnStartupNextInstance(e);\n }\n\n protected override void OnCreateMainForm()\n {\n this.MainForm = new Form1();\n }\n }\n\n static class Program\n {\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n string[] args = Environment.GetCommandLineArgs();\n SingleInstanceController controller = new SingleInstanceController();\n controller.Run(args);\n }\n }\n}\n"
},
{
"answer_id": 49796895,
"author": "Deniz",
"author_id": 9569602,
"author_profile": "https://Stackoverflow.com/users/9569602",
"pm_score": 2,
"selected": false,
"text": "Program.cs"
},
{
"answer_id": 57140889,
"author": "Vishnu Babu",
"author_id": 5342284,
"author_profile": "https://Stackoverflow.com/users/5342284",
"pm_score": 2,
"selected": false,
"text": "static Mutex mutex = null;\n//A string that is the name of the mutex\nstring mutexName = @\"Global\\test\";\n//Prevent Multiple Instances of Application\nbool onlyInstance = false;\nmutex = new Mutex(true, mutexName, out onlyInstance);\n\nif (!onlyInstance)\n{\n MessageBox.Show(\"You are already running this application in your system.\", \"Already Running..\", MessageBoxButton.OK);\n Application.Current.Shutdown();\n}\n"
},
{
"answer_id": 62712773,
"author": "std8590",
"author_id": 13319821,
"author_profile": "https://Stackoverflow.com/users/13319821",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// This class allows restricting the number of executables in execution, to one.\n/// </summary>\npublic sealed class SingletonApplicationEnforcer\n{\n readonly Action<IEnumerable<string>> processArgsFunc;\n readonly string applicationId;\n Thread thread;\n string argDelimiter = \"_;;_\";\n\n /// <summary>\n /// Gets or sets the string that is used to join \n /// the string array of arguments in memory.\n /// </summary>\n /// <value>The arg delimeter.</value>\n public string ArgDelimeter\n {\n get\n {\n return argDelimiter;\n }\n set\n {\n argDelimiter = value;\n }\n }\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"SingletonApplicationEnforcer\"/> class.\n /// </summary>\n /// <param name=\"processArgsFunc\">A handler for processing command line args \n /// when they are received from another application instance.</param>\n /// <param name=\"applicationId\">The application id used \n /// for naming the <seealso cref=\"EventWaitHandle\"/>.</param>\n public SingletonApplicationEnforcer(Action<IEnumerable<string>> processArgsFunc, \n string applicationId = \"DisciplesRock\")\n {\n if (processArgsFunc == null)\n {\n throw new ArgumentNullException(\"processArgsFunc\");\n }\n this.processArgsFunc = processArgsFunc;\n this.applicationId = applicationId;\n }\n\n /// <summary>\n /// Determines if this application instance is not the singleton instance.\n /// If this application is not the singleton, then it should exit.\n /// </summary>\n /// <returns><c>true</c> if the application should shutdown, \n /// otherwise <c>false</c>.</returns>\n public bool ShouldApplicationExit()\n {\n bool createdNew;\n string argsWaitHandleName = \"ArgsWaitHandle_\" + applicationId;\n string memoryFileName = \"ArgFile_\" + applicationId;\n\n EventWaitHandle argsWaitHandle = new EventWaitHandle(\n false, EventResetMode.AutoReset, argsWaitHandleName, out createdNew);\n\n GC.KeepAlive(argsWaitHandle);\n\n if (createdNew)\n {\n /* This is the main, or singleton application. \n * A thread is created to service the MemoryMappedFile. \n * We repeatedly examine this file each time the argsWaitHandle \n * is Set by a non-singleton application instance. */\n thread = new Thread(() =>\n {\n try\n {\n using (MemoryMappedFile file = MemoryMappedFile.CreateOrOpen(memoryFileName, 10000))\n {\n while (true)\n {\n argsWaitHandle.WaitOne();\n using (MemoryMappedViewStream stream = file.CreateViewStream())\n {\n var reader = new BinaryReader(stream);\n string args;\n try\n {\n args = reader.ReadString();\n }\n catch (Exception ex)\n {\n Debug.WriteLine(\"Unable to retrieve string. \" + ex);\n continue;\n }\n string[] argsSplit = args.Split(new string[] { argDelimiter }, \n StringSplitOptions.RemoveEmptyEntries);\n processArgsFunc(argsSplit);\n }\n\n }\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine(\"Unable to monitor memory file. \" + ex);\n }\n });\n\n thread.IsBackground = true;\n thread.Start();\n }\n else\n {\n /* Non singleton application instance. \n * Should exit, after passing command line args to singleton process, \n * via the MemoryMappedFile. */\n using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting(memoryFileName))\n {\n using (MemoryMappedViewStream stream = mmf.CreateViewStream())\n {\n var writer = new BinaryWriter(stream);\n string[] args = Environment.GetCommandLineArgs();\n string joined = string.Join(argDelimiter, args);\n writer.Write(joined);\n }\n }\n argsWaitHandle.Set();\n }\n\n return !createdNew;\n }\n}\n"
},
{
"answer_id": 68214933,
"author": "datchung",
"author_id": 4856020,
"author_profile": "https://Stackoverflow.com/users/4856020",
"pm_score": -1,
"selected": false,
"text": "public static class SingleAppInstanceChecker\n{\n /// <summary>\n /// Arbitrary unique string\n /// </summary>\n private static Mutex _mutex = new Mutex(true, \"0d12ad74-026f-40c3-bdae-e178ddee8602\");\n\n public static bool IsNotRunning()\n {\n return _mutex.WaitOne(TimeSpan.Zero, true);\n }\n}\n"
},
{
"answer_id": 72174023,
"author": "Hanabi",
"author_id": 14700529,
"author_profile": "https://Stackoverflow.com/users/14700529",
"pm_score": 0,
"selected": false,
"text": "App.xaml.cs"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
] |
19,151
|
<p>How would one create an iterative function (or iterator object) in python?</p>
|
[
{
"answer_id": 19152,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 7,
"selected": false,
"text": "def count(n=0):\n while True:\n yield n\n n += 1\n"
},
{
"answer_id": 24377,
"author": "ars",
"author_id": 2611,
"author_profile": "https://Stackoverflow.com/users/2611",
"pm_score": 11,
"selected": true,
"text": "__iter__()"
},
{
"answer_id": 7542261,
"author": "Ethan Furman",
"author_id": 208880,
"author_profile": "https://Stackoverflow.com/users/208880",
"pm_score": 9,
"selected": false,
"text": "__iter__"
},
{
"answer_id": 11690539,
"author": "Manux",
"author_id": 319926,
"author_profile": "https://Stackoverflow.com/users/319926",
"pm_score": 7,
"selected": false,
"text": "return self"
},
{
"answer_id": 35779493,
"author": "Nizam Mohamed",
"author_id": 4522780,
"author_profile": "https://Stackoverflow.com/users/4522780",
"pm_score": 2,
"selected": false,
"text": "yield"
},
{
"answer_id": 36138037,
"author": "aq2",
"author_id": 5806943,
"author_profile": "https://Stackoverflow.com/users/5806943",
"pm_score": 4,
"selected": false,
"text": "__getitem__"
},
{
"answer_id": 50038486,
"author": "Daniil Mashkin",
"author_id": 2207154,
"author_profile": "https://Stackoverflow.com/users/2207154",
"pm_score": 3,
"selected": false,
"text": "class A(object):\n def __init__(self, l):\n self.data = l\n\n def __iter__(self):\n return iter(self.data)\n"
},
{
"answer_id": 51836944,
"author": "John Strood",
"author_id": 5337834,
"author_profile": "https://Stackoverflow.com/users/5337834",
"pm_score": 3,
"selected": false,
"text": "str"
},
{
"answer_id": 63337271,
"author": "Sreevatsan",
"author_id": 13093094,
"author_profile": "https://Stackoverflow.com/users/13093094",
"pm_score": 2,
"selected": false,
"text": " def __iter__(self):\n for x in self.iterable:\n yield x\n"
},
{
"answer_id": 71498451,
"author": "Muhammad Yasirroni",
"author_id": 11671779,
"author_profile": "https://Stackoverflow.com/users/11671779",
"pm_score": 1,
"selected": false,
"text": "class uc_iter():\n def __init__(self):\n self.value = 0\n def __iter__(self):\n return self\n def __next__(self):\n next_value = self.value\n self.value += 2\n return next_value\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] |
19,173
|
<p>If you're building an <code>AJA~Xy</code> app, are there any downsides to using <code>JSONP</code> requests/responses even if you're not planning on any <code>cross-domain</code> requests? </p>
<p>The only thing I can think of is that there are a couple extra bytes for the callback wrapper... </p>
<p><strong>Edit:</strong></p>
<p>I found <a href="http://remysharp.com/2007/10/08/what-is-jsonp/" rel="nofollow noreferrer">this</a> which also suggests <code>security and error handling</code> as potential problems... </p>
<blockquote>
<p>There's no error handling. The <code>script injection</code> either works, or it doesn't.
If there's an error from the <code>injection</code>, it'll hit the page, and short of a window wide error handler (bad, bad, very bad), you need to be sure the return value is valid on the <code>server side</code>.</p>
</blockquote>
<p>I don't think <code>error handling</code> is much of a problem... most of us would use a library to generate the <code>JSON</code>... the well-formedness of my response isn't a concern for this question.</p>
<p><strong>and security:</strong></p>
<blockquote>
<p>There are documents out on the web that can help, but as a cursory check, I would check the referrer in the <code>server side</code> script.</p>
</blockquote>
<p>it seems like this is a potential problem with any type of response... certainly, there's nothing unique to <code>JSONP</code> in the security arena...?</p>
|
[
{
"answer_id": 23208,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<script>"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031/"
] |
19,185
|
<p>There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&SiteID=1" rel="nofollow noreferrer">detected by checking for keyboard and mouse events</a>. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.</p>
<p>As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?</p>
|
[
{
"answer_id": 19188,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 3,
"selected": true,
"text": "using System.Runtime.InteropServices;\n\n[DllImport(\"User32.dll\")] \nstatic extern bool GetLastInputInfo(ref LASTINPUTINFO plii);\n\nstruct LASTINPUTINFO \n{\n public uint cbSize;\n public uint dwTime;\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] |
19,193
|
<p>How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this:</p>
<pre><code>#include <iostream>
#include <tree>
using namespace std;
int main()
{
tree<int> myTree;
tree<int>::iterator i = myTree.root();
*i = 42;
tree<int>::iterator j = i.add_child();
*j = 777;
j = j.parent();
if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n";
return 0;
}
</code></pre>
<hr>
<p>Thank you, tree.hh seems to be just what I was looking for.</p>
<blockquote>
<p>If this is for gaining the benefit of
a data-structure holding arbitrary
index types, optimized for searching
and good at insertion then consider
using a map.</p>
<p>A map is an associative container that
has performance guarantees identical
to those of a tree: logarithmic
searching, logarithmic insertion,
logarithmic deletion, linear space.
Internally they are often implemented
as red-black trees, although that is
not a guarantee. Still, as an STL user
all you should care about is the
performance guarantees of the STL
algorithms and data-structures.
Whether they're implemented as trees
or little green men shouldn't matter
to you.</p>
</blockquote>
<p>I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.</p>
|
[
{
"answer_id": 19255,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 4,
"selected": true,
"text": "int main(int, char **)\n {\n tree<string> tr;\n tree<string>::iterator top, one, two, loc, banana;\n\n top=tr.begin();\n one=tr.insert(top, \"one\");\n two=tr.append_child(one, \"two\");\n tr.append_child(two, \"apple\");\n banana=tr.append_child(two, \"banana\");\n tr.append_child(banana,\"cherry\");\n tr.append_child(two, \"peach\");\n tr.append_child(one,\"three\");\n\n loc=find(tr.begin(), tr.end(), \"two\");\n if(loc!=tr.end()) {\n tree<string>::sibling_iterator sib=tr.begin(loc);\n while(sib!=tr.end(loc)) {\n cout << (*sib) << endl;\n ++sib;\n }\n cout << endl;\n tree<string>::iterator sib2=tr.begin(loc);\n tree<string>::iterator end2=tr.end(loc);\n while(sib2!=end2) {\n for(int i=0; i<tr.depth(sib2)-2; ++i) \n cout << \" \";\n cout << (*sib2) << endl;\n ++sib2;\n }\n }\n }\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2222/"
] |
19,201
|
<p>Does anyone use Accurev for Source Control Management? We are switching (eventually) from StarTeam to Accurev.</p>
<p>My initial impression is that the GUI tool is severely lacking, however the underlying engine, and the branches as streams concept is incredible.</p>
<p>The biggest difficulty we are facing is assessing our own DIY tools that interfaced with starteam, and either replacing them with DIY new tools, or finding and purchasing appropriate replacements.</p>
<p>Additionally, is anyone using the AccuWork component for Issue management? Starteam had a very nice change request system, and AccuWork does not come close to matching it. We are evaluating either using Accuwork, or buying a 3rd party package such as JIRA.</p>
<p>Opinions?</p>
|
[
{
"answer_id": 14609643,
"author": "Paul",
"author_id": 70930,
"author_profile": "https://Stackoverflow.com/users/70930",
"pm_score": 4,
"selected": false,
"text": "accurev update -t <transaction-number>"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19201",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
19,236
|
<p>I'm working on a internal web based tool for my company. Part of this tool is another application (The Cruise Control Dashboard) that runs in its own Virtual Directory under my root application.</p>
<p>I wanted to limit access to this internal application by setting up Forms Authentication on it, and having a login form in the root application.</p>
<p>I put the following into the root applications web.config:</p>
<pre><code><location path="ccnet">
<system.web>
<authentication mode="Forms">
<forms loginUrl="/default.aspx" timeout="5000"/>
</authentication>
<authorization>
<allow users="?"/>
<deny users="?"/>
</authorization>
</system.web>
</location>
</code></pre>
<p>However, the Forms Authentication does not appear to be working, it does not redirect back to the login page when I access that application directly.</p>
<p>I have a feeling I have the <allow> and <deny> tags set wrong. Can someone clarify?</p>
|
[
{
"answer_id": 19239,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<deny users=\"?\"/>\n"
},
{
"answer_id": 19253,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<deny users=\"?\"/>\n"
},
{
"answer_id": 19287,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 2,
"selected": false,
"text": "<authentication mode=\"Forms\"> \n <forms name=\"{name}\" path=\"/\" ...>\n</authentication>\n"
},
{
"answer_id": 19291,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "If CustomAuthenticate(Login1.UserName, Login1.Password) Then\n FormsAuthentication.RedirectFromLoginPage(Login1.UserName, False)\nElse\n e.Authenticated = False\nEnd If\n"
},
{
"answer_id": 19316,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<machineKey validationKey=\"AutoGenerate\" decryptionKey=\"AutoGenerate\" validation=\"SHA1\" />\n"
},
{
"answer_id": 41677870,
"author": "Kevin Pluck",
"author_id": 1507920,
"author_profile": "https://Stackoverflow.com/users/1507920",
"pm_score": 0,
"selected": false,
"text": "<forms loginUrl=\"/pages/login.aspx\" enableCrossAppRedirects=\"true\"...\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
19,280
|
<p>I could only find the function <code>confirm()</code> that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?</p>
|
[
{
"answer_id": 19290,
"author": "Cade",
"author_id": 565,
"author_profile": "https://Stackoverflow.com/users/565",
"pm_score": 4,
"selected": true,
"text": "prompt"
},
{
"answer_id": 19307,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "confirm()"
},
{
"answer_id": 22914957,
"author": "mason",
"author_id": 1139830,
"author_profile": "https://Stackoverflow.com/users/1139830",
"pm_score": 1,
"selected": false,
"text": "<script>\n $(function() {\n $( \"#dialog-confirm\" ).dialog({\n resizable: false,\n height:140,\n modal: true,\n buttons: {\n \"Yes\": function() {\n $( this ).dialog( \"close\" );\n alert(\"You chose Yes!\");\n },\n \"No\": function() {\n $( this ).dialog( \"close\" );\n alert(\"You chose No!\");\n }\n }\n });\n });\n </script>\n\n<div id=\"dialog-confirm\" title=\"Are you sure you want to continue?\">\n <p><span class=\"ui-icon ui-icon-alert\" style=\"float:left; margin:0 7px 20px 0;\"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>\n</div>\n"
},
{
"answer_id": 38184570,
"author": "Shree",
"author_id": 5698411,
"author_profile": "https://Stackoverflow.com/users/5698411",
"pm_score": 0,
"selected": false,
"text": " <div id=\"dialog_box\" class=\"mnk-modal-bg\" style=\"display:none\">\n <div id=\"dbg\" class=\"mnk-modal-box\">\n <i class=\"uk-icon-exclamation-triangle\" style=\"color:#757575; padding-right:5px;\">\n </i>Confirm?\n <div class=\"uk-text-center\" style=\"margin-top:10px;\">\n <button class=\"md-btn md-btn-small md-btn-primary\" id=\"ok_btn\">\n <i class=\"uk-icon-save\" style=\"padding-right:3px;\"></i>OK\n </button>\n <button class=\"md-btn md-btn-small md-btn-danger\" id=\"close_btn\">\n <i class=\"uk-icon-remove\" style=\"padding-right:3px;\"></i>Cancel\n </button>\n </div>\n </div>\n"
},
{
"answer_id": 48141559,
"author": "Ewomazino Ukah",
"author_id": 5746074,
"author_profile": "https://Stackoverflow.com/users/5746074",
"pm_score": 1,
"selected": false,
"text": "swal(\"Are you sure you want to do this?\", {\n buttons: [\"yes\", \"no\"],\n});"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
19,294
|
<p>In my code behind I wire up my events like so:</p>
<pre><code>protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnUpdateUser.Click += btnUpateUserClick;
}
</code></pre>
<p>I've done it this way because that's what I've seen in examples. </p>
<ul>
<li>Does the base.OnInit() method need to be called? </li>
<li>Will it be implicitly be called? </li>
<li>Is it better to call it at the beginning of the method or at the end? </li>
<li>What would be an example where confusion over the base method can get you in trouble? </li>
</ul>
|
[
{
"answer_id": 19299,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "protected virtual void OnClick(EventArgs e)\n{\n if (Click != null) Click(this, e);\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1894/"
] |
19,295
|
<p>I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.</p>
<p>I'm specifically refering to something that would work with the jstl tags such as</p>
<pre><code><fmt:setlocale>
<fmt:bundle>
<fmt:setBundle>
<fmt:message>
</code></pre>
<p>I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.</p>
|
[
{
"answer_id": 19308,
"author": "danb",
"author_id": 2031,
"author_profile": "https://Stackoverflow.com/users/2031",
"pm_score": 3,
"selected": true,
"text": "HttpSession session = .. [get hold of the session] \nResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream] \nLocale locale = .. [get hold of the locale]\njavax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale));\n"
},
{
"answer_id": 19377,
"author": "dlinsin",
"author_id": 198,
"author_profile": "https://Stackoverflow.com/users/198",
"pm_score": 1,
"selected": false,
"text": "<bean:message key=\"impressum.text\" />"
},
{
"answer_id": 32325,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 4,
"selected": false,
"text": "ResourceBundle bundle = ResourceBundle.getBundle(\"AwesomeBundle\", locale, DbResourceBundle.getMyControl());\njavax.servlet.jsp.jstl.core.Config.set(actionBeanContext.getRequest(), Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, locale));\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19295",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] |
19,318
|
<p>I have an ASP.NET webservice with along the lines of:</p>
<pre><code>[WebService(Namespace = "http://internalservice.net/messageprocessing")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class ProvisioningService : WebService
{
[WebMethod]
public XmlDocument ProcessMessage(XmlDocument message)
{
// ... do stuff
}
}
</code></pre>
<p>I am calling the web service from ASP using something like:</p>
<pre><code>provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl"
Set service = CreateObject("MSSOAP.SoapClient30")
service.ClientProperty("ServerHTTPRequest") = True
Call service.MSSoapInit(provWSDL)
xmlMessage = "<request><task>....various xml</task></request>"
result = service.ProcessMessage(xmlMessage)
</code></pre>
<p>The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:</p>
<pre><code><request xmlns="http://internalservice.net/messageprocessing">
<task>....various xml</task>
</request>
</code></pre>
<p>When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends:</p>
<pre><code><SOAP-ENV:Envelope
xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema"
xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance"
xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing">
<request>
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code></pre>
<p>Whilst the .NET client sends:</p>
<pre><code><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<ProcessMessage xmlns="http://internalservice.net/messageprocessing">
<message>
<request xmlns="">
<task>...stuff to do</task>
</request>
</message>
</ProcessMessage>
</soap:Body>
</soap:Envelope>
</code></pre>
<p>It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this.</p>
<p>Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.</p>
|
[
{
"answer_id": 19324,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "XmlDocument changeDocumentNamespace(XmlDocument doc, string newNamespace) \n{ \n if (doc.DocumentElement.NamespaceURI.Length > 0) \n {\n doc.DocumentElement.SetAttribute(\"xmlns\", newNameSpace);\n XmlDocument newDoc = new XmlDocument();\n newDoc.LoadXml(doc.OuterXml);\n return newDoc;\n }\n else \n {\n return doc;\n }\n}\n"
},
{
"answer_id": 19328,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 1,
"selected": true,
"text": "<ProcessMessage xmlns=\"http://internalservice.net/messageprocessing\">\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419/"
] |
19,339
|
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p>
<p><strong>For example:</strong></p>
<pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
# and I want to become...
result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
</code></pre>
<p>Is there a builtin function that does that?</p>
|
[
{
"answer_id": 19343,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 11,
"selected": true,
"text": "zip"
},
{
"answer_id": 25193,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 5,
"selected": false,
"text": "result = ([ a for a,b in original ], [ b for a,b in original ])\n"
},
{
"answer_id": 4578299,
"author": "Chris",
"author_id": 307678,
"author_profile": "https://Stackoverflow.com/users/307678",
"pm_score": 4,
"selected": false,
"text": ">>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])\n[('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n"
},
{
"answer_id": 22115957,
"author": "wassimans",
"author_id": 313127,
"author_profile": "https://Stackoverflow.com/users/313127",
"pm_score": 5,
"selected": false,
"text": "zip(*iterable)"
},
{
"answer_id": 35012020,
"author": "G M",
"author_id": 2132157,
"author_profile": "https://Stackoverflow.com/users/2132157",
"pm_score": 2,
"selected": false,
"text": "X=[1,2,3,4]\nY=['a','b','c','d']\nXY=zip(X,Y)\n"
},
{
"answer_id": 35813331,
"author": "Noyer282",
"author_id": 5918464,
"author_profile": "https://Stackoverflow.com/users/5918464",
"pm_score": 4,
"selected": false,
"text": ">>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> tuple([list(tup) for tup in zip(*original)])\n(['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n"
},
{
"answer_id": 50799018,
"author": "Waylon Flinn",
"author_id": 74291,
"author_profile": "https://Stackoverflow.com/users/74291",
"pm_score": 1,
"selected": false,
"text": "zip(*zipped)"
},
{
"answer_id": 51991395,
"author": "jpp",
"author_id": 9209546,
"author_profile": "https://Stackoverflow.com/users/9209546",
"pm_score": 2,
"selected": false,
"text": "tuple"
},
{
"answer_id": 52519708,
"author": "Charlie Clark",
"author_id": 2385133,
"author_profile": "https://Stackoverflow.com/users/2385133",
"pm_score": 1,
"selected": false,
"text": "zip(*seq)"
},
{
"answer_id": 53885047,
"author": "Azat Ibrakov",
"author_id": 5997596,
"author_profile": "https://Stackoverflow.com/users/5997596",
"pm_score": 3,
"selected": false,
"text": "def transpose_finite_iterable(iterable):\n return zip(*iterable) # `itertools.izip` for Python 2 users\n"
},
{
"answer_id": 54013413,
"author": "Neil G",
"author_id": 99989,
"author_profile": "https://Stackoverflow.com/users/99989",
"pm_score": 2,
"selected": false,
"text": ">>> from more_itertools import unzip\n>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n>>> [list(x) for x in unzip(original)]\n[['a', 'b', 'c', 'd'], [1, 2, 3, 4]] \n"
},
{
"answer_id": 61685860,
"author": "Trasp",
"author_id": 1388027,
"author_profile": "https://Stackoverflow.com/users/1388027",
"pm_score": 2,
"selected": false,
"text": "zip(*args)"
},
{
"answer_id": 71385682,
"author": "mkearney",
"author_id": 5435428,
"author_profile": "https://Stackoverflow.com/users/5435428",
"pm_score": 0,
"selected": false,
"text": "original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\nlist(zip(*original))\n# [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] |
19,347
|
<p>At my university most of my classes have been in Java. I have also recently learned C# (and the Visual Studio environment) at a summer internship. Now I'm taking an Intro to Computer Graphics class and the grad student teaching the class prefers us to use C++ to access the OpenGL bindings via GLUT.</p>
<p>Does anyone have any good resources on how to make a good transition from Java/C# to C++? Obviously pointers are going to be a big issue, but any other things I should be looking out for? Any tutorials, guides, etc. would be very helpful!</p>
<p>Thanks!</p>
|
[
{
"answer_id": 19439,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "Thing mything = new Thing(); // mything is an object reference\nmything.method();\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
] |
19,353
|
<p>I'm tasked with building a .NET client app to detect silence in a WAV files.</p>
<p>Is this possible with the built-in Windows APIs? Or alternately, any good libraries out there to help with this?</p>
|
[
{
"answer_id": 21500363,
"author": "Aleks",
"author_id": 3258422,
"author_profile": "https://Stackoverflow.com/users/3258422",
"pm_score": -1,
"selected": false,
"text": "private static void SkipSilent(string fileName, short silentLevel)\n{\n WaveReader wr = new WaveReader(File.OpenRead(fileName));\n IntPtr format = wr.ReadFormat();\n WaveWriter ww = new WaveWriter(File.Create(fileName + \".wav\"), \n AudioCompressionManager.FormatBytes(format));\n int i = 0;\n while (true)\n {\n byte[] data = wr.ReadData(i, 1);\n if (data.Length == 0)\n {\n break;\n }\n if (!AudioCompressionManager.CheckSilent(format, data, silentLevel))\n {\n ww.WriteData(data);\n }\n }\n ww.Close();\n wr.Close();\n}\n"
},
{
"answer_id": 46024371,
"author": "41686d6564 stands w. Palestine",
"author_id": 8967612,
"author_profile": "https://Stackoverflow.com/users/8967612",
"pm_score": 3,
"selected": false,
"text": "AudioFileReader"
},
{
"answer_id": 60262870,
"author": "Ibai",
"author_id": 9955237,
"author_profile": "https://Stackoverflow.com/users/9955237",
"pm_score": 3,
"selected": false,
"text": "static class AudioFileReaderExt\n{\n\n\n private static bool IsSilence(float amplitude, sbyte threshold)\n {\n double dB = 20 * Math.Log10(Math.Abs(amplitude));\n return dB < threshold;\n }\n\n private static bool IsBeep(float amplitude, sbyte threshold)\n {\n double dB = 20 * Math.Log10(Math.Abs(amplitude));\n return dB > threshold;\n }\n\n public static double GetBeepDuration(this AudioFileReader reader,\n double StartPosition, sbyte silenceThreshold = -40)\n {\n int counter = 0;\n bool eof = false;\n int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);\n if (initial > reader.Length) return -1;\n reader.Position = initial;\n var buffer = new float[reader.WaveFormat.SampleRate * 4];\n while (!eof)\n {\n int samplesRead = reader.Read(buffer, 0, buffer.Length);\n if (samplesRead == 0)\n eof = true;\n\n for (int n = initial; n < samplesRead; n++)\n {\n if (IsBeep(buffer[n], silenceThreshold))\n {\n counter++;\n }\n else\n {\n eof=true; break;\n }\n }\n }\n\n\n double silenceSamples = (double)counter / reader.WaveFormat.Channels;\n double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;\n\n return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;\n }\n\n public static double GetSilenceDuration(this AudioFileReader reader,\n double StartPosition, sbyte silenceThreshold = -40)\n {\n int counter = 0;\n bool eof = false;\n int initial = (int)(StartPosition * reader.WaveFormat.Channels * reader.WaveFormat.SampleRate / 1000);\n if (initial > reader.Length) return -1;\n reader.Position = initial;\n var buffer = new float[reader.WaveFormat.SampleRate * 4];\n while (!eof)\n {\n int samplesRead = reader.Read(buffer, 0, buffer.Length);\n if (samplesRead == 0) \n eof=true;\n\n for (int n = initial; n < samplesRead; n++)\n {\n if (IsSilence(buffer[n], silenceThreshold))\n {\n counter++;\n }\n else\n {\n eof=true; break;\n }\n }\n }\n\n\n double silenceSamples = (double)counter / reader.WaveFormat.Channels;\n double silenceDuration = (silenceSamples / reader.WaveFormat.SampleRate) * 1000;\n\n return TimeSpan.FromMilliseconds(silenceDuration).TotalMilliseconds;\n }\n\n\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
19,355
|
<p>In a .NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). </p>
<p>How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers).</p>
<p><hr />
Edit: Can the "<code>file</code>" method suggested by @Jonathon be somehow used with the <code>connectionStrings</code> section?</p>
|
[
{
"answer_id": 19360,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<target name=\"copyconfigs\" depends=\"clean\">\n <foreach item=\"File\" property=\"filename\" unless=\"${string::get-length(ConfigPrefix) == 0}\">\n <in>\n <items>\n <include name=\"**/${ConfigPrefix}App.config\" />\n <include name=\"**/${ConfigPrefix}connectionstrings.config\" />\n <include name=\"**/${ConfigPrefix}web.config\" />\n </items>\n </in>\n <do>\n <copy overwrite=\"true\" file=\"${filename}\" tofile=\"${string::replace(filename, ConfigPrefix,'')}\" />\n </do>\n </foreach></target>\n"
},
{
"answer_id": 19361,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<appSettings file=\"localoveride.config\"/>\n"
},
{
"answer_id": 19380,
"author": "Scott Muc",
"author_id": 1894,
"author_profile": "https://Stackoverflow.com/users/1894",
"pm_score": 2,
"selected": false,
"text": "public class ConnectionString\n{\n public static string Default\n {\n get \n { \n if (string.IsNullOrEmpty(ConfigurationManager.AppSettings[\"DefaultConnectionStringName\"]))\n throw new ApplicationException(\"DefaultConnectionStringName must be set in the appSettings\");\n\n return GetByName(ConfigurationManager.AppSettings[\"DefaultConnectionStringName\"]);\n }\n }\n\n public static string GetByName(string dsn)\n {\n return ConfigurationManager.ConnectionStrings[dsn].ConnectionString;\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
19,388
|
<p>I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?</p>
<p>I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "<code>GOTO 10</code>"-like command...</p>
|
[
{
"answer_id": 19398,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "for(...) {\n for (...) {\n for (...) {\n // some code\n if (x) GOTO outside;\n }\n }\n} \n:outside\n"
},
{
"answer_id": 19403,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 4,
"selected": true,
"text": "<?php\nfor ($i = 0; $i < 9; $i++) {\n if (true) {\n break blah;\n }\n echo \"not shown\";\n blah:\n echo \"iteration $i\\n\";\n}\n?>\n"
},
{
"answer_id": 19452,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 1,
"selected": false,
"text": "function findItem(...) {\n for (...) {\n for (...) {\n for (...) {\n if (x) {\n return theItem;\n }\n }\n }\n }\n}\n\n// no need for label now\ntheItem = findItem(a, b, c);\n"
},
{
"answer_id": 1078480,
"author": "Ira Baxter",
"author_id": 120163,
"author_profile": "https://Stackoverflow.com/users/120163",
"pm_score": 3,
"selected": false,
"text": "a: for (...) {\n b: for (...) {\n c: for (...) {\n ...\n break a;\n }\n }\n }\n"
},
{
"answer_id": 16190143,
"author": "Jurijs Nesterovs",
"author_id": 2181738,
"author_profile": "https://Stackoverflow.com/users/2181738",
"pm_score": 0,
"selected": false,
"text": "goto"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2238/"
] |
19,409
|
<p>This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this:</p>
<pre><code># count.s: print the numbers from 0 to 100.
.text
string: .asciz "%d\n"
.globl _main
_main:
movl $0, %eax # The starting point/current value.
movl $100, %ebx # The ending point.
_loop:
# Display the current value.
pushl %eax
pushl $string
call _printf
addl $8, %esp
# Check against the ending value.
cmpl %eax, %ebx
je _end
# Increment the current value.
incl %eax
jmp _loop
_end:
</code></pre>
<p>All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem.</p>
<p>(The formatting's a little messed up, but nothing major).</p>
|
[
{
"answer_id": 19453,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 5,
"selected": true,
"text": "# count.s: print the numbers from 0 to 100. \n .text\nstring: .asciz \"%d\\n\"\n .globl _main\n\n_main:\n movl $0, %eax # The starting point/current value.\n movl $100, %ebx # The ending point.\n\n_loop:\n # Remember your registers.\n pushl %eax\n pushl %ebx\n\n # Display the current value.\n pushl %eax\n pushl $string\n call _printf\n addl $8, %esp\n\n # reinstate registers.\n popl %ebx\n popl %eax\n\n # Check against the ending value.\n cmpl %eax, %ebx\n je _end\n\n # Increment the current value.\n incl %eax\n jmp _loop \n\n_end:\n"
},
{
"answer_id": 21148,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": -1,
"selected": false,
"text": "%ebp"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
19,412
|
<p>How can I request a random row (or as close to truly random as is possible) in pure SQL?</p>
|
[
{
"answer_id": 19414,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": false,
"text": "SELECT TOP 1 * FROM MyTable ORDER BY newid()\n"
},
{
"answer_id": 19415,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": " SELECT * FROM table ORDER BY RAND() LIMIT 1\n"
},
{
"answer_id": 19416,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "select top 1 * from mytable order by newid()\n"
},
{
"answer_id": 19419,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": 11,
"selected": true,
"text": "SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n"
},
{
"answer_id": 19421,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 2,
"selected": false,
"text": "randomNo = random()\nexecSql(\"SELECT TOP 1 * FROM MyTable WHERE MyTable.Randomness > $randomNo\")\n"
},
{
"answer_id": 19422,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 8,
"selected": false,
"text": "SELECT * FROM table ORDER BY RAND() LIMIT 1\n"
},
{
"answer_id": 182584,
"author": "Santiago Cepas",
"author_id": 6547,
"author_profile": "https://Stackoverflow.com/users/6547",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(), SalesOrderID) & 0x7fffffff AS float)\n/ CAST (0x7fffffff AS int)\n"
},
{
"answer_id": 922443,
"author": "Rob Boek",
"author_id": 27179,
"author_profile": "https://Stackoverflow.com/users/27179",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM Sales.SalesOrderDetail\nWHERE 0.01 >= CAST(CHECKSUM(NEWID(),SalesOrderID) & 0x7fffffff AS float)\n / CAST (0x7fffffff AS int)\n"
},
{
"answer_id": 1074261,
"author": "hegemon",
"author_id": 113083,
"author_profile": "https://Stackoverflow.com/users/113083",
"pm_score": 1,
"selected": false,
"text": "explain analyze select * from cms_refs where rec_id in \n (select (random()*(select last_value from cms_refs_rec_id_seq))::bigint \n from generate_series(1,10))\n limit 1;\n"
},
{
"answer_id": 3286484,
"author": "alphadogg",
"author_id": 59494,
"author_profile": "https://Stackoverflow.com/users/59494",
"pm_score": 2,
"selected": false,
"text": "SELECT TOP 1\n word\nFROM (\n SELECT TOP(@idx)\n word \n FROM\n dbo.DictionaryAbridged WITH(NOLOCK)\n ORDER BY\n word DESC\n) AS D\nORDER BY\n word ASC\n"
},
{
"answer_id": 4497240,
"author": "Neel",
"author_id": 549625,
"author_profile": "https://Stackoverflow.com/users/549625",
"pm_score": 5,
"selected": false,
"text": "ORDER BY NEWID()\n"
},
{
"answer_id": 4856912,
"author": "DAVID ",
"author_id": 597598,
"author_profile": "https://Stackoverflow.com/users/597598",
"pm_score": 0,
"selected": false,
"text": "WITH TEMP AS (\nSELECT COMLUMN, RAND() AS IDX FROM TABLE)\nSELECT COLUMN FROM TABLE WHERE IDX > .5\nFETCH FIRST 1 ROW ONLY\n"
},
{
"answer_id": 6729183,
"author": "Jai - gotaninterviewcall",
"author_id": 849458,
"author_profile": "https://Stackoverflow.com/users/849458",
"pm_score": 1,
"selected": false,
"text": "new id()"
},
{
"answer_id": 12852040,
"author": "karmakaze",
"author_id": 720030,
"author_profile": "https://Stackoverflow.com/users/720030",
"pm_score": 2,
"selected": false,
"text": ""
},
{
"answer_id": 17768021,
"author": "Sophy",
"author_id": 833394,
"author_profile": "https://Stackoverflow.com/users/833394",
"pm_score": 2,
"selected": false,
"text": " SELECT name\n FROM random AS r1 JOIN\n (SELECT (RAND() *\n (SELECT MAX(id)\n FROM random)) AS id)\n AS r2\n WHERE r1.id >= r2.id\n ORDER BY r1.id ASC\n LIMIT 1\n"
},
{
"answer_id": 20661166,
"author": "Mmmh mmh",
"author_id": 1582182,
"author_profile": "https://Stackoverflow.com/users/1582182",
"pm_score": 0,
"selected": false,
"text": "SET @i = (SELECT FLOOR(RAND() * COUNT(*)) FROM table); PREPARE get_stmt FROM 'SELECT * FROM table LIMIT ?, 1'; EXECUTE get_stmt USING @i;\n"
},
{
"answer_id": 25021581,
"author": "klyd",
"author_id": 471810,
"author_profile": "https://Stackoverflow.com/users/471810",
"pm_score": 1,
"selected": false,
"text": "select top 10 percent *\nfrom table_name\norder by rand(checksum(*))\n"
},
{
"answer_id": 25642622,
"author": "sev3ryn",
"author_id": 1167502,
"author_profile": "https://Stackoverflow.com/users/1167502",
"pm_score": 0,
"selected": false,
"text": "SELECT *\nFROM employee sample(1)\nWHERE rownum=1\n"
},
{
"answer_id": 29676451,
"author": "David Knight",
"author_id": 161332,
"author_profile": "https://Stackoverflow.com/users/161332",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 100 * FROM employee ORDER BY CRYPT_GEN_RANDOM(10)\n"
},
{
"answer_id": 40839843,
"author": "Luigi04",
"author_id": 1964666,
"author_profile": "https://Stackoverflow.com/users/1964666",
"pm_score": 1,
"selected": false,
"text": "Select FIRST 1 column from table ORDER BY RAND()\n"
},
{
"answer_id": 42723045,
"author": "forsberg",
"author_id": 1624397,
"author_profile": "https://Stackoverflow.com/users/1624397",
"pm_score": 2,
"selected": false,
"text": "SELECT MAX(ID) FROM TABLE;\n"
},
{
"answer_id": 43461850,
"author": "Chris Arbogast",
"author_id": 5361251,
"author_profile": "https://Stackoverflow.com/users/5361251",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 1 * FROM [table] \nTABLESAMPLE (500 ROWS) \nORDER BY NEWID()\n"
},
{
"answer_id": 49542866,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "select * from MyTable ORDER BY id OFFSET n ROW FETCH NEXT 1 ROWS ONLY\n"
},
{
"answer_id": 50562274,
"author": "Endri",
"author_id": 4699575,
"author_profile": "https://Stackoverflow.com/users/4699575",
"pm_score": 0,
"selected": false,
"text": "num_value"
},
{
"answer_id": 51205622,
"author": "Nitin",
"author_id": 2669383,
"author_profile": "https://Stackoverflow.com/users/2669383",
"pm_score": 1,
"selected": false,
"text": "SELECT column FROM table\nORDER BY RAND()\nLIMIT 1\n"
},
{
"answer_id": 64543769,
"author": "Kuks",
"author_id": 14219455,
"author_profile": "https://Stackoverflow.com/users/14219455",
"pm_score": 0,
"selected": false,
"text": "select r.id, r.name from table AS r\nINNER JOIN(select CEIL(RAND() * (select MAX(id) from table)) as id) as r1\nON r.id >= r1.id ORDER BY r.id ASC LIMIT 1\n"
},
{
"answer_id": 66179699,
"author": "user2864740",
"author_id": 2864740,
"author_profile": "https://Stackoverflow.com/users/2864740",
"pm_score": 2,
"selected": false,
"text": "[0, max_rows)"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/473/"
] |
19,433
|
<p>What is a good free library for editing MP3s/FLACs. </p>
<p>By editing I mean:</p>
<ul>
<li>Cutting audio file into multiple parts</li>
<li>Joining multiple audio files together</li>
<li>Increase playback speed of file without affecting the pitch (eg. podcasts up to 1.3x)</li>
<li>Re-encoding audio file from Flac -> MP3 or vice versa</li>
</ul>
<p>I don't mean software, I mean a library that I can use within another application. Programming language agnostic.</p>
|
[
{
"answer_id": 19434,
"author": "Christian Hagelid",
"author_id": 202,
"author_profile": "https://Stackoverflow.com/users/202",
"pm_score": 1,
"selected": false,
"text": "* Record live audio.\n* Convert tapes and records into digital recordings or CDs.\n* Edit Ogg Vorbis, MP3, WAV or AIFF sound files.\n* Cut, copy, splice or mix sounds together.\n* Change the speed or pitch of a recording.\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915/"
] |
19,436
|
<p>I have a datalist with a OnDeleteCommand="Delete_Command".</p>
<p>I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event.</p>
<p>If I use DataKeyField I'm limited to only one key.
Any workarounds for this?</p>
|
[
{
"answer_id": 19447,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 2,
"selected": true,
"text": "gridView.DataKeys[rowNum][dataKeyName]\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] |
19,442
|
<p>How can I create this file in a directory in windows 2003 SP2:</p>
<pre><code>.hgignore
</code></pre>
<p>I get error: You must type a file name.</p>
|
[
{
"answer_id": 19443,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 6,
"selected": true,
"text": "echo Hello there! > .hgignore\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] |
19,454
|
<p>Following on from my recent question on <a href="https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result">Large, Complex Objects as a Web Service Result</a>. I have been thinking about how I can ensure all future child classes are serializable to XML.</p>
<p>Now, obviously I could implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="noreferrer">IXmlSerializable</a> interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a <em>string</em> so I may just write my own.</p>
<p>However, to serialize to XML, I am simply decorating the class and its members with the <em>Xml???</em> attributes ( <em>XmlRoot</em> , <em>XmlElement</em> etc.) and then passing it to the <em>XmlSerializer</em> and a <em>StringWriter</em> to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.</p>
<p>The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.</p>
<p><strong>Is there any way to enforce attribute decoration? Can this be done with FxCop?</strong> (I have not used FxCop yet)</p>
<h3>UPDATE:</h3>
<p>Sorry for the delay in getting this close off guys, lots to do!</p>
<p>Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455">Fredrik Kalseth's answer</a> was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!</p>
<p>+1 to the other guys for similar suggestions :)</p>
|
[
{
"answer_id": 19455,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 5,
"selected": true,
"text": "[TestClass]\npublic class When_type_inherits_MyObject\n{\n private readonly List<Type> _types = new List<Type>();\n\n public When_type_inherits_MyObject()\n {\n // lets find all types that inherit from MyObject, directly or indirectly\n foreach(Type type in typeof(MyObject).Assembly.GetTypes())\n {\n if(type.IsClass && typeof(MyObject).IsAssignableFrom(type))\n {\n _types.Add(type);\n }\n }\n }\n\n [TestMethod]\n public void Properties_have_XmlElement_attribute\n {\n foreach(Type type in _types)\n {\n foreach(PropertyInfo property in type.GetProperties())\n {\n object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false);\n Assert.IsTrue(attribs.Count > 0, \"Missing XmlElementAttribute on property \" + property.Name + \" in type \" + type.FullName);\n }\n }\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
19,461
|
<p>I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.</p>
<p>The coordinates need to be relative to the image top and left.</p>
|
[
{
"answer_id": 19464,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 3,
"selected": false,
"text": "<input id=\"info\" type=\"image\">\n"
},
{
"answer_id": 1222641,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Point mousePoint = e.GetPosition( this );\n"
},
{
"answer_id": 46995289,
"author": "TessavWalstijn",
"author_id": 7185314,
"author_profile": "https://Stackoverflow.com/users/7185314",
"pm_score": 1,
"selected": false,
"text": "let img = document.getElementById(\"canvas\");\n\nimg.x = img.getBoundingClientRect().left;\nimg.y = img.getBoundingClientRect().top;\n\nfunction click(e) {\n document.getElementById(\"output\").innerHTML = \"X coords: \" + (e.clientX - img.x) + \"<br> Y coords: \" + (e.clientY - img.y);\n}\n\nimg.addEventListener(\"click\", click);"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
19,466
|
<p>How can I check <code>file permissions</code>, without having to run operating system specific command via <code>passthru()</code> or <code>exec()</code>?</p>
|
[
{
"answer_id": 19472,
"author": "Željko Živković",
"author_id": 1926,
"author_profile": "https://Stackoverflow.com/users/1926",
"pm_score": 6,
"selected": true,
"text": "clearstatcache();\necho substr(sprintf('%o', fileperms('/etc/passwd')), -4);\n"
},
{
"answer_id": 11434314,
"author": "OzzyCzech",
"author_id": 355316,
"author_profile": "https://Stackoverflow.com/users/355316",
"pm_score": 1,
"selected": false,
"text": "substr(decoct(fileperms(__DIR__)), -4); // 0777\nsubstr(decoct(fileperms(__DIR__)), -3); // 777\n"
},
{
"answer_id": 16083949,
"author": "Maciej Sz",
"author_id": 1697320,
"author_profile": "https://Stackoverflow.com/users/1697320",
"pm_score": 3,
"selected": false,
"text": "function checkPerms($path)\n{\n clearstatcache(null, $path);\n return decoct( fileperms($path) & 0777 );\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
19,481
|
<p>Another discussion (we've been having a lot of them these days!) in our work is whether data binding is a bad idea or not.</p>
<p>Personally, I think it is a Bad Thing™.</p>
<p>My reasons are thrice:</p>
<ol>
<li><p>It circumvents my well architectured MVP framework - with databinding, the view communicates bi-directionally with a model. Ewww.</p></li>
<li><p>It promotes hooking up view controls to datafields at design time. In my experience, this leads to vital code (binding column A to Field X) being obscure and hidden away in some designer file. IMO this code should be explicit and in-your-face, so that it is easy to modify and see what is going on, without having to use a clunky designer interface.</p></li>
<li><p>Relating to Point #1 this direct binding makes it harder to isolate each component (view, model, controller/presenter) and unit-test. </p></li>
</ol>
<p>The pros are that it is easy to set up, and you can take advantage of some nice features (validation etc) which come with the plumbing already done for you. </p>
<p>But for me, databinding becomes much more of a hindrance when dealing with a large data-centric application.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 663652,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 2,
"selected": false,
"text": "Bind()"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1193/"
] |
19,487
|
<p>I generally use a manual process:</p>
<ol>
<li>Look at the page, figure out the semantic elements, and build the HTML</li>
<li>Slice up the images I think I'll need</li>
<li>Start writing CSS</li>
<li>Tweak and repeat different steps as necessary</li>
</ol>
<p>Got a better approach, or a tool?</p>
|
[
{
"answer_id": 22078,
"author": "Andy",
"author_id": 1993,
"author_profile": "https://Stackoverflow.com/users/1993",
"pm_score": 3,
"selected": false,
"text": "<ul id=\"menu\">\n <li id=\"home\"><a href=\"/\" title=\"Go to Homepage\">Home</a></li>\n <li id=\"about\"><a href=\"/about\" title=\"More about us\">About</a></li>\n</ul>\n"
},
{
"answer_id": 22087,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 4,
"selected": true,
"text": "<label>"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
19,516
|
<p>Here is a simplification of my database:</p>
<pre>Table: Property
Fields: ID, Address
Table: Quote
Fields: ID, PropertyID, BespokeQuoteFields...
Table: Job
Fields: ID, PropertyID, BespokeJobFields...</pre>
<p>Then we have other tables that relate to the <strong>Quote</strong> and <strong>Job</strong> tables individually.</p>
<p>I now need to add a <strong>Message</strong> table where users can record telephone messages left by customers regarding Jobs and Quotes.</p>
<p>I could create two identical tables (<strong>QuoteMessage</strong> and <strong>JobMessage</strong>), but this violates the DRY principal and seems messy.</p>
<p>I could create one <strong>Message</strong> table:</p>
<pre>Table: Message
Fields: ID, RelationID, RelationType, OtherFields...</pre>
<p>But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on.</p>
<p>Is there an elegant solution to this problem, or am I ultimately going to have to hack something together?</p>
<p>Burns</p>
|
[
{
"answer_id": 19521,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": true,
"text": "Table: Message\nFields: Id, TimeReceived, MessageDetails, WhateverElse...\n"
},
{
"answer_id": 19545,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "Table: Message\nFields: Id, MessageTypeId, Text, ...\nPrimary Key: Id, MessageTypeId\nUnique: Id\n\nTable: MessageType\nFields: Id, Name\nValues: 1, \"Quote\" : 2, \"Job\"\n\nTable: QuoteMessage\nFields: Id, MessageId, MessageTypeId, QuoteId\nConstraints: MessageTypeId = 1\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n QuoteId = Quote.QuoteId\n\nTable: JobMessage\nFields: Id, MessageId, MessageTypeId, JobId\nConstraints: MessageTypeId = 2\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n JobId = Job.QuoteId\n"
},
{
"answer_id": 19670,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 1,
"selected": false,
"text": "QUOTEMESSAGE"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] |
19,517
|
<p>I was reading the example chapter from <a href="http://www.manning.com/rahien/" rel="nofollow noreferrer">the book by Ayende</a> and on the website of <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">the Boo language</a> I saw a reference to the <a href="http://specter.sourceforge.net/" rel="nofollow noreferrer">Specter BDD Framework</a>.</p>
<p>I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.</p>
<p>Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.</p>
<hr>
<p>A few year later visiting this question. I think we can safely assume <a href="http://www.specflow.org/" rel="nofollow noreferrer">Specflow</a> and some others like <a href="http://nspec.org/" rel="nofollow noreferrer">NSpec</a> became the tools we are using.</p>
|
[
{
"answer_id": 19521,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": true,
"text": "Table: Message\nFields: Id, TimeReceived, MessageDetails, WhateverElse...\n"
},
{
"answer_id": 19545,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "Table: Message\nFields: Id, MessageTypeId, Text, ...\nPrimary Key: Id, MessageTypeId\nUnique: Id\n\nTable: MessageType\nFields: Id, Name\nValues: 1, \"Quote\" : 2, \"Job\"\n\nTable: QuoteMessage\nFields: Id, MessageId, MessageTypeId, QuoteId\nConstraints: MessageTypeId = 1\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n QuoteId = Quote.QuoteId\n\nTable: JobMessage\nFields: Id, MessageId, MessageTypeId, JobId\nConstraints: MessageTypeId = 2\nReferences: (MessageId, MessageTypeId) = (Message.Id, Message.MessageTypeId)\n JobId = Job.QuoteId\n"
},
{
"answer_id": 19670,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 1,
"selected": false,
"text": "QUOTEMESSAGE"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4367/"
] |
19,553
|
<p>I have a "Status" class in C#, used like this:</p>
<pre><code>Status MyFunction()
{
if(...) // something bad
return new Status(false, "Something went wrong")
else
return new Status(true, "OK");
}
</code></pre>
<p>You get the idea.
All callers of MyFunction <em>should</em> check the returned Status:</p>
<pre><code>Status myStatus = MyFunction();
if ( ! myStatus.IsOK() )
// handle it, show a message,...
</code></pre>
<p>Lazy callers however can ignore the Status.</p>
<pre><code>MyFunction(); // call function and ignore returned Status
</code></pre>
<p>or </p>
<pre><code>{
Status myStatus = MyFunction();
} // lose all references to myStatus, without calling IsOK() on it
</code></pre>
<p>Is it possible to make this impossible? e.g. an throw exception</p>
<p><strong>In general</strong>: is it possible to write a C# class on which you <em>have</em> to call a certain function?</p>
<p>In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the <em>destructor</em> and ring some bells when someone doesn't check this instance.</p>
<p>What is the equivalent option in C#?
I read somewhere that "You don't want a destructor in your C# class"</p>
<p>Is the Dispose method of the IDisposable interface an option?</p>
<p>In this case there are no unmanaged resources to free.
Additionally, it is not determined <em>when</em> the GC will dispose the object.
When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance?
The "using" keyword does help, but again, it is not <em>required</em> for lazy callers.</p>
|
[
{
"answer_id": 19560,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 3,
"selected": false,
"text": "bool TryMyFunction(out Status status)\n{\n}\n"
},
{
"answer_id": 19561,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 0,
"selected": false,
"text": "throw MyException;\n\n\n[global::System.Serializable]\n public class MyException : Exception\n {\n //\n // For guidelines regarding the creation of new exception types, see\n // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp\n // and\n // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp\n //\n\n public MyException () { }\n public MyException ( string message ) : base( message ) { }\n public MyException ( string message, Exception inner ) : base( message, inner ) { }\n protected MyException (\n System.Runtime.Serialization.SerializationInfo info,\n System.Runtime.Serialization.StreamingContext context )\n : base( info, context ) { }\n }\n"
},
{
"answer_id": 19586,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "void MyFunction(Action<Status> callback)\n { bool errorHappened = false;\n\n if (somethingBadHappend) errorHappened = true;\n\n Status status = (errorHappend)\n ? new Status(false, \"Something went wrong\")\n : new Status(true, \"OK\");\n callback(status)\n\n if (!status.isOkWasCalled) \n throw new Exception(\"Please call IsOK() on Status\"). \n }\n\nMyFunction(status => if (!status.IsOK()) onerror());\n"
},
{
"answer_id": 19590,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "void MyFunction(out Status status)\n{\n}\n"
},
{
"answer_id": 19591,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 0,
"selected": false,
"text": "warn_unused_result"
},
{
"answer_id": 19835,
"author": "Weeble",
"author_id": 2283,
"author_profile": "https://Stackoverflow.com/users/2283",
"pm_score": 3,
"selected": true,
"text": "using System;\n\npublic class Example\n{\n public class Toy\n {\n private bool inCupboard = false;\n public void Play() { Console.WriteLine(\"Playing.\"); }\n public void PutAway() { inCupboard = true; }\n public bool IsInCupboard { get { return inCupboard; } }\n }\n\n public delegate void ToyUseCallback(Toy toy);\n\n public class Parent\n {\n public static void RequestToy(ToyUseCallback callback)\n {\n Toy toy = new Toy();\n callback(toy);\n if (!toy.IsInCupboard)\n {\n throw new Exception(\"You didn't put your toy in the cupboard!\");\n }\n }\n }\n\n public class Child\n {\n public static void Play()\n {\n Parent.RequestToy(delegate(Toy toy)\n {\n toy.Play();\n // Oops! Forgot to put the toy away!\n });\n }\n }\n\n public static void Main()\n {\n Child.Play();\n Console.ReadLine();\n }\n}\n"
},
{
"answer_id": 26170051,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "TryXX"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1163/"
] |
19,589
|
<p>Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to).</p>
<p>The obvious way is to use <code>ConfigurationManager</code> to load the configuration section and write out the data I need.</p>
<pre><code>var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");
</code></pre>
<p>Appears to always return null.</p>
<pre><code>var serviceModelSection = ConfigurationManager.GetSection("appSettings");
</code></pre>
<p>Works perfectly.</p>
<p>The configuration section is present in the App.config but for some reason <code>ConfigurationManager</code> refuses to load the <code>system.ServiceModel</code> section.</p>
<p>I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 19594,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 6,
"selected": false,
"text": "// Automagically find all client endpoints defined in app.config\nClientSection clientSection = \n ConfigurationManager.GetSection(\"system.serviceModel/client\") as ClientSection;\n\nChannelEndpointElementCollection endpointCollection =\n clientSection.ElementInformation.Properties[string.Empty].Value as ChannelEndpointElementCollection;\nList<string> endpointNames = new List<string>();\nforeach (ChannelEndpointElement endpointElement in endpointCollection)\n{\n endpointNames.Add(endpointElement.Name);\n}\n// use endpointNames somehow ...\n"
},
{
"answer_id": 19596,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": true,
"text": "<system.serviceModel>"
},
{
"answer_id": 19602,
"author": "DavidWhitney",
"author_id": 1297,
"author_profile": "https://Stackoverflow.com/users/1297",
"pm_score": 4,
"selected": false,
"text": " public static string GetServerName()\n {\n string serverName = \"Unknown\";\n\n Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\n ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);\n BindingsSection bindings = serviceModel.Bindings;\n\n ChannelEndpointElementCollection endpoints = serviceModel.Client.Endpoints;\n\n for(int i=0; i<endpoints.Count; i++)\n {\n ChannelEndpointElement endpointElement = endpoints[i];\n if (endpointElement.Contract == \"MyContractName\")\n {\n serverName = endpointElement.Address.Host;\n }\n }\n\n return serverName;\n }\n"
},
{
"answer_id": 5986619,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 3,
"selected": false,
"text": "Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);\n"
},
{
"answer_id": 18844990,
"author": "Robin G Brown",
"author_id": 2771792,
"author_profile": "https://Stackoverflow.com/users/2771792",
"pm_score": 3,
"selected": false,
"text": "Private Function GetEndpointAddress(name As String) As String\n Debug.Print(\"--- GetEndpointAddress ---\")\n Dim address As String = \"Unknown\"\n Dim appConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)\n Debug.Print(\"app.config: \" & appConfig.FilePath)\n Dim serviceModel As ServiceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(appConfig)\n Dim bindings As BindingsSection = serviceModel.Bindings\n Dim endpoints As ChannelEndpointElementCollection = serviceModel.Client.Endpoints\n For i As Integer = 0 To endpoints.Count - 1\n Dim endpoint As ChannelEndpointElement = endpoints(i)\n Debug.Print(\"Endpoint: \" & endpoint.Name & \" - \" & endpoint.Address.ToString)\n If endpoint.Name = name Then\n address = endpoint.Address.ToString\n End If\n Next\n Debug.Print(\"--- GetEndpointAddress ---\")\n Return address\nEnd Function\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1297/"
] |
19,604
|
<p>What is the best Image Manager to integrate in TinyMce editor apart the official Moxiecode commercial ones?</p>
<p>I'm looking to integrate a light texteditor in an asp.net mvc application and I choosed the Tinymce solution (and not the classic FCKEditor as this seems more lightweight and more jquery friendly).</p>
<p>Sadly TinyMce doesn't come with the Image Manager or Document Manager integrated like FCKeditor but you must buy them as plugins form Moxiecode.</p>
<p>I've looked other plugins but till now I've not find any decend and light solution that works with asp.net mvc framework. </p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 24569996,
"author": "Ravimallya",
"author_id": 1201322,
"author_profile": "https://Stackoverflow.com/users/1201322",
"pm_score": 0,
"selected": false,
"text": " div.mce-fullscreen\n {\n z-index: 1030;\n }\n div.mce-edit-area\n {\n border-width: 1px !important;\n border-left-width: 0 !important;\n border-bottom-width: 0 !important;\n }\n .mce-combobox .mce-btn\n {\n width: 44px !important;\n height: auto !important;\n }\n .mce-combobox .mce-btn button\n {\n padding-right: 0;\n padding-left: 0;\n }\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1929/"
] |
19,611
|
<p>Given a (source) patch file, what's the easiest way to apply this patch on the source files under Windows?</p>
<p>A GUI tool where I can visually compare the unchanged-changed source lines would be great.</p>
|
[
{
"answer_id": 8056005,
"author": "Nicolas Thery",
"author_id": 903840,
"author_profile": "https://Stackoverflow.com/users/903840",
"pm_score": 4,
"selected": false,
"text": "git apply --ignore-space-change --ignore-whitespace --whitespace=nowarn file.patch\n"
},
{
"answer_id": 29050457,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "git apply --unsafe-paths"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1630/"
] |
19,656
|
<p>I have an Interface called <code>IStep</code> that can do some computation (See "<a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html" rel="nofollow noreferrer">Execution in the Kingdom of Nouns</a>"). At runtime, I want to select the appropriate implementation by class name.</p>
<pre>
// use like this:
IStep step = GetStep(sName);
</pre>
|
[
{
"answer_id": 19658,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 2,
"selected": false,
"text": "IStep step = System.Activator.CreateInstance(sAssemblyName, sClassName).Unwrap() as IStep;\n"
},
{
"answer_id": 19663,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": true,
"text": "foreach (Type t in Assembly.GetCallingAssembly().GetTypes())\n{\n if (!typeof(IStep).IsAssignableFrom(t)) continue;\n Console.WriteLine(t.FullName + \" implements \" + typeof(IStep).FullName);\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
19,708
|
<p>To grab the inode of a file in PHP, you can use this:</p>
<pre><code>$fs = stat($file);
echo $fs['ino'];
</code></pre>
<p>The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?</p>
|
[
{
"answer_id": 19716,
"author": "mercutio",
"author_id": 1951,
"author_profile": "https://Stackoverflow.com/users/1951",
"pm_score": 2,
"selected": true,
"text": "fileinode()"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] |
19,746
|
<p>I'm trying to create a webapplication where I want to be able to plug-in separate assemblies. I'm using MVC preview 4 combined with Unity for dependency injection, which I use to create the controllers from my plugin assemblies. I'm using WebForms (default aspx) as my view engine.</p>
<p>If I want to use a view, I'm stuck on the ones that are defined in the core project, because of the dynamic compiling of the ASPX part. I'm looking for a proper way to enclose ASPX files in a different assembly, without having to go through the whole deployment step. Am I missing something obvious? Or should I resort to creating my views programmatically?</p>
<hr>
<p>Update: I changed the accepted answer. Even though Dale's answer is very thorough, I went for the solution with a different virtual path provider. It works like a charm, and takes only about 20 lines in code altogether I think.</p>
|
[
{
"answer_id": 1514764,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "protected void Application_Start()\n{\n WebFormViewEngine engine = new WebFormViewEngine();\n\n engine.ViewLocationFormats = new[] { \"~/bin/Views/{1}/{0}.aspx\", \"~/Views/Shared/{0}.aspx\" };\n engine.PartialViewLocationFormats = engine.ViewLocationFormats;\n\n ViewEngines.Engines.Clear();\n ViewEngines.Engines.Add(engine);\n\n RegisterRoutes(RouteTable.Routes);\n}\n"
},
{
"answer_id": 4573845,
"author": "Tom Clarkson",
"author_id": 101970,
"author_profile": "https://Stackoverflow.com/users/101970",
"pm_score": 5,
"selected": false,
"text": "HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedViewPathProvider());\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] |
19,766
|
<p>What would be the best way to have a list of items with a checkbox each in Java Swing?</p>
<p>I.e. a JList with items that have some text and a checkbox each?</p>
|
[
{
"answer_id": 19804,
"author": "Telcontar",
"author_id": 518,
"author_profile": "https://Stackoverflow.com/users/518",
"pm_score": 5,
"selected": true,
"text": "ListCellRenderer"
},
{
"answer_id": 1966151,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 5,
"selected": false,
"text": "CheckBoxList"
},
{
"answer_id": 24777687,
"author": "Rawa",
"author_id": 1724097,
"author_profile": "https://Stackoverflow.com/users/1724097",
"pm_score": 3,
"selected": false,
"text": "import java.awt.Component;\n\nimport javax.swing.*;\nimport javax.swing.border.*;\n\nimport java.awt.event.*;\n\n@SuppressWarnings(\"serial\")\npublic class JCheckBoxList extends JList<JCheckBox> {\n protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n public JCheckBoxList() {\n setCellRenderer(new CellRenderer());\n addMouseListener(new MouseAdapter() {\n public void mousePressed(MouseEvent e) {\n int index = locationToIndex(e.getPoint());\n if (index != -1) {\n JCheckBox checkbox = (JCheckBox) getModel().getElementAt(index);\n checkbox.setSelected(!checkbox.isSelected());\n repaint();\n }\n }\n });\n setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n\n public JCheckBoxList(ListModel<JCheckBox> model){\n this();\n setModel(model);\n }\n\n protected class CellRenderer implements ListCellRenderer<JCheckBox> {\n public Component getListCellRendererComponent(\n JList<? extends JCheckBox> list, JCheckBox value, int index,\n boolean isSelected, boolean cellHasFocus) {\n JCheckBox checkbox = value;\n\n //Drawing checkbox, change the appearance here\n checkbox.setBackground(isSelected ? getSelectionBackground()\n : getBackground());\n checkbox.setForeground(isSelected ? getSelectionForeground()\n : getForeground());\n checkbox.setEnabled(isEnabled());\n checkbox.setFont(getFont());\n checkbox.setFocusPainted(false);\n checkbox.setBorderPainted(true);\n checkbox.setBorder(isSelected ? UIManager\n .getBorder(\"List.focusCellHighlightBorder\") : noFocusBorder);\n return checkbox;\n }\n }\n}\n"
},
{
"answer_id": 25521015,
"author": "Željko Vuković",
"author_id": 3980145,
"author_profile": "https://Stackoverflow.com/users/3980145",
"pm_score": 0,
"selected": false,
"text": " addKeyListener(new KeyAdapter() {\n @Override\n public void keyPressed(KeyEvent e) {\n int index = getSelectedIndex();\n if (index != -1 && e.getKeyCode() == KeyEvent.VK_SPACE) {\n boolean newVal = !((JCheckBox) (getModel()\n .getElementAt(index))).isSelected();\n for (int i : getSelectedIndices()) {\n JCheckBox checkbox = (JCheckBox) getModel()\n .getElementAt(i);\n checkbox.setSelected(newVal);\n repaint();\n }\n }\n }\n });\n"
},
{
"answer_id": 27215934,
"author": "René Link",
"author_id": 974186,
"author_profile": "https://Stackoverflow.com/users/974186",
"pm_score": 4,
"selected": false,
"text": "ListCellRenderer"
},
{
"answer_id": 32712019,
"author": "Lucky",
"author_id": 1793718,
"author_profile": "https://Stackoverflow.com/users/1793718",
"pm_score": 1,
"selected": false,
"text": "import javax.swing.*;\nimport javax.swing.border.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class CheckBoxList extends JList\n{\n protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n public CheckBoxList()\n {\n setCellRenderer(new CellRenderer());\n\n addMouseListener(new MouseAdapter()\n {\n public void mousePressed(MouseEvent e)\n {\n int index = locationToIndex(e.getPoint());\n\n if (index != -1) {\n JCheckBox checkbox = (JCheckBox)\n getModel().getElementAt(index);\n checkbox.setSelected(\n !checkbox.isSelected());\n repaint();\n }\n }\n }\n );\n\n setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n\n protected class CellRenderer implements ListCellRenderer\n {\n public Component getListCellRendererComponent(\n JList list, Object value, int index,\n boolean isSelected, boolean cellHasFocus)\n {\n JCheckBox checkbox = (JCheckBox) value;\n checkbox.setBackground(isSelected ?\n getSelectionBackground() : getBackground());\n checkbox.setForeground(isSelected ?\n getSelectionForeground() : getForeground());\n checkbox.setEnabled(isEnabled());\n checkbox.setFont(getFont());\n checkbox.setFocusPainted(false);\n checkbox.setBorderPainted(true);\n checkbox.setBorder(isSelected ?\n UIManager.getBorder(\n \"List.focusCellHighlightBorder\") : noFocusBorder);\n return checkbox;\n }\n }\n}\n"
},
{
"answer_id": 74432809,
"author": "huakim",
"author_id": 20501329,
"author_profile": "https://Stackoverflow.com/users/20501329",
"pm_score": 0,
"selected": false,
"text": "class JCheckList<T> extends JList<T> {\n\n protected static Border noFocusBorder = new EmptyBorder(1, 1, 1, 1);\n\n public void setSelected(int index) {\n if (index != -1) {\n JCheckBox checkbox = (JCheckBox) getModel().getElementAt(index);\n checkbox.setSelected(\n !checkbox.isSelected());\n repaint();\n }\n }\n\n protected static class CellListener\n extends DefaultListModel\n implements ListDataListener {\n\n ListModel ls;\n\n public CellListener(ListModel ls) {\n ls.addListDataListener(this);\n int i = ls.getSize();\n for (int v = 0; v < i; v++) {\n var r = new JCheckBox();\n r.setText(ls.getElementAt(v).toString());\n this.addElement(r);\n }\n this.ls = ls;\n }\n\n @Override\n public void intervalAdded(ListDataEvent e) {\n int begin = e.getIndex0();\n int end = e.getIndex1();\n for (; begin <= end; begin++) {\n var r = new JCheckBox();\n r.setText(ls.getElementAt(begin).toString());\n this.add(begin, r);\n }\n }\n\n @Override\n public void intervalRemoved(ListDataEvent e) {\n int begin = e.getIndex0();\n int end = e.getIndex1();\n for (; begin <= end; end--) {\n this.remove(begin);\n }\n }\n\n @Override\n public void contentsChanged(ListDataEvent e) {\n\n }\n }\n\n public JCheckList() {\n setCellRenderer(new CellRenderer());\n\n addMouseListener(new MouseAdapter() {\n public void mousePressed(MouseEvent e) {\n int index = locationToIndex(e.getPoint());\n\n setSelected(index);\n }\n }\n );\n\n\n addKeyListener(new KeyListener(){\n @Override\n public void keyTyped(KeyEvent e) {\n \n }\n\n @Override\n public void keyPressed(KeyEvent e) {\n if (e.getKeyCode() == KeyEvent.VK_SPACE){\n \n int index = JCheckList.this.getSelectedIndex();\n\n setSelected(index);\n }\n }\n\n @Override\n public void keyReleased(KeyEvent e) {\n \n }\n \n });\n\n setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n }\n\n @Override\n public void setModel(ListModel<T> d) {\n var r = new CellListener(d);\n d.addListDataListener(r);\n super.setModel(r);\n }\n\n protected class CellRenderer implements ListCellRenderer {\n\n public Component getListCellRendererComponent(\n JList list, Object value, int index,\n boolean isSelected, boolean cellHasFocus) {\n JCheckBox checkbox = (JCheckBox) value;\n checkbox.setBackground(isSelected\n ? getSelectionBackground() : getBackground());\n checkbox.setForeground(isSelected\n ? getSelectionForeground() : getForeground());\n checkbox.setEnabled(isEnabled());\n checkbox.setFont(getFont());\n checkbox.setFocusPainted(false);\n checkbox.setBorderPainted(true);\n checkbox.setBorder(isSelected\n ? UIManager.getBorder(\n \"List.focusCellHighlightBorder\") : noFocusBorder);\n return checkbox;\n }\n }\n}\n"
},
{
"answer_id": 74535408,
"author": "JPT",
"author_id": 4308462,
"author_profile": "https://Stackoverflow.com/users/4308462",
"pm_score": 1,
"selected": false,
"text": "import java.awt.Component;\n\nimport javax.swing.JCheckBox;\nimport javax.swing.JList;\nimport javax.swing.ListCellRenderer;\n\nclass CheckListRenderer extends JCheckBox implements ListCellRenderer<Entity> {\n\n @Override\n public Component getListCellRendererComponent(JList<? extends Entity> list, \n Entity value, int index, boolean isSelected, boolean cellHasFocus) {\n\n setEnabled(list.isEnabled());\n setSelected(value.isActive()); // sets the checkbox\n setFont(list.getFont());\n if (isSelected) { // highlights the currently selected entry\n setBackground(list.getSelectionBackground());\n setForeground(list.getSelectionForeground());\n } else {\n setBackground(list.getBackground());\n setForeground(list.getForeground());\n }\n setText(value.toString()+\" - A\" + value.isActive()+\" - F\"+cellHasFocus+\" - S\"+isSelected );\n return this;\n }\n\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1827/"
] |
19,772
|
<p>Does anyone know of a good Command Prompt replacement? I've tried bash/Cygwin, but that does not really meet my needs at work because it's too heavy. I'd like a function-for-function identical wrapper on cmd.exe, but with highlighting, intellisense, and (critically) a tabbed interface. Powershell is okay, but the interface is still lacking.</p>
|
[
{
"answer_id": 6149994,
"author": "Priya",
"author_id": 465560,
"author_profile": "https://Stackoverflow.com/users/465560",
"pm_score": 0,
"selected": false,
"text": "ZOC"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] |
19,773
|
<p>I have a huge web app that is having issues with memory leak in IE 6.</p>
<p>Fixing a memory leak in a 5 line code sample that demonstrates the problem is easy. </p>
<p>But if I have a very huge application, where should a start from?</p>
|
[
{
"answer_id": 9519996,
"author": "Trident D'Gao",
"author_id": 139667,
"author_profile": "https://Stackoverflow.com/users/139667",
"pm_score": 0,
"selected": false,
"text": "<!--[if lt IE 8]>\n<script type=\"text/javascript\">\n\nfunction disposeAll() {\n if (window.document.all) {\n for (var index = 0; index < window.document.all.length; index++) {\n try { dispose(window.document.all[index], []); } catch (e) { debugger; }\n }\n }\n dispose(window.document.body, []);\n dispose(window.document, []);\n dispose(window, []);\n window.disposeAll = null;\n window.dispose = null;\n window.onunload = null;\n}\n\nfunction dispose(something, map) {\n if (something == null) return;\n if (something.dispose && typeof (something.dispose) == 'function') {\n try { something.dispose(); } catch (e) { debugger; }\n }\n map.push(something);\n for (var key in something) {\n var value = null;\n try { value = something[key]; } catch (e) { };\n if (value == null || value == dispose || value == disposeAll) continue;\n\n var processed = null;\n for (var index = 0; index < map.length; index++) {\n if (map[index] === value) {\n processed = value;\n break;\n }\n }\n if (processed != null) continue;\n var constructor = value.constructor;\n if (constructor == Object || constructor == Array) {\n try { dispose(value, map); } catch (e) { debugger; }\n }\n if (constructor == Object || constructor == Array || constructor == Function) {\n try { something[key] = null; } catch (e) { debugger; }\n }\n }\n map.pop();\n}\n\n(function() {\n var previousUnloadHandler = window.onunload;\n if (previousUnloadHandler == null) {\n window.onunload = disposeAll;\n } else {\n window.onunload = function() {\n previousUnloadHandler.apply(this, arguments); // <== HERE YOU MAY WANT TO HAVE AN \"IF\" TO MAKE SURE THE ORIGINAL UNLOAD EVENT WASN'T CANCELLED\n disposeAll();\n previousUnloadHandler = null;\n };\n }\n}());\n\n</script>\n<![endif]-->\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
19,786
|
<p>I am maintaining an app for a client that is used in two locations. One in England and one in Poland.</p>
<p>The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format.</p>
<p>My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ?</p>
<p>BTW I have looked at CCur, but not sure if that will do what I want. </p>
|
[
{
"answer_id": 19920,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 4,
"selected": true,
"text": "\"£1000.00\""
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1075/"
] |
19,787
|
<p>Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)?</p>
<p>I want to see if a <code>.bat</code> file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this.</p>
<p>The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?</p>
|
[
{
"answer_id": 19824,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 0,
"selected": false,
"text": "svnadmin dump -r1:HEAD /path/to/repo/\n"
},
{
"answer_id": 19826,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 6,
"selected": true,
"text": "svn log --verbose"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
19,790
|
<p>By default each row of a Gridview maps to each row in a datatable or dataset attached to its datasource. But what if I want to display these rows in multiple columns. For example if it has 10 rows, 5 rows each should be displayed in 2 columns side by side. Also can I do this with the Infragistics grid. Is this possible?</p>
|
[
{
"answer_id": 19805,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 5,
"selected": true,
"text": "DataList"
},
{
"answer_id": 177689,
"author": "BenB",
"author_id": 11703,
"author_profile": "https://Stackoverflow.com/users/11703",
"pm_score": 1,
"selected": false,
"text": "e.Row.Cells(2).Text = e.Row.Cells(1).Text\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
19,837
|
<p>Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP. </p>
<p>What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP?</p>
<hr>
<p>Update: OK so I was definitely trying to avoid using anything to do with copying DLLs etc. I'll look into the <a href="http://www.codeplex.com/SQL2K5PHP" rel="nofollow noreferrer">SQL2K5PHP</a> driver (thanks Vincent). @jcarrascal for the sake of clarity, by "client side" I mean our application is an internal web app that runs as an <a href="http://msdn.microsoft.com/en-us/library/ms536471.aspx" rel="nofollow noreferrer">HTA</a>, with all queries done via javascript calls to an ASP which actually submits the DB request.</p>
|
[
{
"answer_id": 19851,
"author": "Julio César",
"author_id": 2148,
"author_profile": "https://Stackoverflow.com/users/2148",
"pm_score": 2,
"selected": false,
"text": "$conn = mssql_connect('localhost', 'sa' , '123456')\n or die('Can\\'t connect.');\nmssql_select_db('database', $conn)\n or die('Can\\'t select the database');\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1915/"
] |
19,838
|
<p>I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.</p>
<p>One easy way to implement closures is to pass a <code>void*</code> to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.</p>
<pre><code>loop do
break i if (i >= 4000)
i *= 2
end
</code></pre>
<p>I think one of the closures proposals for Java works like this also.</p>
<p>So, how would you implement Ruby-blocks/Java-closures in C?</p>
|
[
{
"answer_id": 20154,
"author": "wvdschel",
"author_id": 2018,
"author_profile": "https://Stackoverflow.com/users/2018",
"pm_score": 4,
"selected": true,
"text": "context"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148/"
] |
19,843
|
<p>My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:</p>
<pre><code>Class test<T>{
int method1(Obj Parameter1){
//in here I want to do something which I would explain as
T.TryParse(Parameter1);
//my problem is that it does not work ... I get an error.
//just to explain: if I declare test<int> (with type Integer)
//I want my sample code to call int.TryParse(). If it were String
//it should have been String.TryParse()
}
}
</code></pre>
<p>So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!</p>
<hr />
<p>Edit: Thank you all for your answers!</p>
<p>Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.</p>
<p>This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)</p>
<hr />
<p>Though if you have some other suggestion I am still waiting (and willing to participate)</p>
|
[
{
"answer_id": 19867,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "class a {\n static StaticMethod1 ()\n virtual Method1 ()\n}\n\nclass b : a {\n override Method1 () return StaticMethod1()\n}\n\nclass c : a {\n override Method1 () return \"XYZ\"\n}\n\nclass generic<T> \n where T : a {\n void DoSomething () T.Method1()\n}\n"
},
{
"answer_id": 19885,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 2,
"selected": false,
"text": "class test<T>\n{\n T Method(object P)\n {\n try {\n return (T)Convert.ChangeType(P, typeof(T));\n } catch(Exception e) {\n return null;\n }\n }\n}\n"
},
{
"answer_id": 19911,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "Class test<T>\n{\n T method1(object Parameter1){\n\n if( Parameter1 is T ) \n {\n T value = (T) Parameter1;\n //do something with value\n return value;\n }\n else\n {\n //Parameter1 is not a T\n return default(T); //or throw exception\n }\n }\n}\n"
},
{
"answer_id": 19982,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "Class test<T>\n{\n int method1(IConvertible Parameter1){\n\n IFormatProvider provider = System.Globalization.CultureInfo.CurrentCulture.GetFormat(typeof(T));\n\n T temp = Parameter1.ToType(typeof(T), provider);\n }\n}\n"
},
{
"answer_id": 20010,
"author": "Weeble",
"author_id": 2283,
"author_profile": "https://Stackoverflow.com/users/2283",
"pm_score": 2,
"selected": false,
"text": "public class Example\n{\n internal static class Support\n {\n private delegate bool GenericParser<T>(string s, out T o);\n private static Dictionary<Type, object> parsers =\n MakeStandardParsers();\n private static Dictionary<Type, object> MakeStandardParsers()\n {\n Dictionary<Type, object> d = new Dictionary<Type, object>();\n // You need to add an entry for every type you want to cope with.\n d[typeof(int)] = new GenericParser<int>(int.TryParse);\n d[typeof(long)] = new GenericParser<long>(long.TryParse);\n d[typeof(float)] = new GenericParser<float>(float.TryParse);\n return d;\n }\n public static bool TryParse<T>(string s, out T result)\n {\n return ((GenericParser<T>)parsers[typeof(T)])(s, out result);\n }\n }\n public class Test<T>\n {\n public static T method1(string s)\n {\n T value;\n bool success = Support.TryParse(s, out value);\n return value;\n }\n }\n public static void Main()\n {\n Console.WriteLine(Test<int>.method1(\"23\"));\n Console.WriteLine(Test<float>.method1(\"23.4\"));\n Console.WriteLine(Test<long>.method1(\"99999999999999\"));\n Console.ReadLine();\n }\n}\n"
},
{
"answer_id": 20053,
"author": "niklasfi",
"author_id": 2275,
"author_profile": "https://Stackoverflow.com/users/2275",
"pm_score": 1,
"selected": false,
"text": "Class a<T>{\n private void checkWetherTypeIsOK()\n {\n if (T is int || T is float //|| ... any other types you want to be allowed){\n return true;\n }\n else {\n throw new exception();\n }\n }\n public static a(){\n ccheckWetherTypeIsOK();\n }\n}\n"
},
{
"answer_id": 20139,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": true,
"text": "static class Parser\n{\n public static bool TryParse<TType>( string str, out TType x )\n {\n // Get the type on that TryParse shall be called\n Type objType = typeof( TType );\n\n // Enumerate the methods of TType\n foreach( MethodInfo mi in objType.GetMethods() )\n {\n if( mi.Name == \"TryParse\" )\n {\n // We found a TryParse method, check for the 2-parameter-signature\n ParameterInfo[] pi = mi.GetParameters();\n if( pi.Length == 2 ) // Find TryParse( String, TType )\n {\n // Build a parameter list for the call\n object[] paramList = new object[2] { str, default( TType ) };\n\n // Invoke the static method\n object ret = objType.InvokeMember( \"TryParse\", BindingFlags.InvokeMethod, null, null, paramList );\n\n // Get the output value from the parameter list\n x = (TType)paramList[1];\n return (bool)ret;\n }\n }\n }\n\n // Maybe we should throw an exception here, because we were unable to find the TryParse\n // method; this is not just a unable-to-parse error.\n\n x = default( TType );\n return false;\n }\n}\n"
},
{
"answer_id": 1138729,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "class test1<T> where T: struct\n"
},
{
"answer_id": 10590634,
"author": "Amir Abiri",
"author_id": 800334,
"author_profile": "https://Stackoverflow.com/users/800334",
"pm_score": 2,
"selected": false,
"text": "public class Example\n{\n // ...\n\n public static void PostInitCallback(Example example)\n {\n // Do something with the object...\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2275/"
] |
19,852
|
<p>I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc).</p>
<p>Does anybody know the maximum length that I can expect a content-type to be?</p>
|
[
{
"answer_id": 1849792,
"author": "speaker",
"author_id": 215670,
"author_profile": "https://Stackoverflow.com/users/215670",
"pm_score": 7,
"selected": true,
"text": "Type and subtype names MUST conform to the following ABNF:\n\n type-name = reg-name\n subtype-name = reg-name\n\n reg-name = 1*127reg-name-chars\n reg-name-chars = ALPHA / DIGIT / \"!\" /\n \"#\" / \"$\" / \"&\" / \".\" /\n \"+\" / \"-\" / \"^\" / \"_\"\n"
},
{
"answer_id": 23928635,
"author": "appleleaf",
"author_id": 3131821,
"author_profile": "https://Stackoverflow.com/users/3131821",
"pm_score": 3,
"selected": false,
"text": "<type-name>"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2084/"
] |
19,883
|
<p>I've used Trac/Subversion before and really like the integration. My current project is using Mercurial for distributed development and it'd be nice to be able to track issues/bugs and have this be integrated with Mercurial. I realized this could be tricky with the nature of DVCS.</p>
|
[
{
"answer_id": 3129480,
"author": "dimo414",
"author_id": 113632,
"author_profile": "https://Stackoverflow.com/users/113632",
"pm_score": 1,
"selected": false,
"text": "hg b"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287/"
] |
19,893
|
<p>I have two applications written in Java that communicate with each other using XML messages over the network. I'm using a SAX parser at the receiving end to get the data back out of the messages. One of the requirements is to embed binary data in an XML message, but SAX doesn't like this. Does anyone know how to do this?</p>
<p>UPDATE: I got this working with the <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html" rel="noreferrer">Base64</a> class from the <a href="http://commons.apache.org/codec/" rel="noreferrer">apache commons codec library</a>, in case anyone else is trying something similar.</p>
|
[
{
"answer_id": 19939,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 8,
"selected": false,
"text": "<DATA>\n <BINARY>\n <BIT index=\"0\">0</BIT>\n <BIT index=\"1\">0</BIT>\n <BIT index=\"2\">1</BIT>\n ...\n <BIT index=\"n\">1</BIT>\n </BINARY>\n</DATA>\n"
},
{
"answer_id": 3156135,
"author": "Jarek Przygódzki",
"author_id": 293933,
"author_profile": "https://Stackoverflow.com/users/293933",
"pm_score": 3,
"selected": false,
"text": "<data encoding=\"yEnc>\n<![CDATA[ encoded binary data ]]>\n</data>\n"
},
{
"answer_id": 3400927,
"author": "Baxter Tidwell",
"author_id": 2055692,
"author_profile": "https://Stackoverflow.com/users/2055692",
"pm_score": 4,
"selected": false,
"text": "string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));\n"
},
{
"answer_id": 27396540,
"author": "Lie Ryan",
"author_id": 309412,
"author_profile": "https://Stackoverflow.com/users/309412",
"pm_score": 0,
"selected": false,
"text": "POST / HTTP/1.1\nContent-Type: multipart/related; boundary=\"qd43hdi34udh34id344\"\n... other headers elided ...\n\n--qd43hdi34udh34id344\nContent-Type: application/xml\n\n<myxml>\n <data href=\"cid:data.bin\"/>\n</myxml>\n--qd43hdi34udh34id344\nContent-Id: <data.bin>\nContent-type: application/octet-stream\nContent-Transfer-Encoding: binary\n\n... binary data ...\n--qd43hdi34udh34id344--\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
19,933
|
<p>I want to copy a file from A to B in C#. How do I do that?</p>
|
[
{
"answer_id": 19936,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "FileInfo fi = new FileInfo(\"a.txt\");\nfi.CopyTo(\"b.txt\");\n"
},
{
"answer_id": 19938,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 4,
"selected": false,
"text": "File.Copy(path, path2);\n"
},
{
"answer_id": 52519781,
"author": "Stan van de Bovenkamp",
"author_id": 10391137,
"author_profile": "https://Stackoverflow.com/users/10391137",
"pm_score": 2,
"selected": false,
"text": "using System.IO;\n\n...\n\nvar path = //your current filePath\nvar outputPath = //the directory where you want your (.txt) file\n\n\nFile.Copy(path,outputPath);\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
19,941
|
<p>I want to be able to capture the exception that is thrown when a user requests a non-existent controller and re-direct it to a 404 page. How can I do this?</p>
<p>For example, the user requests <code>http://www.nosite.com/paeges/1</code> (<em>should be</em> <code>/pages/</code>). How do I make it so they get re-directed to the 404 rather than the exception screen?</p>
|
[
{
"answer_id": 19959,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 4,
"selected": false,
"text": "// We couldn't find a route to handle the request. Show the 404 page.\nroutes.MapRoute(\"Error\", \"{*url}\",\n new { controller = \"Error\", action = \"404\" }\n);\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2285/"
] |
19,952
|
<p>The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class.
RFC = M + R where
M = Number of methods in the class.
R = Total number of other methods directly invoked from the M.</p>
<p>Thinking C is the .class and J is the .java file of which we need to calculate RFC.</p>
<pre>
class J{
a(){}
b(){}
c(){
e1.e();
e1.f();
e1.g();
}
h(){
i.k();
i.j();
}
m(){}
n(){
i.o();
i.p();
i.p();
i.p();
}
}
</pre>
<p>here M=6
and R=9 (Don't worry about call inside a loop. It's considered as a single call)</p>
<p>Calculating M is easy. Load C using classloader and use reflection to get the count of methods.</p>
<p>Calculating R is not direct. We need to count the number of method calls from the class. First level only. </p>
<p>For calculating R I must use regex. Usually format would be (calls without using . are not counted)</p>
<pre>
[variable_name].[method_name]([zero or more parameters]);
</pre>
<p>or</p>
<pre>
[variable_name].[method_name]([zero or more parameters])
</pre>
<p>with out semicolon when call return is directly becomes parameter to another method.
or </p>
<pre>
[variable_name].[method_name]([zero or more parameters]).method2();
</pre>
<p>this becomes two method calls</p>
<p>What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R.</p>
<hr>
<p><strong>UPDATE:</strong><br>
<a href="https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983" title="@McDowell">@McDowell</a>
Looks like using BCEL I can simplify the whole process. Let me try it.</p>
|
[
{
"answer_id": 19998,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 0,
"selected": false,
"text": "class J {\n a() { }\n b() { this.a(); }\n c() { jj.aa(); }\n d() { i.k(); }\n e() { this.f().a(); }\n f() { return this; }\n g() { i.m().n(); }\n\n class JJ {\n aa() { a(); }\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/482/"
] |
19,988
|
<p>I'm currently using the awesome attachment-fu plugin for a Rails app, but as a novice developer, I've never encountered a scenario like the one I've found myself in.</p>
<p>Essentially, I'm using the attachment-fu plugin on two levels.</p>
<ol>
<li>Is for user avatars in the user class.</li>
<li>Is to allow file attachments (<strong><em>PDFs</em></strong>, etc) in a messaging system.</li>
</ol>
<p>My question is what the best use practice would be in these situations to remain <strong><em>DRY</em></strong>, clear, and consistent.</p>
<p>Clearly it would make no sense to define and execute the plugin in both classes, but there's something deeply strange to me (possibly unfounded) about just going ahead and setting it all up in the godly Application class.</p>
<p>Is there something in between, or is the parent class the way to go?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 78719,
"author": "Dan Harper",
"author_id": 14530,
"author_profile": "https://Stackoverflow.com/users/14530",
"pm_score": 0,
"selected": false,
"text": " class FileUpload < ActiveRecord::Base\n belongs_to :fileable, :polymorphic => true\n file_column :name\n end\n"
},
{
"answer_id": 80016,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 2,
"selected": false,
"text": "class Asset < ActiveRecord::Base\n ... attachment_fu logic ...\nend\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2293/"
] |
19,995
|
<p>Of course I am aware of Ajax, but the problem with Ajax is that the browser should poll the server frequently to find whether there is new data. This increases server load.</p>
<p>Is there any better method (even using Ajax) other than polling the server frequently?</p>
|
[
{
"answer_id": 20014,
"author": "sparkes",
"author_id": 269,
"author_profile": "https://Stackoverflow.com/users/269",
"pm_score": 1,
"selected": false,
"text": "multipart/x-mixed-replace"
},
{
"answer_id": 19458245,
"author": "pafinde",
"author_id": 1033410,
"author_profile": "https://Stackoverflow.com/users/1033410",
"pm_score": 5,
"selected": false,
"text": "var ws = new WebSocket(\"ws://your.domain.com/somePathIfYouNeed?args=any\");\nws.onmessage = function (evt) \n{\n var message = evt.data;\n //decode message (with JSON or something) and do the needed\n};\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/19995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
20,047
|
<p>We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.</p>
<p>I attached the profiler, set up a trace profile using <a href="http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/" rel="noreferrer">this excellent article on troubleshooting deadlocks</a>, and captured a bunch of examples. The weird thing is that <strong>the deadlocking write is <em>always</em> the same</strong>:</p>
<pre><code>UPDATE [dbo].[Posts]
SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3
WHERE [Id] = @p0
</code></pre>
<p>The other deadlocking statement varies, but it's usually some kind of trivial, simple <strong>read</strong> of the posts table. This one always gets killed in the deadlock. Here's an example</p>
<pre><code>SELECT
[t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount],
[t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId],
[t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason],
[t0].[LastActivityDate], [t0].[LastActivityUserId]
FROM [dbo].[Posts] AS [t0]
WHERE [t0].[ParentId] = @p0
</code></pre>
<p>To be perfectly clear, we are not seeing write / write deadlocks, but read / write.</p>
<p>We have a mixture of LINQ and parameterized SQL queries at the moment. We have added <code>with (nolock)</code> to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!</p>
<p>Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.</p>
<p>The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's <em>only</em> executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.</p>
<p>I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?</p>
<p>Using NOLOCK with Linq is a bit more difficult as <a href="http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx" rel="noreferrer">Scott Hanselman discusses here</a>.</p>
<p>We are flirting with the idea of using</p>
<pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
</code></pre>
<p>on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.</p>
<p>I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but <em>reads?</em> We're not running a banking site here, we don't need perfect accuracy every time.</p>
<p>Ideas? Thoughts?</p>
<hr>
<blockquote>
<p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?</p>
</blockquote>
<p>Jeremy, we are sharing one static datacontext in the base Controller for the most part:</p>
<pre><code>private DBContext _db;
/// <summary>
/// Gets the DataContext to be used by a Request's controllers.
/// </summary>
public DBContext DB
{
get
{
if (_db == null)
{
_db = new DBContext() { SessionName = GetType().Name };
//_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED");
}
return _db;
}
}
</code></pre>
<p>Do you recommend we create a new context for every Controller, or per Page, or .. more often?</p>
|
[
{
"answer_id": 20094,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "Begin Tran\nInsert into Table (Columns) Values (Values)\nSelect Max(ID) From Table\nCommit Tran\n"
},
{
"answer_id": 20147,
"author": "jeremcc",
"author_id": 1436,
"author_profile": "https://Stackoverflow.com/users/1436",
"pm_score": 2,
"selected": false,
"text": "public static class AppData\n{\n /// <summary>\n /// Gets a new database context\n /// </summary>\n public static CoreDataContext DB\n {\n get\n {\n var dataContext = new CoreDataContext\n {\n DeferredLoadingEnabled = true\n };\n return dataContext;\n }\n }\n}\n"
},
{
"answer_id": 20224,
"author": "JEzell",
"author_id": 2308,
"author_profile": "https://Stackoverflow.com/users/2308",
"pm_score": 5,
"selected": false,
"text": "AnswerCount = AnswerCount+1"
},
{
"answer_id": 20473,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 1,
"selected": false,
"text": "using System.Configuration;\nnamespace VideoShow.Data\n{\n public class DataContextFactory\n {\n public static VideoShowDataContext DataContext()\n {\n return new VideoShowDataContext(ConfigurationManager.ConnectionStrings[\"VideoShowConnectionString\"].ConnectionString);\n }\n public static VideoShowDataContext DataContext(string connectionString)\n {\n return new VideoShowDataContext(connectionString);\n }\n }\n}\n"
},
{
"answer_id": 20727,
"author": "Seibar",
"author_id": 357,
"author_profile": "https://Stackoverflow.com/users/357",
"pm_score": 1,
"selected": false,
"text": "SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\n"
},
{
"answer_id": 21158,
"author": "Geoff Dalgas",
"author_id": 2,
"author_profile": "https://Stackoverflow.com/users/2",
"pm_score": 6,
"selected": true,
"text": "ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON\n"
},
{
"answer_id": 21438,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 2,
"selected": false,
"text": "-- Deadlock retry template\n\ndeclare @lastError int;\ndeclare @numErrors int;\n\nset @numErrors = 0;\n\nLockTimeoutRetry:\n\nbegin try;\n\n-- The query goes here\n\nreturn; -- this is the normal end of the procedure\n\nend try begin catch\n set @lastError=@@error\n if @lastError = 1222 or @lastError = 1205 -- Lock timeout or deadlock\n begin;\n if @numErrors >= 3 -- We hit the retry limit\n begin;\n raiserror('Could not get a lock after 3 attempts', 16, 1);\n return -100;\n end;\n\n -- Wait and then try the transaction again\n waitfor delay '00:00:00.25';\n set @numErrors = @numErrors + 1;\n goto LockTimeoutRetry;\n\n end;\n\n -- Some other error occurred\n declare @errorMessage nvarchar(4000), @errorSeverity int\n select @errorMessage = error_message(),\n @errorSeverity = error_severity()\n\n raiserror(@errorMessage, @errorSeverity, 1)\n\n return -100\nend catch; \n"
},
{
"answer_id": 22019,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 2,
"selected": false,
"text": "AnswerCount"
},
{
"answer_id": 27617,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 4,
"selected": false,
"text": "DBCC TRACEON (1222, -1)\n"
},
{
"answer_id": 243187,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public static void SetNoLock(this MyDataContext myDS)\n{\n myDS.ExecuteCommand(\"SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED\");\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] |
20,054
|
<p>I shudder to ask, but my client might offer no other SQL (or SQL-like) solution. I know Access has some SQL hooks; are they enough for basic ActiveRecord?</p>
<p><em>Later:</em></p>
<p>I appreciate all the suggestions to use other databases, but trust me: I've tried convincing them. There is an "approved" list, and no SQL databases are on it. Getting something onto the list could take more than a year, and this project will be done in three weeks.</p>
|
[
{
"answer_id": 20940,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "development:\n adapter: msaccess\n database: C:\\path\\to\\access_file.mdb\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
20,061
|
<p>I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.</p>
<p>My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?</p>
<hr>
<p>Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon.</p>
<p>So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?</p>
|
[
{
"answer_id": 20117,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "System::Xml"
},
{
"answer_id": 20130,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 5,
"selected": true,
"text": "\nusing (FileStream fs = new FileStream(....))\n{\n // Read in stats\n XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n GameStats stats = (GameStats)xs.Deserialize(fs);\n\n // Manipulate stats here ...\n\n // Write out game stats\n XmlSerializer xs = new XmlSerializer(typeof(GameStats));\n xs.Serialize(fs, stats);\n\n fs.Close();\n}\n"
},
{
"answer_id": 20209,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "[Serializable]"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/271/"
] |
20,063
|
<p>What's the <strong>easiest</strong>, <strong>tersest</strong>, and most <strong>flexible</strong> method or library for parsing Python command line arguments?</p>
|
[
{
"answer_id": 20065,
"author": "Corey",
"author_id": 1595,
"author_profile": "https://Stackoverflow.com/users/1595",
"pm_score": 4,
"selected": false,
"text": "optparse"
},
{
"answer_id": 20069,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": 4,
"selected": false,
"text": "import getopt, sys\n\ndef main():\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"ho:v\", [\"help\", \"output=\"])\n except getopt.GetoptError:\n # print help information and exit:\n usage()\n sys.exit(2)\n output = None\n verbose = False\n for o, a in opts:\n if o == \"-v\":\n verbose = True\n if o in (\"-h\", \"--help\"):\n usage()\n sys.exit()\n if o in (\"-o\", \"--output\"):\n output = a\n"
},
{
"answer_id": 20169,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 3,
"selected": false,
"text": "\nfrom ctypes import *\n\ndef wmain(argc, argv):\n print argc\n for i in argv:\n print i\n return 0\n\ndef startup():\n size = c_int()\n ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size))\n ref = c_wchar_p * size.value\n raw = ref.from_address(ptr)\n args = [arg for arg in raw]\n windll.kernel32.LocalFree(ptr)\n exit(wmain(len(args), args))\nstartup()\n"
},
{
"answer_id": 26910,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 9,
"selected": true,
"text": "optparse"
},
{
"answer_id": 30973,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 2,
"selected": false,
"text": "from werkzeug import script\n\n# actions go here\ndef action_foo(name=\"\"):\n \"\"\"action foo does foo\"\"\"\n pass\n\ndef action_bar(id=0, title=\"default title\"):\n \"\"\"action bar does bar\"\"\"\n pass\n\nif __name__ == '__main__':\n script.run()\n"
},
{
"answer_id": 979871,
"author": "Silfheed",
"author_id": 28421,
"author_profile": "https://Stackoverflow.com/users/28421",
"pm_score": 5,
"selected": false,
"text": "argparse"
},
{
"answer_id": 11271779,
"author": "stalk",
"author_id": 821594,
"author_profile": "https://Stackoverflow.com/users/821594",
"pm_score": 1,
"selected": false,
"text": "from consoleargs import command\n\n@command\ndef main(url, name=None):\n \"\"\"\n :param url: Remote URL \n :param name: File name\n \"\"\"\n print \"\"\"Downloading url '%r' into file '%r'\"\"\" % (url, name)\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 16377263,
"author": "ndemou",
"author_id": 1011025,
"author_profile": "https://Stackoverflow.com/users/1011025",
"pm_score": 6,
"selected": false,
"text": "\"\"\"Naval Fate.\n\nUsage:\n naval_fate.py ship new <name>...\n naval_fate.py ship <name> move <x> <y> [--speed=<kn>]\n naval_fate.py ship shoot <x> <y>\n naval_fate.py mine (set|remove) <x> <y> [--moored | --drifting]\n naval_fate.py (-h | --help)\n naval_fate.py --version\n\nOptions:\n -h --help Show this screen.\n --version Show version.\n --speed=<kn> Speed in knots [default: 10].\n --moored Moored (anchored) mine.\n --drifting Drifting mine.\n\n\"\"\"\nfrom docopt import docopt\n\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='Naval Fate 2.0')\n print(arguments)\n"
},
{
"answer_id": 27069329,
"author": "suda",
"author_id": 83055,
"author_profile": "https://Stackoverflow.com/users/83055",
"pm_score": 5,
"selected": false,
"text": "import click\n\n@click.command()\n@click.option('--count', default=1, help='Number of greetings.')\n@click.option('--name', prompt='Your name',\n help='The person to greet.')\ndef hello(count, name):\n \"\"\"Simple program that greets NAME for a total of COUNT times.\"\"\"\n for x in range(count):\n click.echo('Hello %s!' % name)\n\nif __name__ == '__main__':\n hello()\n"
},
{
"answer_id": 30493366,
"author": "Andrzej Pronobis",
"author_id": 1576602,
"author_profile": "https://Stackoverflow.com/users/1576602",
"pm_score": 9,
"selected": false,
"text": "argparse"
},
{
"answer_id": 36516929,
"author": "erco",
"author_id": 836131,
"author_profile": "https://Stackoverflow.com/users/836131",
"pm_score": 1,
"selected": false,
"text": "import os,sys\n\ndef HelpAndExit():\n print(\"<<your help output goes here>>\")\n sys.exit(1)\n\ndef Fatal(msg):\n sys.stderr.write(\"%s: %s\\n\" % (os.path.basename(sys.argv[0]), msg))\n sys.exit(1)\n\ndef NextArg(i):\n '''Return the next command line argument (if there is one)'''\n if ((i+1) >= len(sys.argv)):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return(1, sys.argv[i+1])\n\n### MAIN\nif __name__=='__main__':\n\n verbose = 0\n debug = 0\n infile = \"infile\"\n outfile = \"outfile\"\n\n # Parse command line\n skip = 0\n for i in range(1, len(sys.argv)):\n if not skip:\n if sys.argv[i][:2] == \"-d\": debug ^= 1\n elif sys.argv[i][:2] == \"-v\": verbose ^= 1\n elif sys.argv[i][:2] == \"-i\": (skip,infile) = NextArg(i)\n elif sys.argv[i][:2] == \"-o\": (skip,outfile) = NextArg(i)\n elif sys.argv[i][:2] == \"-h\": HelpAndExit()\n elif sys.argv[i][:1] == \"-\": Fatal(\"'%s' unknown argument\" % sys.argv[i])\n else: Fatal(\"'%s' unexpected\" % sys.argv[i])\n else: skip = 0\n\n print(\"%d,%d,%s,%s\" % (debug,verbose,infile,outfile))\n"
},
{
"answer_id": 43234054,
"author": "Simon Hibbs",
"author_id": 318488,
"author_profile": "https://Stackoverflow.com/users/318488",
"pm_score": 4,
"selected": false,
"text": "argparse"
},
{
"answer_id": 51185393,
"author": "QA Collective",
"author_id": 5196274,
"author_profile": "https://Stackoverflow.com/users/5196274",
"pm_score": 3,
"selected": false,
"text": "main()"
},
{
"answer_id": 51498731,
"author": "Erik",
"author_id": 7384642,
"author_profile": "https://Stackoverflow.com/users/7384642",
"pm_score": 0,
"selected": false,
"text": "import os,sys\n\n\ndef HelpAndExit():\n print(\"<<your help output goes here>>\")\n sys.exit(1)\n\ndef Fatal(msg):\n sys.stderr.write(\"%s: %s\\n\" % (os.path.basename(sys.argv[0]), msg))\n sys.exit(1)\n\ndef NextArg(i):\n '''Return the next command line argument (if there is one)'''\n if ((i+1) >= len(sys.argv)):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return(1, sys.argv[i+1])\n\ndef PosArg(i):\n '''Return positional argument'''\n if i >= len(sys.argv):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n return sys.argv[i]\n\ndef OptArg(i, default):\n '''Return optional argument (if there is one)'''\n if i >= len(sys.argv):\n Fatal(\"'%s' expected an argument\" % sys.argv[i])\n if sys.argv[i][:1] != '-':\n return True, sys.argv[i]\n else:\n return False, default\n\n\n### MAIN\nif __name__=='__main__':\n\n verbose = 0\n debug = 0\n infile = \"infile\"\n outfile = \"outfile\"\n options_start = 3\n\n # --- Parse two positional parameters ---\n n1 = int(PosArg(1))\n n2 = int(PosArg(2))\n\n # --- Parse an optional parameters ---\n present, a3 = OptArg(3,50)\n n3 = int(a3)\n options_start += int(present)\n\n # --- Parse rest of command line ---\n skip = 0\n for i in range(options_start, len(sys.argv)):\n if not skip:\n if sys.argv[i][:2] == \"-d\": debug ^= 1\n elif sys.argv[i][:2] == \"-v\": verbose ^= 1\n elif sys.argv[i][:2] == \"-i\": (skip,infile) = NextArg(i)\n elif sys.argv[i][:2] == \"-o\": (skip,outfile) = NextArg(i)\n elif sys.argv[i][:2] == \"-h\": HelpAndExit()\n elif sys.argv[i][:1] == \"-\": Fatal(\"'%s' unknown argument\" % sys.argv[i])\n else: Fatal(\"'%s' unexpected\" % sys.argv[i])\n else: skip = 0\n\n print(\"Number 1 = %d\" % n1)\n print(\"Number 2 = %d\" % n2)\n print(\"Number 3 = %d\" % n3)\n print(\"Debug = %d\" % debug)\n print(\"verbose = %d\" % verbose)\n print(\"infile = %s\" % infile)\n print(\"outfile = %s\" % outfile) \n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1335/"
] |
20,081
|
<p>I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together.</p>
<p>The logic is written as a <a href="http://www.oreillynet.com/lpt/a/3136" rel="nofollow noreferrer">pipelined table function</a>, following the pattern from the linked article. The table function uses a <code>PRAGMA AUTONOMOUS_TRANSACTION</code> declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values.</p>
<p>I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive).</p>
<p>My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing?</p>
<p>Every time I touch PL/SQL I get the impression that I'm typing way too much.</p>
<p><strong>Update:</strong> I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example:</p>
<pre><code>| EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns...
| 1 | 10 | A | 10-JAN-2008 |
| 2 | 11 | A | 13-JAN-2008 |
| 1 | 12 | A | 20-JAN-2008 |
| 2 | 11 | T | 01-FEB-2008 |
| 1 | 10 | T | 02-FEB-2008 |
| 2 | 11 | A | 20-FEB-2008 |
</code></pre>
<p>Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any <code>EMP_ID</code>s passed in though the cursor. Passing in <code>EMP_ID</code>s 1 and 2 would produce the following:</p>
<pre><code>| EMP_ID | JOB_ID | START_DATE | END_DATE |
| 1 | 10 | 10-JAN-2008 | 02-FEB-2008 |
| 2 | 11 | 13-JAN-2008 | 01-FEB-2008 |
| 1 | 12 | 20-JAN-2008 | |
| 2 | 11 | 20-FEB-2008 | |
</code></pre>
<p>(<code>END_DATE</code> allows <code>NULL</code>s for jobs that don't have a predetermined termination date.)</p>
<p>As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.</p>
|
[
{
"answer_id": 89084,
"author": "Sergey Stadnik",
"author_id": 10557,
"author_profile": "https://Stackoverflow.com/users/10557",
"pm_score": 0,
"selected": false,
"text": "CREATE GLOBAL TEMPORARY TABLE tab_ids (id INTEGER) \nON COMMIT DELETE ROWS;\n"
},
{
"answer_id": 97091,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 3,
"selected": true,
"text": "create table employee_job (\n emp_id integer,\n job_id integer,\n status varchar2(1 char),\n eff_date date\n ); \n\ninsert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY'));\ninsert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY'));\ninsert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY'));\n\ncommit;\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726/"
] |
20,084
|
<p>Following on from my <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods">previous question</a> I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).</p>
<p>The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types.</p>
<p>I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case!</p>
<p>So I have done some digging on Google and I now understand <em>why</em> it's not working. In that <strong>the <code>XmlSerializer</code> is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to</strong>. Fine.</p>
<p>I did come across <a href="http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx" rel="noreferrer">this page</a> on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible.</p>
<p>One thing I should also add is that I <strong>DO NOT</strong> want to go down the <code>XmlInclude</code> route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!</p>
|
[
{
"answer_id": 20126,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "IList"
},
{
"answer_id": 392690,
"author": "Max Galkin",
"author_id": 2351099,
"author_profile": "https://Stackoverflow.com/users/2351099",
"pm_score": 2,
"selected": false,
"text": "type.AssemblyQualifiedName\n"
},
{
"answer_id": 985495,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 7,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Xml.Serialization;\n\nnamespace Utility.Xml\n{\n public class AbstractXmlSerializer<AbstractType> : IXmlSerializable\n {\n // Override the Implicit Conversions Since the XmlSerializer\n // Casts to/from the required types implicitly.\n public static implicit operator AbstractType(AbstractXmlSerializer<AbstractType> o)\n {\n return o.Data;\n }\n\n public static implicit operator AbstractXmlSerializer<AbstractType>(AbstractType o)\n {\n return o == null ? null : new AbstractXmlSerializer<AbstractType>(o);\n }\n\n private AbstractType _data;\n /// <summary>\n /// [Concrete] Data to be stored/is stored as XML.\n /// </summary>\n public AbstractType Data\n {\n get { return _data; }\n set { _data = value; }\n }\n\n /// <summary>\n /// **DO NOT USE** This is only added to enable XML Serialization.\n /// </summary>\n /// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks>\n public AbstractXmlSerializer()\n {\n // Default Ctor (Required for Xml Serialization - DO NOT USE)\n }\n\n /// <summary>\n /// Initialises the Serializer to work with the given data.\n /// </summary>\n /// <param name=\"data\">Concrete Object of the AbstractType Specified.</param>\n public AbstractXmlSerializer(AbstractType data)\n {\n _data = data;\n }\n\n #region IXmlSerializable Members\n\n public System.Xml.Schema.XmlSchema GetSchema()\n {\n return null; // this is fine as schema is unknown.\n }\n\n public void ReadXml(System.Xml.XmlReader reader)\n {\n // Cast the Data back from the Abstract Type.\n string typeAttrib = reader.GetAttribute(\"type\");\n\n // Ensure the Type was Specified\n if (typeAttrib == null)\n throw new ArgumentNullException(\"Unable to Read Xml Data for Abstract Type '\" + typeof(AbstractType).Name +\n \"' because no 'type' attribute was specified in the XML.\");\n\n Type type = Type.GetType(typeAttrib);\n\n // Check the Type is Found.\n if (type == null)\n throw new InvalidCastException(\"Unable to Read Xml Data for Abstract Type '\" + typeof(AbstractType).Name +\n \"' because the type specified in the XML was not found.\");\n\n // Check the Type is a Subclass of the AbstractType.\n if (!type.IsSubclassOf(typeof(AbstractType)))\n throw new InvalidCastException(\"Unable to Read Xml Data for Abstract Type '\" + typeof(AbstractType).Name +\n \"' because the Type specified in the XML differs ('\" + type.Name + \"').\");\n\n // Read the Data, Deserializing based on the (now known) concrete type.\n reader.ReadStartElement();\n this.Data = (AbstractType)new\n XmlSerializer(type).Deserialize(reader);\n reader.ReadEndElement();\n }\n\n public void WriteXml(System.Xml.XmlWriter writer)\n {\n // Write the Type Name to the XML Element as an Attrib and Serialize\n Type type = _data.GetType();\n\n // BugFix: Assembly must be FQN since Types can/are external to current.\n writer.WriteAttributeString(\"type\", type.AssemblyQualifiedName);\n new XmlSerializer(type).Serialize(writer, _data);\n }\n\n #endregion\n }\n}\n"
},
{
"answer_id": 26373293,
"author": "user2009677",
"author_id": 2009677,
"author_profile": "https://Stackoverflow.com/users/2009677",
"pm_score": 1,
"selected": false,
"text": "[XmlRoot]\npublic class MyClass {\n public abstract class MyAbstract {} \n public class MyInherited : MyAbstract {} \n [XmlArray(), XmlArrayItem(typeof(MyInherited))] \n public MyAbstract[] Items {get; set; } \n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
20,088
|
<p>I am maintaining a few web applications. The development and qa environments use invalid/outdated ssl-certificates.</p>
<p>Although it is generally a good thing, that Firefox makes me click like a dozen times to accept the certificate, this is pretty annoying.</p>
<p>Is there a configuration-parameter to make Firefox (and possibly IE too) accept any ssl-certificate?</p>
<p>EDIT: I have accepted the solution, that worked. But thanks to all the people that have advised to use self-signed certificates. I am totally aware, that the accepted solution leaves me with a <strong>gaping security hole</strong>. Nonetheless I am to lazy to change the certificate for all the applications and all the environments...</p>
<p>But I also advice anybody strongly to leave validation enabled!</p>
|
[
{
"answer_id": 32188658,
"author": "Bryan Focht",
"author_id": 3145191,
"author_profile": "https://Stackoverflow.com/users/3145191",
"pm_score": 5,
"selected": false,
"text": "about:config"
},
{
"answer_id": 71890334,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 2,
"selected": false,
"text": "MOZILLA_PKIX_ERROR_SELF_SIGNED_CERT\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
20,107
|
<p>This line in YUI's <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Reset CSS</a> is causing trouble for me:</p>
<pre class="lang-css prettyprint-override"><code>address,caption,cite,code,dfn,em,strong,th,var {
font-style: normal;
font-weight: normal;
}
</code></pre>
<p>It makes my <code>em</code> not italic and my <code>strong</code> not bold. Which is okay. I know how to override that in my own stylesheet.</p>
<pre class="lang-css prettyprint-override"><code>strong, b
{
font-weight: bold;
}
em, i
{
font-style: italic;
}
</code></pre>
<p>The problem comes in when I have text that's both <code>em</code> and <code>strong</code>. </p>
<pre><code><strong>This is bold, <em>and this is italic, but not bold</em></strong>
</code></pre>
<p>My rule for <code>strong</code> makes it bold, but YUI's rule for <code>em</code> makes it normal again. How do I fix that? </p>
|
[
{
"answer_id": 20118,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 5,
"selected": true,
"text": "strong, b, strong *, b * { font-weight: bold; }\nem, i, em *, i * { font-style: italic; }\n"
},
{
"answer_id": 20138,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "strong, b, strong *, b *\n{\n font-weight: bold;\n}\n\nem, i, em *, i *\n{\n font-style: italic;\n}\n"
},
{
"answer_id": 20162,
"author": "alexp206",
"author_id": 666,
"author_profile": "https://Stackoverflow.com/users/666",
"pm_score": 2,
"selected": false,
"text": "font-weight: normal;\n"
},
{
"answer_id": 20265,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 0,
"selected": false,
"text": "strong, b \n{\n font-weight: bold;\n font-style: inherit;\n}\n\nem, i \n{\n font-style: italic;\n font-weight: inherit;\n}\n"
},
{
"answer_id": 20723,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 0,
"selected": false,
"text": "strong em { font-weight: bold; }\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
] |
20,146
|
<p>I'm looking for something like the <code>tempfile</code> module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...</p>
<p>It seems, .NET does not have the "batteries included" features of the <code>tempfile</code> module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (<code>mkstemp()</code> I think): <a href="https://docs.python.org/library/tempfile.html" rel="nofollow noreferrer">https://docs.python.org/library/tempfile.html</a></p>
<hr />
<p>Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...</p>
|
[
{
"answer_id": 20153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Guid.NewGuid().ToString(), \".TMP\"))\n"
},
{
"answer_id": 3378474,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 5,
"selected": false,
"text": "public sealed class TemporaryFile : IDisposable {\n public TemporaryFile() : \n this(Path.GetTempPath()) { }\n\n public TemporaryFile(string directory) {\n Create(Path.Combine(directory, Path.GetRandomFileName()));\n }\n\n ~TemporaryFile() {\n Delete();\n }\n\n public void Dispose() {\n Delete();\n GC.SuppressFinalize(this);\n }\n\n public string FilePath { get; private set; }\n\n private void Create(string path) {\n FilePath = path;\n using (File.Create(FilePath)) { };\n }\n\n private void Delete() {\n if (FilePath == null) return;\n File.Delete(FilePath);\n FilePath = null;\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
20,148
|
<p>I'm working on a projects which involves a lot of database writes, I'd say (<em>70% inserts and 30% reads</em>). This ratio would also include updates which I consider to be one read and one write. The reads can be dirty (e.g. I don't need 100% accurate information at the time of read).<br>
The task in question will be doing over 1 million database transactions an hour. </p>
<p>I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task. From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported.</p>
<p>Does anybody have any experience with this type of load (or higher)? Is MyISAM the way to go?</p>
|
[
{
"answer_id": 414934,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 6,
"selected": false,
"text": "SELECT"
},
{
"answer_id": 16785740,
"author": "Pankaj Khurana",
"author_id": 2413197,
"author_profile": "https://Stackoverflow.com/users/2413197",
"pm_score": 5,
"selected": false,
"text": "ACID transactions\nrow-level locking\nforeign key constraints\nautomatic crash recovery\ntable compression (read/write)\nspatial data types (no spatial indexes)\n"
},
{
"answer_id": 17706717,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 8,
"selected": false,
"text": "killall -9 mysqld"
},
{
"answer_id": 18088402,
"author": "tony gil",
"author_id": 1166727,
"author_profile": "https://Stackoverflow.com/users/1166727",
"pm_score": 0,
"selected": false,
"text": "USC00178998,20130101,TMAX,-22,,,7,0700\nUSC00178998,20130101,TMIN,-117,,,7,0700\nUSC00178998,20130101,TOBS,-28,,,7,0700\nUSC00178998,20130101,PRCP,0,T,,7,0700\nUSC00178998,20130101,SNOW,0,T,,7,\n"
},
{
"answer_id": 30776508,
"author": "StackG",
"author_id": 3403718,
"author_profile": "https://Stackoverflow.com/users/3403718",
"pm_score": 6,
"selected": false,
"text": "The table 'tbl' is full"
},
{
"answer_id": 43767498,
"author": "Rick James",
"author_id": 1766831,
"author_profile": "https://Stackoverflow.com/users/1766831",
"pm_score": 5,
"selected": false,
"text": "COUNT(*)"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2013/"
] |
20,156
|
<p>Is there an easy way in C# to create <a href="http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29" rel="noreferrer">Ordinals</a> for a number? For example:</p>
<ul>
<li>1 returns 1st</li>
<li>2 returns 2nd</li>
<li>3 returns 3rd</li>
<li>...etc</li>
</ul>
<p>Can this be done through <code>String.Format()</code> or are there any functions available to do this?</p>
|
[
{
"answer_id": 20166,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 4,
"selected": false,
"text": "public static string Ordinal(this int number)\n{\n var work = number.ToString();\n if ((number % 100) == 11 || (number % 100) == 12 || (number % 100) == 13)\n return work + \"th\";\n switch (number % 10)\n {\n case 1: work += \"st\"; break;\n case 2: work += \"nd\"; break;\n case 3: work += \"rd\"; break;\n default: work += \"th\"; break;\n }\n return work;\n}\n"
},
{
"answer_id": 20175,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 9,
"selected": true,
"text": "String.Format"
},
{
"answer_id": 31066,
"author": "Jesse C. Slicer",
"author_id": 3312,
"author_profile": "https://Stackoverflow.com/users/3312",
"pm_score": 4,
"selected": false,
"text": "public static string Ordinal(this int number)\n{\n const string TH = \"th\";\n var s = number.ToString();\n \n number %= 100;\n \n if ((number >= 11) && (number <= 13))\n {\n return s + TH;\n }\n \n switch (number % 10)\n {\n case 1:\n return s + \"st\";\n case 2:\n return s + \"nd\";\n case 3:\n return s + \"rd\";\n default:\n return s + TH;\n }\n}\n"
},
{
"answer_id": 111542,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 3,
"selected": false,
"text": "public class NumberUtil {\n final static String[] ORDINAL_SUFFIXES = {\n \"th\", \"st\", \"nd\", \"rd\", \"th\", \"th\", \"th\", \"th\", \"th\", \"th\"\n };\n\n public static String ordinalSuffix(int value) {\n int n = Math.abs(value);\n int lastTwoDigits = n % 100;\n int lastDigit = n % 10;\n int index = (lastTwoDigits >= 11 && lastTwoDigits <= 13) ? 0 : lastDigit;\n return ORDINAL_SUFFIXES[index];\n }\n\n public static String toOrdinal(int n) {\n return new StringBuffer().append(n).append(ordinalSuffix(n)).toString();\n }\n}\n"
},
{
"answer_id": 620504,
"author": "si618",
"author_id": 44540,
"author_profile": "https://Stackoverflow.com/users/44540",
"pm_score": 5,
"selected": false,
"text": "/// <summary>\n/// Get the ordinal value of positive integers.\n/// </summary>\n/// <remarks>\n/// Only works for english-based cultures.\n/// Code from: http://stackoverflow.com/questions/20156/is-there-a-quick-way-to-create-ordinals-in-c/31066#31066\n/// With help: http://www.wisegeek.com/what-is-an-ordinal-number.htm\n/// </remarks>\n/// <param name=\"number\">The number.</param>\n/// <returns>Ordinal value of positive integers, or <see cref=\"int.ToString\"/> if less than 1.</returns>\npublic static string Ordinal(this int number)\n{\n const string TH = \"th\";\n string s = number.ToString();\n\n // Negative and zero have no ordinal representation\n if (number < 1)\n {\n return s;\n }\n\n number %= 100;\n if ((number >= 11) && (number <= 13))\n {\n return s + TH;\n }\n\n switch (number % 10)\n {\n case 1: return s + \"st\";\n case 2: return s + \"nd\";\n case 3: return s + \"rd\";\n default: return s + TH;\n }\n}\n\n[Test]\npublic void Ordinal_ReturnsExpectedResults()\n{\n Assert.AreEqual(\"-1\", (1-2).Ordinal());\n Assert.AreEqual(\"0\", 0.Ordinal());\n Assert.AreEqual(\"1st\", 1.Ordinal());\n Assert.AreEqual(\"2nd\", 2.Ordinal());\n Assert.AreEqual(\"3rd\", 3.Ordinal());\n Assert.AreEqual(\"4th\", 4.Ordinal());\n Assert.AreEqual(\"5th\", 5.Ordinal());\n Assert.AreEqual(\"6th\", 6.Ordinal());\n Assert.AreEqual(\"7th\", 7.Ordinal());\n Assert.AreEqual(\"8th\", 8.Ordinal());\n Assert.AreEqual(\"9th\", 9.Ordinal());\n Assert.AreEqual(\"10th\", 10.Ordinal());\n Assert.AreEqual(\"11th\", 11.Ordinal());\n Assert.AreEqual(\"12th\", 12.Ordinal());\n Assert.AreEqual(\"13th\", 13.Ordinal());\n Assert.AreEqual(\"14th\", 14.Ordinal());\n Assert.AreEqual(\"20th\", 20.Ordinal());\n Assert.AreEqual(\"21st\", 21.Ordinal());\n Assert.AreEqual(\"22nd\", 22.Ordinal());\n Assert.AreEqual(\"23rd\", 23.Ordinal());\n Assert.AreEqual(\"24th\", 24.Ordinal());\n Assert.AreEqual(\"100th\", 100.Ordinal());\n Assert.AreEqual(\"101st\", 101.Ordinal());\n Assert.AreEqual(\"102nd\", 102.Ordinal());\n Assert.AreEqual(\"103rd\", 103.Ordinal());\n Assert.AreEqual(\"104th\", 104.Ordinal());\n Assert.AreEqual(\"110th\", 110.Ordinal());\n Assert.AreEqual(\"111th\", 111.Ordinal());\n Assert.AreEqual(\"112th\", 112.Ordinal());\n Assert.AreEqual(\"113th\", 113.Ordinal());\n Assert.AreEqual(\"114th\", 114.Ordinal());\n Assert.AreEqual(\"120th\", 120.Ordinal());\n Assert.AreEqual(\"121st\", 121.Ordinal());\n Assert.AreEqual(\"122nd\", 122.Ordinal());\n Assert.AreEqual(\"123rd\", 123.Ordinal());\n Assert.AreEqual(\"124th\", 124.Ordinal());\n}\n"
},
{
"answer_id": 16339730,
"author": "shawad",
"author_id": 1765067,
"author_profile": "https://Stackoverflow.com/users/1765067",
"pm_score": 2,
"selected": false,
"text": "private string[] ordinals = new string[] {\"\",\"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"st\",\"nd\",\"rd\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"th\",\"st\" };\nDateTime D = DateTime.Now;\nString date = \"Today's day is: \"+ D.Day.ToString() + ordinals[D.Day];\n"
},
{
"answer_id": 20610493,
"author": "Faust",
"author_id": 613004,
"author_profile": "https://Stackoverflow.com/users/613004",
"pm_score": 1,
"selected": false,
"text": "public static string OrdinalSuffix(int ordinal)\n{\n //Because negatives won't work with modular division as expected:\n var abs = Math.Abs(ordinal); \n\n var lastdigit = abs % 10; \n\n return \n //Catch 60% of cases (to infinity) in the first conditional:\n lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? \"th\" \n : lastdigit == 1 ? \"st\" \n : lastdigit == 2 ? \"nd\" \n : \"rd\";\n}\n"
},
{
"answer_id": 21968095,
"author": "Rupert",
"author_id": 1904153,
"author_profile": "https://Stackoverflow.com/users/1904153",
"pm_score": -1,
"selected": false,
"text": "public static string DateSuffix(int day)\n{\n if (day == 11 | day == 12 | day == 13) return \"th\";\n Math.DivRem(day, 10, out day);\n switch (day)\n {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n}\n"
},
{
"answer_id": 25935496,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 0,
"selected": false,
"text": "WHEN num % 100 IN (11, 12, 13) THEN 'th'"
},
{
"answer_id": 26282053,
"author": "Maulik Patel",
"author_id": 4125994,
"author_profile": "https://Stackoverflow.com/users/4125994",
"pm_score": -1,
"selected": false,
"text": "public static class DateTimeExtensions\n{\n public static string ToStringWithOrdinal(this DateTime d)\n {\n var result = \"\";\n bool bReturn = false; \n \n switch (d.Day % 100)\n {\n case 11:\n case 12:\n case 13:\n result = d.ToString(\"dd'th' MMMM yyyy\");\n bReturn = true;\n break;\n }\n\n if (!bReturn)\n {\n switch (d.Day % 10)\n {\n case 1:\n result = d.ToString(\"dd'st' MMMM yyyy\");\n break;\n case 2:\n result = d.ToString(\"dd'nd' MMMM yyyy\");\n break;\n case 3:\n result = d.ToString(\"dd'rd' MMMM yyyy\");\n break;\n default:\n result = d.ToString(\"dd'th' MMMM yyyy\");\n break;\n }\n\n }\n\n if (result.StartsWith(\"0\")) result = result.Substring(1);\n return result;\n }\n}\n"
},
{
"answer_id": 26433514,
"author": "Shahzad Qureshi",
"author_id": 2719563,
"author_profile": "https://Stackoverflow.com/users/2719563",
"pm_score": 5,
"selected": false,
"text": "private static string GetOrdinalSuffix(int num)\n{\n string number = num.ToString();\n if (number.EndsWith(\"11\")) return \"th\";\n if (number.EndsWith(\"12\")) return \"th\";\n if (number.EndsWith(\"13\")) return \"th\";\n if (number.EndsWith(\"1\")) return \"st\";\n if (number.EndsWith(\"2\")) return \"nd\";\n if (number.EndsWith(\"3\")) return \"rd\";\n return \"th\";\n}\n"
},
{
"answer_id": 27509908,
"author": "Whelkaholism",
"author_id": 318411,
"author_profile": "https://Stackoverflow.com/users/318411",
"pm_score": 1,
"selected": false,
"text": "public static String GetOrdinal(int i)\n{\n String res = \"\";\n\n if (i > 0)\n {\n int j = (i - ((i / 100) * 100));\n\n if ((j == 11) || (j == 12) || (j == 13))\n res = \"th\";\n else\n {\n int k = i % 10;\n\n if (k == 1)\n res = \"st\";\n else if (k == 2)\n res = \"nd\";\n else if (k == 3)\n res = \"rd\";\n else\n res = \"th\";\n }\n }\n\n return i.ToString() + res;\n}\n"
},
{
"answer_id": 36878179,
"author": "Ali Humayun",
"author_id": 1845464,
"author_profile": "https://Stackoverflow.com/users/1845464",
"pm_score": 2,
"selected": false,
"text": "private static string GetOrd(int num) => $\"{num}{(!(Range(11, 3).Any(n => n == num % 100) ^ Range(1, 3).All(n => n != num % 10)) ? new[] { \"ˢᵗ\", \"ⁿᵈ\", \"ʳᵈ\" }[num % 10 - 1] : \"ᵗʰ\")}\";\n"
},
{
"answer_id": 39665303,
"author": "Perry Tribolet",
"author_id": 5668,
"author_profile": "https://Stackoverflow.com/users/5668",
"pm_score": 2,
"selected": false,
"text": "public static class Int32Extensions\n{\n public static string ToOrdinal(this int i)\n {\n return (i + \"th\")\n .Replace(\"1th\", \"1st\")\n .Replace(\"2th\", \"2nd\")\n .Replace(\"3th\", \"3rd\");\n }\n}\n"
},
{
"answer_id": 43260913,
"author": "Ian Warburton",
"author_id": 221683,
"author_profile": "https://Stackoverflow.com/users/221683",
"pm_score": 2,
"selected": false,
"text": "public static string AddOrdinal(int number)\n{\n if (number <= 0) return number.ToString();\n\n string GetIndicator(int num)\n {\n switch (num % 100)\n {\n case 11:\n case 12:\n case 13:\n return \"th\";\n }\n\n switch (num % 10)\n {\n case 1:\n return \"st\";\n case 2:\n return \"nd\";\n case 3:\n return \"rd\";\n default:\n return \"th\";\n }\n }\n\n return number + GetIndicator(number);\n}\n"
},
{
"answer_id": 44010138,
"author": "Dave Sumter",
"author_id": 706866,
"author_profile": "https://Stackoverflow.com/users/706866",
"pm_score": 1,
"selected": false,
"text": "public static string Ordinal(int n)\n{ \n int r = n % 100, m = n % 10;\n\n return (r<4 || r>20) && (m>0 && m<4) ? n+\" stndrd\".Substring(m*2,2) : n+\"th\"; \n}\n"
},
{
"answer_id": 56439487,
"author": "Phani Rithvij",
"author_id": 8608146,
"author_profile": "https://Stackoverflow.com/users/8608146",
"pm_score": 0,
"selected": false,
"text": "dart"
},
{
"answer_id": 58378465,
"author": "Dan Dohotaru",
"author_id": 2583579,
"author_profile": "https://Stackoverflow.com/users/2583579",
"pm_score": 1,
"selected": false,
"text": "public static string Ordinals1(this int number)\n{\n switch (number)\n {\n case int p when p % 100 == 11:\n case int q when q % 100 == 12:\n case int r when r % 100 == 13:\n return $\"{number}th\";\n case int p when p % 10 == 1:\n return $\"{number}st\";\n case int p when p % 10 == 2:\n return $\"{number}nd\";\n case int p when p % 10 == 3:\n return $\"{number}rd\";\n default:\n return $\"{number}th\";\n }\n}\n"
},
{
"answer_id": 58632762,
"author": "Pluto",
"author_id": 1507941,
"author_profile": "https://Stackoverflow.com/users/1507941",
"pm_score": 0,
"selected": false,
"text": "public static string GetOrdinalSuffix(int input)\n{\n return new []{\"th\", \"st\", \"nd\", \"rd\"}[Convert.ToInt32(\"0\" + Regex.Match(input.ToString(), \"(?<!1)[1-3]$\").Value)];\n}\n"
},
{
"answer_id": 61644903,
"author": "Echostorm",
"author_id": 12862,
"author_profile": "https://Stackoverflow.com/users/12862",
"pm_score": 0,
"selected": false,
"text": "public static string Ordinal(this int n)\n{ \n return n + (new [] {\"st\",\"nd\",\"rd\" }.ElementAtOrDefault((((n + 90) % 100 - 10) % 10 - 1)) ?? \"th\");\n}\n"
},
{
"answer_id": 72025082,
"author": "aloisdg",
"author_id": 1248177,
"author_profile": "https://Stackoverflow.com/users/1248177",
"pm_score": 1,
"selected": false,
"text": "Ordinalize"
},
{
"answer_id": 72792661,
"author": "Grastveit",
"author_id": 470022,
"author_profile": "https://Stackoverflow.com/users/470022",
"pm_score": 1,
"selected": false,
"text": "string.Concat(number, number < 0 ? \"\" : (number % 100) switch \n{ \n 11 or 12 or 13 => \"th\", \n int n => (n % 10) switch \n { \n 1 => \"st\", \n 2 => \"nd\", \n 3 => \"rd\", \n _ => \"th\", \n }\n})\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
20,173
|
<p>Does anyone have any experience getting MSTest to copy hibernate.cfg.xml properly to the output directory? All my MSTests fail with a cannot find hibernate.cfg.xml error (I have it set to Copy Always), but my MBUnit tests pass.</p>
|
[
{
"answer_id": 178478,
"author": "Watson",
"author_id": 25807,
"author_profile": "https://Stackoverflow.com/users/25807",
"pm_score": 2,
"selected": false,
"text": " try\n {\n sessionFactory = new Configuration()\n .Configure()\n .BuildSessionFactory();\n }\n // Assume we are in \"MSTest mode\"\n catch (Exception)\n {\n sessionFactory = new Configuration()\n .Configure(@\"..\\..\\..\\Program.Tests\\\" + @\"\\hibernate.cfg.xml\")\n .BuildSessionFactory();\n }\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1975/"
] |
20,185
|
<p>I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. </p>
<p>Is there any way to hide a constructor from all code except a parent class.</p>
<p>I'd like to do this basically</p>
<pre><code>public abstract class AbstractClass
{
public static AbstractClass MakeAbstractClass(string args)
{
if (args == "a")
return new ConcreteClassA();
if (args == "b")
return new ConcreteClassB();
}
}
public class ConcreteClassA : AbstractClass
{
}
public class ConcreteClassB : AbstractClass
{
}
</code></pre>
<p>But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this?</p>
<p><strong>UPDATE</strong><br>
I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class.</p>
<p>To me, the simplest solution is to <a href="https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200">make child classes as samjudson mentioned</a>. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization.</p>
<p>I guess there's no easy solution to this...</p>
|
[
{
"answer_id": 20200,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": true,
"text": "public abstract class AbstractClass\n{\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return new ConcreteClassA();\n if (args == \"b\")\n return new ConcreteClassB();\n }\n\n private class ConcreteClassA : AbstractClass\n {\n }\n\n private class ConcreteClassB : AbstractClass\n {\n }\n}\n"
},
{
"answer_id": 20266,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 3,
"selected": false,
"text": "public abstract class AbstractClass\n{\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return (AbstractClass)Activator.CreateInstance(typeof(ConcreteClassA), true);\n if (args == \"b\")\n return (AbstractClass)Activator.CreateInstance(typeof(ConcreteClassB), true);\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n private ConcreteClassA()\n {\n }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n private ConcreteClassB()\n {\n }\n}\n"
},
{
"answer_id": 20279,
"author": "Jedi Master Spooky",
"author_id": 1154,
"author_profile": "https://Stackoverflow.com/users/1154",
"pm_score": -1,
"selected": false,
"text": "public abstract class AbstractClass{\n\n public static AbstractClass MakeAbstractClass(string args)\n {\n if (args == \"a\")\n return ConcreteClassA().GetConcreteClassA();\n if (args == \"b\")\n return ConcreteClassB().GetConcreteClassB();\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n private ConcreteClassA(){}\n\n internal static ConcreteClassA GetConcreteClassA(){\n return ConcreteClassA();\n }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n private ConcreteClassB(){}\n internal static ConcreteClassB Get ConcreteClassB(){\n return ConcreteClassB();\n }\n\n}\n"
},
{
"answer_id": 20325,
"author": "Peteter",
"author_id": 1192,
"author_profile": "https://Stackoverflow.com/users/1192",
"pm_score": 0,
"selected": false,
"text": "partial"
},
{
"answer_id": 24338,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "public class AbstractClass\n{\n public AbstractClass ClassFactory(string args)\n {\n switch (args)\n {\n case \"A\":\n return new ConcreteClassA(); \n case \"B\":\n return new ConcreteClassB(); \n default:\n return null;\n }\n }\n}\n\npublic class ConcreteClassA : AbstractClass\n{\n internal ConcreteClassA(){ }\n}\n\npublic class ConcreteClassB : AbstractClass\n{\n internal ConcreteClassB() {}\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
20,198
|
<p>I thought .Net code gets compiled into MSIL, so I always wondered how do Yellow Screens produce the faulty code. If it's executing the compiled code, how is the compiler able to produce code from the source files in the error message?</p>
<p>Feel free to edit this question/title, I know it doesn't really make sense.</p>
|
[
{
"answer_id": 20315,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 3,
"selected": false,
"text": "// reverse the stack\nprivate static Stack<Exception> GenerateExceptionStack(Exception exception)\n{\n var exceptionStack = new Stack<Exception>();\n\n // create exception stack\n for (Exception e = exception; e != null; e = e.InnerException)\n {\n exceptionStack.Push(e);\n }\n\n return exceptionStack;\n}\n\n// render stack\nprivate static string GenerateFormattedStackTrace(Stack<Exception> exceptionStack)\n{\n StringBuilder trace = new StringBuilder();\n\n try\n {\n // loop through exception stack\n while (exceptionStack.Count != 0)\n {\n trace.Append(\"\\r\\n\");\n\n // render exception type and message\n Exception ex = exceptionStack.Pop();\n trace.Append(\"[\" + ex.GetType().Name);\n if (!string.IsNullOrEmpty(ex.Message))\n {\n trace.Append(\":\" + ex.Message);\n }\n trace.Append(\"]\\r\\n\");\n\n // Load stack trace\n StackTrace stackTrace = new StackTrace(ex, true);\n for (int frame = 0; frame < stackTrace.FrameCount; frame++)\n {\n StackFrame stackFrame = stackTrace.GetFrame(frame);\n MethodBase method = stackFrame.GetMethod();\n Type declaringType = method.DeclaringType;\n string declaringNamespace = \"\";\n\n // get declaring type information\n if (declaringType != null)\n {\n declaringNamespace = declaringType.Namespace ?? \"\";\n }\n\n // add namespace\n if (!string.IsNullOrEmpty(declaringNamespace))\n {\n declaringNamespace += \".\";\n }\n\n // add method\n if (declaringType == null)\n {\n trace.Append(\" \" + method.Name + \"(\");\n }\n else\n {\n trace.Append(\" \" + declaringNamespace + declaringType.Name + \".\" + method.Name + \"(\");\n }\n\n // get parameter information\n ParameterInfo[] parameters = method.GetParameters();\n for (int paramIndex = 0; paramIndex < parameters.Length; paramIndex++)\n {\n trace.Append(((paramIndex != 0) ? \",\" : \"\") + parameters[paramIndex].ParameterType.Name + \" \" + parameters[paramIndex].Name);\n }\n trace.Append(\")\");\n\n\n // get information\n string fileName = stackFrame.GetFileName() ?? \"\";\n\n if (!string.IsNullOrEmpty(fileName))\n {\n trace.Append(string.Concat(new object[] { \" in \", fileName, \":\", stackFrame.GetFileLineNumber() }));\n }\n else\n {\n trace.Append(\" + \" + stackFrame.GetNativeOffset());\n }\n\n trace.Append(\"\\r\\n\");\n }\n }\n }\n catch\n {\n }\n\n if (trace.Length == 0)\n {\n trace.Append(\"[stack trace unavailable]\");\n }\n\n // return html safe stack trace\n return HttpUtility.HtmlEncode(trace.ToString()).Replace(Environment.NewLine, \"<br>\");\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] |
20,227
|
<p>Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?</p>
<p>I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:</p>
<p>** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.</p>
<pre><code>public class TripleDESTest {
public static void main(String[] args) {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext);
System.out.println(decodedtext);
}
public byte[] encrypt(String message) {
try {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText);
return cipherText;
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
return null;
}
public String decrypt(byte[] message) {
try
{
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;)
{
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
//final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return plainText.toString();
}
catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); }
catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); }
catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); }
catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); }
catch (BadPaddingException e) { System.out.println("Invalid Key");}
catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");}
catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
</code></pre>
|
[
{
"answer_id": 20670,
"author": "Boris Terzic",
"author_id": 1996,
"author_profile": "https://Stackoverflow.com/users/1996",
"pm_score": 7,
"selected": true,
"text": "import java.security.MessageDigest;\nimport java.util.Arrays;\n\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.spec.IvParameterSpec;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class TripleDESTest {\n\n public static void main(String[] args) throws Exception {\n\n String text = \"kyle boon\";\n\n byte[] codedtext = new TripleDESTest().encrypt(text);\n String decodedtext = new TripleDESTest().decrypt(codedtext);\n\n System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array\n System.out.println(decodedtext); // This correctly shows \"kyle boon\"\n }\n\n public byte[] encrypt(String message) throws Exception {\n final MessageDigest md = MessageDigest.getInstance(\"md5\");\n final byte[] digestOfPassword = md.digest(\"HG58YZ3CR9\"\n .getBytes(\"utf-8\"));\n final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n for (int j = 0, k = 16; j < 8;) {\n keyBytes[k++] = keyBytes[j++];\n }\n\n final SecretKey key = new SecretKeySpec(keyBytes, \"DESede\");\n final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n final Cipher cipher = Cipher.getInstance(\"DESede/CBC/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, key, iv);\n\n final byte[] plainTextBytes = message.getBytes(\"utf-8\");\n final byte[] cipherText = cipher.doFinal(plainTextBytes);\n // final String encodedCipherText = new sun.misc.BASE64Encoder()\n // .encode(cipherText);\n\n return cipherText;\n }\n\n public String decrypt(byte[] message) throws Exception {\n final MessageDigest md = MessageDigest.getInstance(\"md5\");\n final byte[] digestOfPassword = md.digest(\"HG58YZ3CR9\"\n .getBytes(\"utf-8\"));\n final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);\n for (int j = 0, k = 16; j < 8;) {\n keyBytes[k++] = keyBytes[j++];\n }\n\n final SecretKey key = new SecretKeySpec(keyBytes, \"DESede\");\n final IvParameterSpec iv = new IvParameterSpec(new byte[8]);\n final Cipher decipher = Cipher.getInstance(\"DESede/CBC/PKCS5Padding\");\n decipher.init(Cipher.DECRYPT_MODE, key, iv);\n\n // final byte[] encData = new\n // sun.misc.BASE64Decoder().decodeBuffer(message);\n final byte[] plainText = decipher.doFinal(message);\n\n return new String(plainText, \"UTF-8\");\n }\n}\n"
},
{
"answer_id": 10164989,
"author": "jlmontesdeoca",
"author_id": 1334941,
"author_profile": "https://Stackoverflow.com/users/1334941",
"pm_score": 4,
"selected": false,
"text": "\n\n import java.security.InvalidKeyException;\n import java.security.NoSuchAlgorithmException;\n import java.security.NoSuchProviderException;\n import java.security.Security;\n import javax.crypto.BadPaddingException;\n import javax.crypto.Cipher;\n import javax.crypto.IllegalBlockSizeException;\n import javax.crypto.NoSuchPaddingException;\n import javax.crypto.SecretKey;\n import javax.crypto.spec.SecretKeySpec;\n import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n\n /**\n *\n * @author Jose Luis Montes de Oca\n */\n public class TripleDesCipher {\n private static String TRIPLE_DES_TRANSFORMATION = \"DESede/ECB/Nopadding\";\n private static String ALGORITHM = \"DESede\";\n private static String BOUNCY_CASTLE_PROVIDER = \"BC\";\n private Cipher encrypter;\n private Cipher decrypter;\n\n public TripleDesCipher(byte[] key) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,\n InvalidKeyException {\n Security.addProvider(new BouncyCastleProvider());\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION, BOUNCY_CASTLE_PROVIDER);\n decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n }\n\n public byte[] encode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n return encrypter.doFinal(input);\n }\n\n public byte[] decode(byte[] input) throws IllegalBlockSizeException, BadPaddingException {\n return decrypter.doFinal(input);\n }\n }\n\n"
},
{
"answer_id": 11367849,
"author": "siliconsmiley",
"author_id": 1024005,
"author_profile": "https://Stackoverflow.com/users/1024005",
"pm_score": 2,
"selected": false,
"text": "\n package com.zenimax.encryption;\n\n import java.security.InvalidKeyException;\n import java.security.NoSuchAlgorithmException;\n import java.security.NoSuchProviderException;\n import java.security.Security;\n import javax.crypto.BadPaddingException;\n import javax.crypto.Cipher;\n import javax.crypto.IllegalBlockSizeException;\n import javax.crypto.NoSuchPaddingException;\n import javax.crypto.SecretKey;\n import javax.crypto.spec.SecretKeySpec;\n import org.bouncycastle.jce.provider.BouncyCastleProvider;\n\n /**\n * \n * @author Matthew H. Wagner\n */\n public class TripleDesBouncyCastle {\n private static String TRIPLE_DES_TRANSFORMATION = \"DESede/ECB/PKCS7Padding\";\n private static String ALGORITHM = \"DESede\";\n private static String BOUNCY_CASTLE_PROVIDER = \"BC\";\n\n private static void init()\n {\n Security.addProvider(new BouncyCastleProvider());\n }\n\n public static byte[] encode(byte[] input, byte[] key)\n throws IllegalBlockSizeException, BadPaddingException,\n NoSuchAlgorithmException, NoSuchProviderException,\n NoSuchPaddingException, InvalidKeyException {\n init();\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n BOUNCY_CASTLE_PROVIDER);\n encrypter.init(Cipher.ENCRYPT_MODE, keySpec);\n return encrypter.doFinal(input);\n }\n\n public static byte[] decode(byte[] input, byte[] key)\n throws IllegalBlockSizeException, BadPaddingException,\n NoSuchAlgorithmException, NoSuchProviderException,\n NoSuchPaddingException, InvalidKeyException {\n init();\n SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);\n Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,\n BOUNCY_CASTLE_PROVIDER);\n decrypter.init(Cipher.DECRYPT_MODE, keySpec);\n return decrypter.doFinal(input);\n }\n }\n"
},
{
"answer_id": 13612902,
"author": "oneiros",
"author_id": 861832,
"author_profile": "https://Stackoverflow.com/users/861832",
"pm_score": 4,
"selected": false,
"text": "import java.security.spec.KeySpec;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKey;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport org.apache.commons.codec.binary.Base64;\n\npublic class TrippleDes {\n\n private static final String UNICODE_FORMAT = \"UTF8\";\n public static final String DESEDE_ENCRYPTION_SCHEME = \"DESede\";\n private KeySpec ks;\n private SecretKeyFactory skf;\n private Cipher cipher;\n byte[] arrayBytes;\n private String myEncryptionKey;\n private String myEncryptionScheme;\n SecretKey key;\n\n public TrippleDes() throws Exception {\n myEncryptionKey = \"ThisIsSpartaThisIsSparta\";\n myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;\n arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);\n ks = new DESedeKeySpec(arrayBytes);\n skf = SecretKeyFactory.getInstance(myEncryptionScheme);\n cipher = Cipher.getInstance(myEncryptionScheme);\n key = skf.generateSecret(ks);\n }\n\n\n public String encrypt(String unencryptedString) {\n String encryptedString = null;\n try {\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n }\n\n\n public String decrypt(String encryptedString) {\n String decryptedText=null;\n try {\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n }\n\n\n public static void main(String args []) throws Exception\n {\n TrippleDes td= new TrippleDes();\n\n String target=\"imparator\";\n String encrypted=td.encrypt(target);\n String decrypted=td.decrypt(encrypted);\n\n System.out.println(\"String To Encrypt: \"+ target);\n System.out.println(\"Encrypted String:\" + encrypted);\n System.out.println(\"Decrypted String:\" + decrypted);\n\n }\n\n}\n"
},
{
"answer_id": 25397364,
"author": "shiv",
"author_id": 3728540,
"author_profile": "https://Stackoverflow.com/users/3728540",
"pm_score": -1,
"selected": false,
"text": "import java.io.IOException;\nimport java.io.UnsupportedEncodingException;\nimport java.security.Key;\nimport javax.crypto.Cipher;\nimport javax.crypto.SecretKeyFactory;\nimport javax.crypto.spec.DESedeKeySpec;\nimport javax.crypto.spec.IvParameterSpec;\nimport java.util.Base64;\nimport java.util.Base64.Encoder;\n\n\n/**\n * \n * @author shivshankar pal\n * \n * this code is working properly. doing proper encription and decription\n note:- it will work only with jdk8\n\n * \n\n * \n */\n\npublic class TDes {\n private static byte[] key = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02,\n 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 };\n\n private static byte[] keyiv = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n 0x00 };\n\n\n\n public static String encode(String args) {\n\n\n System.out.println(\"plain data==> \" + args);\n\n byte[] encoding;\n try {\n encoding = Base64.getEncoder().encode(args.getBytes(\"UTF-8\"));\n\n System.out.println(\"Base64.encodeBase64==>\" + new String(encoding));\n byte[] str5 = des3EncodeCBC(key, keyiv, encoding);\n\n System.out.println(\"des3EncodeCBC==> \" + new String(str5));\n\n byte[] encoding1 = Base64.getEncoder().encode(str5);\n System.out.println(\"Base64.encodeBase64==> \" + new String(encoding1));\n return new String(encoding1);\n } catch (UnsupportedEncodingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return null;\n }\n\n\n public static String decode(String args) {\n try {\n System.out.println(\"encrypted data==>\" + new String(args.getBytes(\"UTF-8\")));\n\n\n byte[] decode = Base64.getDecoder().decode(args.getBytes(\"UTF-8\"));\n System.out.println(\"Base64.decodeBase64(main encription)==>\" + new String(decode));\n\n byte[] str6 = des3DecodeCBC(key, keyiv, decode);\n System.out.println(\"des3DecodeCBC==>\" + new String(str6));\n String data=new String(str6);\n byte[] decode1 = Base64.getDecoder().decode(data.trim().getBytes(\"UTF-8\"));\n System.out.println(\"plaintext==> \" + new String(decode1));\n return new String(decode1);\n } catch (UnsupportedEncodingException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n return \"u mistaken in try block\";\n\n }\n\n\n\n private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n try {\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key);\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n\n Cipher cipher = Cipher.getInstance(\"desede/ CBC/PKCS5Padding\");\n IvParameterSpec ips = new IvParameterSpec(keyiv);\n cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);\n byte[] bout = cipher.doFinal(data);\n return bout;\n\n } catch (Exception e) {\n System.out.println(\"methods qualified name\" + e);\n }\n return null;\n\n }\n\n private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) {\n try {\n Key deskey = null;\n DESedeKeySpec spec = new DESedeKeySpec(key);\n SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(\"desede\");\n deskey = keyfactory.generateSecret(spec);\n\n Cipher cipher = Cipher.getInstance(\"desede/ CBC/NoPadding\");//PKCS5Padding NoPadding\n IvParameterSpec ips = new IvParameterSpec(keyiv);\n cipher.init(Cipher.DECRYPT_MODE, deskey, ips);\n\n byte[] bout = cipher.doFinal(data);\n\n\n return bout;\n\n } catch (Exception e) {\n System.out.println(\"methods qualified name\" + e);\n }\n\n return null;\n\n }\n\n}\n"
},
{
"answer_id": 70600508,
"author": "Ayomide Joysbright Oyediran",
"author_id": 15661514,
"author_profile": "https://Stackoverflow.com/users/15661514",
"pm_score": 0,
"selected": false,
"text": "private static final String UNICODE_FORMAT = \"UTF8\";\nprivate static final String DESEDE_ENCRYPTION_SCHEME = \"DESede\";\nprivate KeySpec ks;\nprivate SecretKeyFactory skf;\nprivate Cipher cipher;\nbyte[] arrayBytes;\nprivate String encryptionSecretKey = \"ThisIsSpartaThisIsSparta\";\nSecretKey key;\n\npublic TripleDesEncryptDecrypt() throws Exception {\n convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic TripleDesEncryptDecrypt(String encryptionSecretKey) throws Exception {\n convertStringToSecretKey(encryptionSecretKey);\n}\n\npublic SecretKey convertStringToSecretKey (String encryptionSecretKey) throws Exception {\n arrayBytes = encryptionSecretKey.getBytes(UNICODE_FORMAT);\n ks = new DESedeKeySpec(arrayBytes);\n skf = SecretKeyFactory.getInstance(DESEDE_ENCRYPTION_SCHEME);\n cipher = Cipher.getInstance(DESEDE_ENCRYPTION_SCHEME);\n key = skf.generateSecret(ks);\n return key;\n}\n\n/**\n * Encrypt without specifying secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String unencryptedString) {\n String encryptedString = null;\n try {\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n}\n\n/**\n * Encrypt with specified secret key\n * \n * @param unencryptedString\n * @return String\n */\npublic String encrypt(String encryptionSecretKey, String unencryptedString) {\n String encryptedString = null;\n try {\n key = convertStringToSecretKey(encryptionSecretKey);\n cipher.init(Cipher.ENCRYPT_MODE, key);\n byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);\n byte[] encryptedText = cipher.doFinal(plainText);\n encryptedString = new String(Base64.encodeBase64(encryptedText));\n } catch (Exception e) {\n e.printStackTrace();\n }\n return encryptedString;\n}\n\n\n/**\n * Decrypt without specifying secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptedString) {\n String decryptedText=null;\n try {\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n}\n\n/**\n * Decrypt with specified secret key\n * @param encryptedString\n * @return\n */\npublic String decrypt(String encryptionSecretKey, String encryptedString) {\n String decryptedText=null;\n try {\n key = convertStringToSecretKey(encryptionSecretKey);\n cipher.init(Cipher.DECRYPT_MODE, key);\n byte[] encryptedText = Base64.decodeBase64(encryptedString);\n byte[] plainText = cipher.doFinal(encryptedText);\n decryptedText= new String(plainText);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return decryptedText;\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
] |
20,245
|
<p>I am doing an e-commerce solution in ASP.NET which uses <a href="https://www.paypal.com/IntegrationCenter/ic_standard_home.html" rel="noreferrer">PayPal's Website Payments Standard</a> service. Together with that I use a service they offer (<a href="https://www.paypal.com/IntegrationCenter/ic_pdt.html" rel="noreferrer">Payment Data Transfer</a>) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :</p>
<blockquote>
<p>SUCCESS<br>
first_name=Jane+Doe<br>
last_name=Smith<br>
payment_status=Completed<br>
payer_email=janedoesmith%40hotmail.com<br>
payment_gross=3.99<br>
mc_currency=USD<br>
custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham</p>
</blockquote>
<p>Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.</p>
|
[
{
"answer_id": 20274,
"author": "Markus Olsson",
"author_id": 2114,
"author_profile": "https://Stackoverflow.com/users/2114",
"pm_score": 5,
"selected": true,
"text": "if (Request.RequestType == \"POST\")\n{\n using (StreamReader sr = new StreamReader(Request.InputStream))\n {\n if (sr.ReadLine() == \"SUCCESS\")\n {\n /* Do your parsing here */\n }\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1801/"
] |
20,263
|
<p>"Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring an instance of the Database Engine or Analysis Services."</p>
<p>I find using SQL Server Profiler extremely useful during development, testing and when I am debugging database application problems. Does anybody know if there is an equivalent program for MySql?</p>
|
[
{
"answer_id": 82757,
"author": "Jon Topper",
"author_id": 6945,
"author_profile": "https://Stackoverflow.com/users/6945",
"pm_score": 4,
"selected": false,
"text": "log = /var/lib/mysql/query.log"
},
{
"answer_id": 14636239,
"author": "Matija",
"author_id": 779965,
"author_profile": "https://Stackoverflow.com/users/779965",
"pm_score": 3,
"selected": false,
"text": "# * Logging and Replication\n# Both location gets rotated by the cronjob.\n# Be aware that this log type is a performance killer.\n\nlog = /var/log/mysql/mysql.log\n"
},
{
"answer_id": 44026778,
"author": "Mauricio Alo",
"author_id": 1902560,
"author_profile": "https://Stackoverflow.com/users/1902560",
"pm_score": 3,
"selected": false,
"text": "SET profiling = 1;\ncall your_procedure;\nSHOW PROFILES;\nSET profiling = 0;\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982/"
] |
20,267
|
<p>I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this?</p>
|
[
{
"answer_id": 20341,
"author": "Slavo",
"author_id": 1801,
"author_profile": "https://Stackoverflow.com/users/1801",
"pm_score": 3,
"selected": false,
"text": "MailDefinition md = new MailDefinition();\nmd.BodyFileName = pathToTemplate;\nmd.From = \"test@somedomain.com\";\n\nListDictionary replacements = new ListDictionary();\nreplacements.Add(\"<%To%>\", someValue);\n// continue adding replacements\n\nMailMessage msg = md.CreateMailMessage(\"test@someotherdomain.com\", replacements, this);\n"
},
{
"answer_id": 7291301,
"author": "ThisGuy",
"author_id": 910348,
"author_profile": "https://Stackoverflow.com/users/910348",
"pm_score": 1,
"selected": false,
"text": "static string SimpleTemplate(string template, Dictionary<string, string> replacements)\n{\n // parse the message into an array of tokens\n Regex regex = new Regex(\"(##[^#]+##)\");\n string[] tokens = regex.Split(template);\n\n // the new message from the tokens\n var sb = new StringBuilder((int)((double)template.Length * 1.1));\n foreach (string token in tokens)\n sb.Append(replacements.ContainsKey(token) ? replacements[token] : token);\n\n return sb.ToString();\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1436/"
] |
20,272
|
<p>In a macro for Visual Studio 6, I wanted to run an external program, so I typed:</p>
<pre><code>shell("p4 open " + ActiveDocument.FullName)
</code></pre>
<p>Which gave me a type mismatch runtime error. What I ended up having to type was this:</p>
<pre><code>Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
strResult = wshShell.Run("p4 open " + ActiveDocument.FullName)
</code></pre>
<p>What is going on here? Is that nonsense really necessary or have I missed something?</p>
|
[
{
"answer_id": 20353,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 0,
"selected": false,
"text": "Shell \"p4 open\" & ActiveDocument.FullName\n"
},
{
"answer_id": 29042,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 2,
"selected": true,
"text": "WScript.Echo \"Hello, World!\"\n"
},
{
"answer_id": 29096,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": -1,
"selected": false,
"text": "Shell \"p4 open \"\"\" & ActiveDocument.FullName & \"\"\"\"\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1105/"
] |
20,298
|
<p>I have something like this:</p>
<pre>
barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation(
barProgress.Value, dNextProgressValue,
new Duration(TimeSpan.FromSeconds(dDuration)));
</pre>
<p>Now, how would you stop that animation (the <code>DoubleAnimation</code>)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...</p>
|
[
{
"answer_id": 20306,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 8,
"selected": true,
"text": "BeginAnimation"
},
{
"answer_id": 36744,
"author": "user3837",
"author_id": 3837,
"author_profile": "https://Stackoverflow.com/users/3837",
"pm_score": 5,
"selected": false,
"text": "public void Begin(\n FrameworkContentElement containingObject,\n **bool isControllable**\n)\n"
},
{
"answer_id": 1071741,
"author": "Junior Mayhé",
"author_id": 66708,
"author_profile": "https://Stackoverflow.com/users/66708",
"pm_score": 3,
"selected": false,
"text": "MyBeginStoryboard.Storyboard.Begin(this, true);\nMyBeginStoryboard.Storyboard.Stop(this);\n"
},
{
"answer_id": 9436145,
"author": "BruceLH",
"author_id": 1231415,
"author_profile": "https://Stackoverflow.com/users/1231415",
"pm_score": 4,
"selected": false,
"text": "DoubleAnimation myAnimation = new Animation();\n// Initialize animation\n...\n\n// To start\nelement.BeginAnimation(Property, myAnimation);\n\n// To stop and keep the current value of the animated property\nmyAnimation.BeginTime = null;\nelement.BeginAnimation(Property, myAnimation);\n"
},
{
"answer_id": 18101726,
"author": "oliver",
"author_id": 1145234,
"author_profile": "https://Stackoverflow.com/users/1145234",
"pm_score": 0,
"selected": false,
"text": "[StoryBoardName].Remove([StoryBoardOwnerControl]);\n"
},
{
"answer_id": 33472902,
"author": "Fawaz",
"author_id": 4998659,
"author_profile": "https://Stackoverflow.com/users/4998659",
"pm_score": 4,
"selected": false,
"text": "<Trigger.EnterActions>\n <BeginStoryboard x:Name=\"myStory\">\n .........\n </BeginStoryboard>\n</Trigger.EnterActions>\n<Trigger.ExitActions>\n <StopStoryboard BeginStoryboardName=\"myStory\"/>\n</Trigger.ExitActions>\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
20,326
|
<p>I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.</p>
<p>I have checked and checked the code, and I can't find the cause.</p>
<p>Here are both call stacks which end in a page_load</p>
<p>First postback (generated by teh ComboBox's autopostback)</p>
<p><a href="http://www.juanformoso.com.ar/images/callstack1.jpg" rel="nofollow noreferrer">Postback call stack</a> (broken)</p>
<p>Second postback (this is what I want to find why it's happening)</p>
<p><a href="http://www.juanformoso.com.ar/images/callstack2.jpg" rel="nofollow noreferrer">alt text</a> (broken)</p>
<p>Any suggestion? What can I check?</p>
|
[
{
"answer_id": 20479,
"author": "Jason Shoulders",
"author_id": 1953,
"author_profile": "https://Stackoverflow.com/users/1953",
"pm_score": 0,
"selected": false,
"text": "Dim i As Integer\ni = 0\n"
},
{
"answer_id": 20649,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 4,
"selected": true,
"text": "onchange"
},
{
"answer_id": 2801589,
"author": "Ealavan",
"author_id": 337121,
"author_profile": "https://Stackoverflow.com/users/337121",
"pm_score": 0,
"selected": false,
"text": "<script>var Q = 0;</script>\n<form id=\"Form1\" runat=\"server\" onsubmit=\"Q++; if(Q==1){return true;} else { return false;}\">\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
20,346
|
<p>What are attributes in .NET, what are they good for, and how do I create my own attributes?</p>
|
[
{
"answer_id": 20418,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 8,
"selected": true,
"text": "public class DisplayWrapper\n{\n private UnderlyingClass underlyingObject;\n\n public DisplayWrapper(UnderlyingClass u)\n {\n underlyingObject = u;\n }\n\n [DisplayOrder(1)]\n public int SomeInt\n {\n get\n {\n return underlyingObject .SomeInt;\n }\n }\n\n [DisplayOrder(2)]\n public DateTime SomeDate\n {\n get\n {\n return underlyingObject .SomeDate;\n }\n }\n}\n"
},
{
"answer_id": 20455,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 4,
"selected": false,
"text": "[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)]\npublic class SortOrderAttribute : Attribute\n{\n public int SortOrder { get; set; }\n\n public SortOrderAttribute(int sortOrder)\n {\n this.SortOrder = sortOrder;\n }\n}\n"
},
{
"answer_id": 20508,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": false,
"text": "UserControl"
},
{
"answer_id": 394559,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 2,
"selected": false,
"text": "attribute"
},
{
"answer_id": 554006,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 5,
"selected": false,
"text": "sealed"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1595/"
] |
20,363
|
<p>I have a database with a table Customers that have some data<br><br>
I have another database in the office that everything is the same, but my table Customers is empty<br><br>
How can I create a sql file in SQL Server 2005 (T-SQL) that takes everything on the table Customers from the first database, creates a, let's say, buildcustomers.sql, I zip that file, copy it across the network, execute it in my SQL Server and voila! my table Customers is full<br>
<br>
How can I do the same for a whole database?</p>
|
[
{
"answer_id": 228896,
"author": "Nordin",
"author_id": 29669,
"author_profile": "https://Stackoverflow.com/users/29669",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO [DestinationDB].[schema].[table] ([column])\nSELECT [column] FROM [OriginDB].[schema].[table]\nGO\n"
},
{
"answer_id": 228957,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 5,
"selected": false,
"text": "bcp"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
20,386
|
<p>What are all the possible ways in which we can get memory leaks in .NET?</p>
<p>I know of two:</p>
<ol>
<li>Not properly un-registering <a href="http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx" rel="nofollow noreferrer">Event Handlers/Delegates</a>.</li>
<li>Not disposing dynamic child controls in Windows Forms:</li>
</ol>
<p>Example:</p>
<pre><code>// Causes Leaks
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
// Correct Code
Label label = new Label();
this.Controls.Add(label);
this.Controls.Remove(label);
label.Dispose();
</code></pre>
<p><strong>Update</strong>: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.</p>
<hr>
<p>Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.</p>
<p>In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).</p>
<p><strong>So, what are the various possible ways in which such a memory leak can happen?</strong></p>
|
[
{
"answer_id": 20431,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": false,
"text": "// slows GC\nLabel label = new Label(); \nthis.Controls.Add(label); \nthis.Controls.Remove(label); \n\n// better \nLabel label = new Label(); \nthis.Controls.Add(label); \nthis.Controls.Remove(label); \nlabel.Dispose();\n\n// best\nusing( Label label = new Label() )\n{ \n this.Controls.Add(label); \n this.Controls.Remove(label); \n}\n"
},
{
"answer_id": 3121231,
"author": "Niki",
"author_id": 70915,
"author_profile": "https://Stackoverflow.com/users/70915",
"pm_score": 1,
"selected": false,
"text": "Region oldClip = graphics.Clip;\nusing (Region newClip = new Region(...))\n{\n graphics.Clip = newClip;\n // draw something\n graphics.Clip = oldClip;\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/380/"
] |
20,391
|
<p>I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share?</p>
<p>I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.</p>
|
[
{
"answer_id": 20453,
"author": "jonezy",
"author_id": 2272,
"author_profile": "https://Stackoverflow.com/users/2272",
"pm_score": 3,
"selected": true,
"text": "svnadmin hotcopy m:\\Source\\Q4Press\\Repo m:\\SvnOut\\Q4Press\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1946/"
] |
20,392
|
<p>We've been trying to alter a lot of columns from nullable to not nullable, which involves dropping all the associated objects, making the change, and recreating the associated objects.</p>
<p>We've been using SQL Compare to generate the scripts, but I noticed that SQL Compare doesn't script statistic objects. Does this mean its ok to drop them and the database will work as well as it did before without them, or have Red Gate missed a trick?</p>
|
[
{
"answer_id": 20417,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "sp_updatestats"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2086/"
] |
20,420
|
<p>I'm a complete Xcode/Objective-C/Cocoa newbie but I'm learning fast and really starting to enjoy getting to grips with a new language, platform and paradigm.</p>
<p>One thing is though, having been using Visual Studio with R# for so long I've kind of been spoiled with the coding tools such as refactorings and completion etc and as far as I can tell Xcode has some fairly limited built in support for this stuff.</p>
<p>On that note, does anyone know if any add-ins or whatever are available for the Xcode environment which add coding helpers such as automatically generating implementation skeletons from a class interface definition etc? </p>
<p>I suspect there aren't but I suppose it can't help to ask.</p>
|
[
{
"answer_id": 21019,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "mogenerator"
},
{
"answer_id": 21106,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 6,
"selected": true,
"text": "NSTextView"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1120/"
] |
20,426
|
<p>I have a tree encoded in a MySQL database as edges:</p>
<pre><code>CREATE TABLE items (
num INT,
tot INT,
PRIMARY KEY (num)
);
CREATE TABLE tree (
orig INT,
term INT
FOREIGN KEY (orig,term) REFERENCES items (num,num)
)
</code></pre>
<p>For each leaf in the tree, <code>items.tot</code> is set by someone. For interior nodes, <code>items.tot</code> needs to be the sum of it's children. Running the following query repeatedly would generate the desired result.</p>
<pre><code>UPDATE items SET tot = (
SELECT SUM(b.tot) FROM
tree JOIN items AS b
ON tree.term = b.num
WHERE tree.orig=items.num)
WHERE EXISTS
(SELECT * FROM tree WHERE orig=items.num)
</code></pre>
<p>(note this actually doesn't work but that's beside the point)</p>
<p>Assume that the database exists and the invariant are already satisfied. </p>
<p>The question is:</p>
<blockquote>
<p><strong>What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of <code>tot</code> on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree.</strong></p>
</blockquote>
<p>Some thoughts I have had:</p>
<ul>
<li>Full Invalidation, after any update, recompute everything (Um... No)</li>
<li>Set a trigger on the items table to update the parent of any row that is updated
<ul>
<li>This would be recursive (updates trigger updates, trigger updates, ...)</li>
<li>Doesn't work, MySQL can't update the table that kicked off the trigger</li>
</ul></li>
<li>Set a trigger to schedule an update of the parent of any row that is updated
<ul>
<li>This would be iterative (get an item from the schedule, processing it schedules more items)</li>
<li>What kicks this off? Trust client code to get it right?</li>
<li>An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own.</li>
</ul></li>
</ul>
<p>An ideal solution would generalize to other "aggregating invariants"</p>
<p>FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it. :-)</p>
|
[
{
"answer_id": 21019,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 3,
"selected": false,
"text": "mogenerator"
},
{
"answer_id": 21106,
"author": "Benjamin Pollack",
"author_id": 2354,
"author_profile": "https://Stackoverflow.com/users/2354",
"pm_score": 6,
"selected": true,
"text": "NSTextView"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
20,450
|
<p>I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.</p>
<p>The command used to paste into Word will be something like:
oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)</p>
<pre><code>{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}}
{\colortbl ;\red255\green255\blue140;}
\viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par
</code></pre>
<p>Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.</p>
|
[
{
"answer_id": 20708,
"author": "Martin",
"author_id": 770,
"author_profile": "https://Stackoverflow.com/users/770",
"pm_score": 3,
"selected": false,
"text": "Dim unformatedtext As String\n\nsomeRTFtext = Replace(someRTFtext, \"\\ul\", \"[ul]\")\nsomeRTFtext = Replace(someRTFtext, \"\\b\", \"[b]\")\nsomeRTFtext = Replace(someRTFtext, \"\\i\", \"[i]\")\n\nDim RTFConvert As RichTextBox = New RichTextBox\nRTFConvert.Rtf = someRTFtext\nunformatedtext = RTFConvert.Text\n\nunformatedtext = Replace(unformatedtext, \"[ul]\", \"\\ul\")\nunformatedtext = Replace(unformatedtext, \"[b]\", \"\\b\")\nunformatedtext = Replace(unformatedtext, \"[i]\", \"\\i\")\n\nClipboard.SetText(unformatedtext)\n\noWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0)\n"
},
{
"answer_id": 10941969,
"author": "Toby Holland",
"author_id": 1367075,
"author_profile": "https://Stackoverflow.com/users/1367075",
"pm_score": 1,
"selected": false,
"text": "string unformatted = Regex.Replace(rtfString, @\"\\{\\*?\\\\[^{}]+}|[{}]|\\\\\\n?[A-Za-z]+\\n?(?:-?\\d+)?[ ]?\", \"\");\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1508/"
] |
20,463
|
<p><a href="http://php.net/Interfaces" rel="noreferrer">Interfaces</a> allow you to create code which defines the methods of classes that implement it. You cannot however add any code to those methods. </p>
<p><a href="http://php.net/Abstract" rel="noreferrer">Abstract classes</a> allow you to do the same thing, along with adding code to the method. </p>
<p>Now if you can achieve the same goal with abstract classes, why do we even need the concept of interfaces? </p>
<p>I've been told that it has to do with OO theory from C++ to Java, which is what PHP's OO stuff is based on. Is the concept useful in Java but not in PHP? Is it just a way to keep from having placeholders littered in the abstract class? Am I missing something?</p>
|
[
{
"answer_id": 20500,
"author": "Tim Frey",
"author_id": 1471,
"author_profile": "https://Stackoverflow.com/users/1471",
"pm_score": 3,
"selected": false,
"text": "interface Readable {\n String read();\n}\n\nList<Readable> readables; // dunno what these actually are, but we know they have read();\nfor(Readable reader : readables)\n System.out.println(reader.read());\n"
},
{
"answer_id": 14778904,
"author": "catalin.costache",
"author_id": 275944,
"author_profile": "https://Stackoverflow.com/users/275944",
"pm_score": 4,
"selected": false,
"text": "$object instanceof MyInterface"
},
{
"answer_id": 24436493,
"author": "Jo Smo",
"author_id": 1286942,
"author_profile": "https://Stackoverflow.com/users/1286942",
"pm_score": 6,
"selected": false,
"text": "AccelerationPedalIsOnTheRight()"
},
{
"answer_id": 31732368,
"author": "Houghtelin",
"author_id": 2625390,
"author_profile": "https://Stackoverflow.com/users/2625390",
"pm_score": 4,
"selected": false,
"text": "<?php\n\ninterface ImportableFeed \n{\n public function getEvents();\n}\n"
},
{
"answer_id": 41606650,
"author": "vivek s vamja",
"author_id": 2459995,
"author_profile": "https://Stackoverflow.com/users/2459995",
"pm_score": 2,
"selected": false,
"text": "interface test{\n public function A($i);\n public function B($j = 20);\n}\n\nclass xyz implements test{\n public function A($a){\n echo \"CLASS A Value is \".$a;\n }\n public function B($b){\n echo \"CLASS B Value is \".$b;\n }\n}\n$x = new xyz();\necho $x->A(11);\necho \"<br/>\";\necho $x->B(10);\n"
},
{
"answer_id": 48825610,
"author": "Hiren Gohel",
"author_id": 6000629,
"author_profile": "https://Stackoverflow.com/users/6000629",
"pm_score": 2,
"selected": false,
"text": " interface abstract class\nthe code - abstract methods - abstract methods\n - constants - constants \n - concrete methods\n - concrete variables\n\naccess modifiers \n - public - public\n - protected\n - private\n etc.\nnumber of parents The same class can implement\n more than 1 interface The child class can \n inherit only from 1 abstract class\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
20,467
|
<p>Are there any automatic methods for trimming a path string in .NET?</p>
<p>For example:</p>
<pre><code>C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx
</code></pre>
<p>becomes</p>
<pre><code>C:\Documents...\demo data.emx
</code></pre>
<p>It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!</p>
|
[
{
"answer_id": 20492,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "c:\\Documents and Settings\\nick\\My Doc...\n"
},
{
"answer_id": 20494,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": " public static string TrimPath(string path)\n {\n int someArbitaryNumber = 10;\n string directory = Path.GetDirectoryName(path);\n string fileName = Path.GetFileName(path);\n if (directory.Length > someArbitaryNumber)\n {\n return String.Format(@\"{0}...\\{1}\", \n directory.Substring(0, someArbitaryNumber), fileName);\n }\n else\n {\n return path;\n }\n }\n"
},
{
"answer_id": 20495,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 4,
"selected": true,
"text": "void label_Paint(object sender, PaintEventArgs e)\n{\n Label label = (Label)sender;\n TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis);\n}\n"
},
{
"answer_id": 20592,
"author": "Nick",
"author_id": 1490,
"author_profile": "https://Stackoverflow.com/users/1490",
"pm_score": 2,
"selected": false,
"text": " Label label = (Label)sender;\n using (SolidBrush b = new SolidBrush(label.BackColor))\n e.Graphics.FillRectangle(b, label.ClientRectangle);\n TextRenderer.DrawText(\n e.Graphics, \n label.Text, \n label.Font, \n label.ClientRectangle, \n label.ForeColor, \n TextFormatFlags.PathEllipsis);\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] |
20,484
|
<p>Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain.</p>
<p>I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
WHERE Description LIKE '%warrior%'
OR
Description LIKE '%fiend%'
OR
Description LIKE '%damage%'
</code></pre>
<p>But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId
</code></pre>
<p>I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this:</p>
<pre><code>SELECT Id, Name, Description
FROM dbo.Card
INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%'
</code></pre>
<p>Is this possible/recommended?</p>
<p>Is there a better way to do something like this?</p>
<hr>
<p>The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts.</p>
<p>I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? </p>
<p>Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?</p>
|
[
{
"answer_id": 20599,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 1,
"selected": false,
"text": "create table name(\n nameID identity / int\n ,name varchar(50))\n\ncreate table description(\n descID identity / int\n ,desc varchar(50)) --something reasonable and to make the most of it alwase lower case your values\n\ncreate table nameDescJunc(\n nameID int\n ,descID int)\n"
},
{
"answer_id": 891792,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT Id, Name, Description\nFROM dbo.Card\nINNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + \n CONCAT(CONCAT('%',@tblKeyword.Value),'%') + '%'\n"
},
{
"answer_id": 14590796,
"author": "John",
"author_id": 1223661,
"author_profile": "https://Stackoverflow.com/users/1223661",
"pm_score": 3,
"selected": false,
"text": " select * from Table_1 a\n left join Table_2 b on b.type LIKE '%' + a.type + '%'\n"
},
{
"answer_id": 30483791,
"author": "Manoj",
"author_id": 4944899,
"author_profile": "https://Stackoverflow.com/users/4944899",
"pm_score": 2,
"selected": false,
"text": "select * from table11 a inner join table2 b on b.id like (select '%'+a.id+'%') where a.city='abc'.\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
20,510
|
<p>I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)</p>
<p>I am currently doing this by exposing the following JavaScript method:</p>
<pre><code>function doScript(js){ eval(js);}
</code></pre>
<p>I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):</p>
<pre><code>ExternalInterface.call("doScript","alert('foo'));
</code></pre>
<p>My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...</p>
<p>Is there a better way to do this?</p>
|
[
{
"answer_id": 20645,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 4,
"selected": true,
"text": "ExternalInterface"
},
{
"answer_id": 40553258,
"author": "user2629253",
"author_id": 2629253,
"author_profile": "https://Stackoverflow.com/users/2629253",
"pm_score": -1,
"selected": false,
"text": "ExternalInterface.call(\"eval\", \"alert('hello');\");\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
20,529
|
<p>I have been using Eclipse as an IDE for a short amount of time (about 3 months of full use) and almost every day I learn about some shortcut or feature that I had absolutely no idea about. For instance, just today I learned that <kbd>Ctrl</kbd>+<kbd>3</kbd> was the shortcut for a Quick Access window.</p>
<p>I was wondering what your most useful/favorite Eclipse features are. With the IDE being so big, it would be helpful to learn about the more commonly used parts of the program.</p>
|
[
{
"answer_id": 19623660,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 1,
"selected": false,
"text": "java.lang.Object"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2329/"
] |
20,586
|
<p>I'm trying to bind a list of custom objects to a WPF Image like this:</p>
<pre><code><Image>
<Image.Source>
<BitmapImage UriSource="{Binding Path=ImagePath}" />
</Image.Source>
</Image>
</code></pre>
<p>But it doesn't work. This is the error I'm getting:</p>
<p><em>"Property 'UriSource' or property 'StreamSource' must be set."</em></p>
<p>What am I missing?</p>
|
[
{
"answer_id": 20617,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 3,
"selected": false,
"text": "BitmapImage image = new BitmapImage();\nimage.BeginInit();\nimage.UriSource = new Uri(value as string);\nimage.EndInit();\n\nreturn image;\n"
},
{
"answer_id": 20648,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 4,
"selected": false,
"text": "<Image Width=\"90\" Height=\"90\" \n Source=\"{Binding Path=ImageSource}\"\n Margin=\"0,0,0,5\" />\n"
},
{
"answer_id": 20737,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 7,
"selected": true,
"text": "Source"
},
{
"answer_id": 19480862,
"author": "Karthik Krishna Baiju",
"author_id": 2608383,
"author_profile": "https://Stackoverflow.com/users/2608383",
"pm_score": 3,
"selected": false,
"text": " img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString(\"/Assets/check.png\");\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373/"
] |
20,587
|
<p>I want to get the results of a stored procedure and place them into a CSV file onto an FTP location.</p>
<p>The catch though is that I cannot create a local/temporary file that I can then FTP over.</p>
<p>The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers.</p>
<h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596">in reply to Yaakov Ellis</a></h2>
<p>I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it.</p>
<h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689">in reply to Kev</a></h2>
<p>I like the idea of the CLR integration, but I don't think our DBA's even know what that is <em>lol</em> and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled.</p>
|
[
{
"answer_id": 20689,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 3,
"selected": false,
"text": "public static void DoQueryAndUploadFile(string uri, string username, string password, string filename)\n{\n FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(uri + \"/\" + filename);\n ftp.Method = WebRequestMethods.Ftp.UploadFile;\n ftp.Credentials = new System.Net.NetworkCredential(username, password);\n\n using(StreamWriter sw = new StreamWriter(ftp.GetRequestStream()))\n {\n // Do the query here then write to the ftp stream by iterating DataReader or other resultset, following code is just to demo concept:\n for (int i = 0; i < 100; i++)\n {\n sw.WriteLine(\"{0},row-{1},data-{2}\", i, i, i);\n }\n sw.Flush();\n }\n}\n"
},
{
"answer_id": 6800413,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "@Kev"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1950/"
] |
20,598
|
<p>I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?</p>
|
[
{
"answer_id": 20605,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "date('Y-m-d', $timestamp);\n"
},
{
"answer_id": 20668,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 0,
"selected": false,
"text": "YYYY-MM-DD\n"
},
{
"answer_id": 30471,
"author": "jonthornton",
"author_id": 3250,
"author_profile": "https://Stackoverflow.com/users/3250",
"pm_score": 2,
"selected": false,
"text": "strtotime()"
},
{
"answer_id": 635809,
"author": "St. John Johnson",
"author_id": 76734,
"author_profile": "https://Stackoverflow.com/users/76734",
"pm_score": 2,
"selected": false,
"text": "/**\n * Convert MySQL datetime to PHP time\n */\nfunction convert_datetime($datetime) {\n //example: 2008-02-07 12:19:32\n $values = split(\" \", $datetime);\n\n $dates = split(\"-\", $values[0]);\n $times = split(\":\", $values[1]);\n\n $newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);\n\n return $newdate;\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
20,611
|
<p>The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:</p>
<p><strong>The node to be removed is not a child of this node.</strong></p>
<p>Does anyone know the proper way to do this?</p>
<pre><code>public void DeleteProject (string projectName)
{
string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"];
XmlDocument configDoc = new XmlDocument();
configDoc.Load(ccConfigPath);
XmlNodeList projectNodes = configDoc.GetElementsByTagName("project");
for (int i = 0; i < projectNodes.Count; i++)
{
if (projectNodes[i].Attributes["name"] != null)
{
if (projectName == projectNodes[i].Attributes["name"].InnerText)
{
configDoc.RemoveChild(projectNodes[i]);
configDoc.Save(ccConfigPath);
}
}
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>Fixed. I did two things:</p>
<pre><code>XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']");
</code></pre>
<p>Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.</p>
<p>The actual fix was:</p>
<pre><code>project.ParentNode.RemoveChild(project);
</code></pre>
<p>Thanks Pat and Chuck for this suggestion.</p>
|
[
{
"answer_id": 20624,
"author": "David Hayes",
"author_id": 1769,
"author_profile": "https://Stackoverflow.com/users/1769",
"pm_score": 0,
"selected": false,
"text": "<Root>\n <Blah>\n <project>...</project>\n </Blah>\n</Root>\n"
},
{
"answer_id": 20625,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "configDoc.RemoveChild(projectNodes[i]);\n"
},
{
"answer_id": 20629,
"author": "Jason",
"author_id": 1338,
"author_profile": "https://Stackoverflow.com/users/1338",
"pm_score": 2,
"selected": false,
"text": "configDoc.DocumentElement.RemoveChild(projectNodes[i]);\n"
},
{
"answer_id": 11116820,
"author": "Eugene Ryabtsev",
"author_id": 1353187,
"author_profile": "https://Stackoverflow.com/users/1353187",
"pm_score": 1,
"selected": false,
"text": "public static class Extensions {\n ...\n public static XmlNode RemoveFromParent(this XmlNode node) {\n return (node == null) ? null : node.ParentNode.RemoveChild(node);\n }\n}\n...\n//some_long_node_expression.parentNode.RemoveChild(some_long_node_expression);\nsome_long_node_expression.RemoveFromParent();\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
20,627
|
<p>I've seen this all over the place: </p>
<blockquote>
<p>Download here! SHA1 =
8e1ed2ce9e7e473d38a9dc7824a384a9ac34d7d0</p>
</blockquote>
<p>What does it mean? How does a hash come into play as far as downloads and... What use can I make of it? Is this a legacy item where you used to have to verify some checksum after you downloaded the whole file?</p>
|
[
{
"answer_id": 20654,
"author": "jl23x",
"author_id": 2143,
"author_profile": "https://Stackoverflow.com/users/2143",
"pm_score": 0,
"selected": false,
"text": "If (hash(file) == “Hash in page”)\n validFile = true;\nelse\n validFile = false;\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] |
20,658
|
<p>How, in general, does one determine if a PC supports hardware virtualization? I use VirtualPC to set up parallel test environments and I'd enjoy a bit of a speed boost.</p>
|
[
{
"answer_id": 20700,
"author": "jmanning2k",
"author_id": 1480,
"author_profile": "https://Stackoverflow.com/users/1480",
"pm_score": 1,
"selected": false,
"text": "cat /proc/cpuinfo"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1490/"
] |
20,674
|
<p>Other than <code>self.class.send :method, args...</code>, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.</p>
<hr>
<p><strong>UPDATE:</strong> </p>
<p>@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that <code>private</code> doesn't work on class methods, though this will declare a private class method:</p>
<pre><code>class Foo
class <<self
private
def bar
puts 'bar'
end
end
end
Foo.bar
# => NoMethodError: private method 'bar' called for Foo:Class
</code></pre>
|
[
{
"answer_id": 20690,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": -1,
"selected": false,
"text": "class Foo\n private\n def Foo.bar\n # Complex logic goes here\n puts \"hi\"\n end\n\n public\n def bar\n Foo.bar\n end\nend\n"
},
{
"answer_id": 20746,
"author": "Jonathan Branam",
"author_id": 2347,
"author_profile": "https://Stackoverflow.com/users/2347",
"pm_score": 5,
"selected": true,
"text": "class Foo\n def self.private_bar\n # Complex logic goes here\n puts \"hi\"\n end\n private_class_method :private_bar\n class <<self\n private\n def another_private_bar\n puts \"bar\"\n end\n end\n public\n def instance_bar\n self.class.private_bar\n end\n def instance_bar2\n self.class.another_private_bar\n end\nend\n\nf=Foo.new\nf=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class\nf=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class\n"
},
{
"answer_id": 8543280,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 0,
"selected": false,
"text": "include"
},
{
"answer_id": 11322794,
"author": "magicgregz",
"author_id": 1169468,
"author_profile": "https://Stackoverflow.com/users/1169468",
"pm_score": 0,
"selected": false,
"text": "class Foo\n def self.private_bar\n # Complex logic goes here\n puts \"hi\"\n end\n private_class_method :private_bar\n class <<self\n private\n def another_private_bar\n puts \"bar\"\n end\n end\n public\n def instance_bar\n self.class.private_bar\n end\n def instance_bar2\n self.class.another_private_bar\n end\n def calling_private_method\n Foo.send :another_private_bar\n self.class.send :private_bar\n end\nend\nf=Foo.new\nf.send :calling_private_method \n # \"bar\"\n # \"hi\"\nFoo.send :another_private_bar\n# \"bar\"\n"
},
{
"answer_id": 24224054,
"author": "Alexey",
"author_id": 898649,
"author_profile": "https://Stackoverflow.com/users/898649",
"pm_score": 3,
"selected": false,
"text": "puts RUBY_VERSION # => 2.1.2\n\nclass C\n class << self\n private def foo\n 'Je suis foo'\n end\n end\n\n private define_method :foo, &method(:foo)\n\n def bar\n foo\n end\nend\n\nputs C.new.bar # => Je suis foo\nputs C.new.foo # => NoMethodError\n"
},
{
"answer_id": 35921805,
"author": "Michael Krupp",
"author_id": 1986344,
"author_profile": "https://Stackoverflow.com/users/1986344",
"pm_score": 2,
"selected": false,
"text": "class MyClass\n\n private_class_method def self.my_private_method\n puts \"private class method\"\n end\n\n private def my_private_method\n puts \"private instance method\"\n end\n\nend\n"
},
{
"answer_id": 55486235,
"author": "Kache",
"author_id": 234593,
"author_profile": "https://Stackoverflow.com/users/234593",
"pm_score": 0,
"selected": false,
"text": "class Foo\n module PrivateStatic # like Java\n private def foo\n 'foo'\n end\n end\n extend PrivateStatic\n include PrivateStatic\n\n def self.static_public_call\n \"static public #{foo}\"\n end\n\n def public_call\n \"instance public #{foo}\"\n end\nend\n\nFoo.static_public_call # 'static public foo'\nFoo.new.public_call # 'instance public foo'\nFoo.foo # NoMethodError: private method `foo' called for Foo:Class\nFoo.new.foo # NoMethodError: private method `foo' called for #<Foo:0x00007fa154d13f10>\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
20,675
|
<p>What is the difference in ASP/VBScript between <code>Int()</code> and <code>CInt()</code>?</p>
|
[
{
"answer_id": 360003,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "wscript.echo 40.91 * 100\nwscript.echo Int(40.91 * 100)\nwscript.echo CInt(40.91 * 100)\n"
},
{
"answer_id": 4404489,
"author": "Steven K. Mariner",
"author_id": 537223,
"author_profile": "https://Stackoverflow.com/users/537223",
"pm_score": 3,
"selected": false,
"text": "a = int(40.91 * 100)\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/357/"
] |
20,684
|
<p>I've been using Linq to SQL for some time now and I find it to be really helpful and easy to use. With other ORM tools I've used in the past, the entity object filled from the database normally has a property indicating the length of the underlying data column in the database. This is helpful in databinding situations where you can set the MaxLength property on a textbox, for example, to limit the length of input entered by the user.</p>
<p>I cannot find a way using Linq to SQL to obtain the length of an underlying data column. Does anyone know of a way to do this? Help please.</p>
|
[
{
"answer_id": 1397564,
"author": "Paul Alexander",
"author_id": 76456,
"author_profile": "https://Stackoverflow.com/users/76456",
"pm_score": 1,
"selected": false,
"text": "var context = new DataContextFromSomewhere();\nvar connection = context.Connection;\nvar command = connection.CreateCommand( \"SELECT TOP 1 * FROM TableImInterestedIn\" );\nvar reader = command.ExecuteReader();\nvar table = reader.GetSchemaTable();\n\nforeach( var column in table.Columns )\n{\n Console.WriteLine( \"Length: {0}\", column.MaxLength );\n\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689/"
] |
20,696
|
<p>In E (specman) I want to declare variables that are lists, and I want to fix their lengths.</p>
<p>It's easy to do for a member of a struct:</p>
<pre><code>thread[2] : list of thread_t;
</code></pre>
<p>while for a "regular" variable in a function the above doesn't work, and I have to do something like:</p>
<pre><code>var warned : list of bool;
gen warned keeping {
it.size() == 5;
};
</code></pre>
<p>Is there a better way to declare a list of fixed size?</p>
|
[
{
"answer_id": 37438,
"author": "JawnV6",
"author_id": 3869,
"author_profile": "https://Stackoverflow.com/users/3869",
"pm_score": 3,
"selected": true,
"text": "event list_size_changed is true (wanted.size() != 5) @clk;\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
20,718
|
<p>I want to test the behavior of a certain piece of .NET code in partial trust environments. What's the fastest way to set this up? Feel free to assume that I (and other readers) are total CAS noobs.</p>
<p>@Nick: Thanks for the reply. Alas, the tool in question is explicitly for unmanaged code. I didn't say "managed" in my question, and should not have assumed that people would infer it from the ".NET" tag.</p>
|
[
{
"answer_id": 12189044,
"author": "bricelam",
"author_id": 475031,
"author_profile": "https://Stackoverflow.com/users/475031",
"pm_score": 1,
"selected": false,
"text": "public class SomeTests : MarshalByRefObject\n{\n [PartialTrustFact]\n public void Partial_trust_test1()\n {\n // Runs in medium trust\n }\n}\n\n// Or...\n\n[PartialTrustFixture]\npublic class MoreTests : MarshalByRefObject\n{\n [Fact]\n public void Another_partial_trust_test()\n {\n // Runs in medium trust\n }\n}\n"
}
] |
2008/08/21
|
[
"https://Stackoverflow.com/questions/20718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/533/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.