qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
167,502
<p>This is the page that I'm having. But the resize part in the section does not seem to be working. I copied most of the code from the <a href="http://www.asp.net/ajax/ajaxcontroltoolkit/samples/UpdatePanelAnimation/UpdatePanelAnimation.aspx" rel="nofollow noreferrer">Ajax site</a>. I placed a alert() in the tag (line 108) to find the value of 'b._originalHeight' and it shows up as '44'. I have also tried the code in the above-said tutorial (line 132) and that did not work either. (I'm not sure where it is getting this value from. But I need it to show all the controls on the form.</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeBehind="AddEditContest.ascx.cs" Inherits="TMPInternational.Spawn2DotComAdmin.Contest.UserControls.AddEditContest" %&gt; &lt;%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="uc" %&gt; &lt;%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %&gt; &lt;%@ Register TagPrefix="ew" Assembly="eWorld.UI, Version=1.9.0.0, Culture=neutral, PublicKeyToken=24d65337282035f2" Namespace="eWorld.UI" %&gt; &lt;h1 style="margin-left:8px"&gt;Add/Edit Contest&lt;/h1&gt; &lt;asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" /&gt; &lt;div style="text-align:left;width:500px; margin-left:8px"&gt; &lt;div id="PanelContainer"&gt; &lt;asp:UpdatePanel ID="AddEditContestUpdatePanel" runat="server" UpdateMode="Always"&gt; &lt;ContentTemplate&gt; &lt;div id="background" style="text-align:left; height: 44px;"&gt; &lt;asp:Panel ID="ContestList" runat="server"&gt; &lt;asp:datagrid AllowSorting="false" id="ContestGrid" GridLines="None" CellPadding="5" Width="100%" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#cccccc" HeaderStyle-Font-Size="15px" HeaderStyle-Font-Bold="true" HeaderStyle-BackColor="#888f9b" Runat="server" AllowPaging="True" PageSize="10" PagerStyle-NextPageText="Next &gt;&gt;" PagerStyle-PrevPageText="&lt;&lt; Back" &gt; &lt;Columns&gt; &lt;asp:HyperLinkColumn DataNavigateUrlField="ContestID" DataNavigateUrlFormatString="../?Load=AddEditContest&amp;Type=Edit&amp;ContestID={0}" DataTextField="Title" ItemStyle-width="30%" headertext="Contest Title" /&gt; &lt;asp:BoundColumn DataField="StartDate" ItemStyle-Width="35%" HeaderText="Start Date" /&gt; &lt;asp:BoundColumn DataField="EndDate" ItemStyle-Width="35%" HeaderText="End Date" /&gt; &lt;/Columns&gt; &lt;/asp:datagrid&gt; &lt;div style="text-align:right;"&gt; &lt;asp:ImageButton ID="AddContest" runat="server" ImageUrl="~/Contest/Images/Add.png" AlternateText="Add Contest" onclick="AddContest_Click" /&gt; &lt;/div&gt; &lt;/asp:Panel&gt; &lt;asp:Panel ID="FieldsPanel" runat="server"&gt; &lt;p /&gt;&lt;b&gt;Title&lt;/b&gt; &lt;br /&gt; &lt;asp:TextBox Runat="server" id="TitleText" /&gt; &lt;asp:RequiredFieldValidator id="TitleValidator" runat="server" ForeColor="Red" ErrorMessage="Please add a title" ControlToValidate="TitleText"&gt;*&lt;/asp:RequiredFieldValidator&gt; &lt;p /&gt;&lt;b&gt;Contest Description&lt;/b&gt; &lt;br /&gt; Use HTML tags to format this area. Start paragraphs with &amp;lt;p /&amp;gt; tag, bold items with &amp;lt;b&amp;gt;&amp;lt;/b&amp;gt; tags. Create a line-break between lines with one &amp;lt;br /&amp;gt; tag.&lt;br /&gt; &lt;asp:TextBox Runat="server" ID="DescriptionText" TextMode="MultiLine" Width="400" Height="200" /&gt; &lt;asp:RequiredFieldValidator id="DescriptionValidator" runat="server" ErrorMessage="Please add a description" ControlToValidate="DescriptionText" ForeColor="Red"&gt;*&lt;/asp:RequiredFieldValidator&gt; &lt;p /&gt; &lt;b&gt;Contest Start Date&lt;/b&gt; &lt;br /&gt; &lt;ew:CalendarPopup id="StartDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"&gt; &lt;WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /&gt; &lt;MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /&gt; &lt;OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /&gt; &lt;GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/&gt; &lt;TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /&gt; &lt;DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /&gt; &lt;WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /&gt; &lt;SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/&gt; &lt;HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /&gt; &lt;/ew:CalendarPopup&gt; &amp;nbsp; &lt;ew:TimePicker id="StartTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"&gt; &lt;TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /&gt; &lt;SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /&gt; &lt;/ew:TimePicker&gt; &lt;p/&gt;&lt;b&gt;Contest End Date&lt;/b&gt; &lt;br /&gt; &lt;ew:CalendarPopup id="EndDate" runat="server" Text="Change Date" Width="75px" MonthYearArrowImageUrl="~/Images/monthchange.gif" CalendarLocation="Left" ControlDisplay="TextBoxImage" ImageUrl="~/Images/calendar.gif" MonthYearPopupApplyText="Select" CalendarWidth="150" UseExternalResource="True" ExternalResourcePath="~/Scripts/CalendarPopup.js" Nullable="False"&gt; &lt;WeekdayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" Font-Size="9pt" /&gt; &lt;MonthHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="White" BackColor="#669AC1" /&gt; &lt;OffMonthStyle ForeColor="Gray" BackColor="White" Font-Size="9pt" /&gt; &lt;GoToTodayStyle Font-Names="Arial" ForeColor="Black" BackColor="White"/&gt; &lt;TodayDayStyle Font-Bold="True" ForeColor="#669AC1" BackColor="White" /&gt; &lt;DayHeaderStyle Font-Size="9pt" Font-Names="Arial" Font-Bold="True" ForeColor="Blue" BackColor="White" /&gt; &lt;WeekendStyle Font-Names="Arial" ForeColor="Blue" BackColor="LightGray" Font-Size="9pt" /&gt; &lt;SelectedDateStyle Font-Bold="True" ForeColor="White" BackColor="#669AC1" Font-Size="9pt"/&gt; &lt;HolidayStyle Font-Names="Arial" ForeColor="Black" BackColor="White" /&gt; &lt;/ew:CalendarPopup&gt; &amp;nbsp; &lt;ew:TimePicker id="EndTime" runat="server" ControlDisplay="TextboxImage" Text="Change Time" ImageUrl="~/Images/clock.gif" NumberOfColumns="4" Scrollable="True" Width="75px"&gt; &lt;TimeStyle ForeColor="Blue" BackColor="White" Font-Size="9pt" /&gt; &lt;SelectedTimeStyle ForeColor="Blue" BackColor="Gray" /&gt; &lt;/ew:TimePicker&gt; &lt;p /&gt; &lt;asp:ImageButton ID="SaveContestButton" runat="server" AlternateText="Confirm" ImageUrl="~/Contest/Images/Confirm.png" onclick="SaveContestButton_Click" /&gt; &lt;/asp:Panel&gt; &lt;br /&gt; &lt;asp:Label ID="MessageLabel" runat="server" /&gt; &lt;/div&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="SaveContestButton" EventName="Click" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; &lt;/div&gt; &lt;uc:UpdatePanelAnimationExtender ID="upae" BehaviorID="animation" runat="server" TargetControlID="AddEditContestUpdatePanel"&gt; &lt;Animations&gt; &lt;OnUpdating&gt; &lt;Sequence&gt; &lt;%-- Store the original height of the panel --%&gt; &lt;ScriptAction Script="var b = $find('animation'); b._originalHeight = b._element.offsetHeight;" /&gt; &lt;%-- Disable all the controls --%&gt; &lt;Parallel duration="0"&gt; &lt;EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="false" /&gt; &lt;/Parallel&gt; &lt;StyleAction Attribute="overflow" Value="hidden" /&gt; &lt;%-- Do each of the selected effects --%&gt; &lt;Parallel duration=".25" Fps="30"&gt; &lt;FadeOut AnimationTarget="PanelContainer" minimumOpacity=".2" /&gt; &lt;Resize Height="0px" /&gt; &lt;/Parallel&gt; &lt;/Sequence&gt; &lt;/OnUpdating&gt; &lt;OnUpdated&gt; &lt;Sequence&gt; &lt;%-- Do each of the selected effects --%&gt; &lt;Parallel duration=".25" Fps="30"&gt; &lt;FadeIn AnimationTarget="PanelContainer" minimumOpacity=".2" /&gt; &lt;Length duration="2" fps="40" Property="style" PropertyKey="height" StartValue="10" EndValueScript="$get('animation').offsetHeight" AnimationTarget="animation" /&gt; &lt;%--Also tried the below &lt;Resize HeightScript="$find('animation')._originalHeight" /&gt; --%&gt; &lt;/Parallel&gt; &lt;%-- Enable all the controls --%&gt; &lt;Parallel duration="0"&gt; &lt;EnableAction AnimationTarget="SaveDefaultDescriptionButton" Enabled="true" /&gt; &lt;/Parallel&gt; &lt;/Sequence&gt; &lt;/OnUpdated&gt; &lt;/Animations&gt; &lt;/uc:UpdatePanelAnimationExtender&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 167501, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 5, "selected": false, "text": "DECLARE @MyDate datetime\n\n-- ... set your datetime's initial value ...'\n\nDATEADD(d, 1, @MyDate)\n" }, { "answer_id": 167507, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 2, "selected": false, "text": "DECLARE @date DateTime\nSET @date = GetDate()\nSET @date = DateAdd(day, 1, @date)\n\nSELECT @date\n" }, { "answer_id": 167539, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 7, "selected": false, "text": "DATEADD(type, value, date)\n SELECT DATEADD(dd, 1, GETDATE()) -- will return a current date + 1 day\n" }, { "answer_id": 2204720, "author": "Lakshmanan From INDIA", "author_id": 266740, "author_profile": "https://Stackoverflow.com/users/266740", "pm_score": 2, "selected": false, "text": "Select getdate() -- 2010-02-05 10:03:44.527\n\n-- To get all date format\nselect CONVERT(VARCHAR(12),getdate(),100) +' '+ 'Date -100- MMM DD YYYY' -- Feb 5 2010\nunion\nselect CONVERT(VARCHAR(10),getdate(),101) +' '+ 'Date -101- MM/DDYYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),102) +' '+ 'Date -102- YYYY.MM.DD'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),103) +' '+ 'Date -103- DD/MM/YYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),104) +' '+ 'Date -104- DD.MM.YYYY'\nUnion\nselect CONVERT(VARCHAR(10),getdate(),105) +' '+ 'Date -105- DD-MM-YYYY'\nUnion\nselect CONVERT(VARCHAR(11),getdate(),106) +' '+ 'Date -106- DD MMM YYYY' --ex: 03 Jan 2007\nUnion\nselect CONVERT(VARCHAR(12),getdate(),107) +' '+ 'Date -107- MMM DD,YYYY' --ex: Jan 03, 2007\nunion\nselect CONVERT(VARCHAR(12),getdate(),109) +' '+ 'Date -108- MMM DD YYYY' -- Feb 5 2010\nunion\nselect CONVERT(VARCHAR(12),getdate(),110) +' '+ 'Date -110- MM-DD-YYYY' --02-05-2010\nunion\nselect CONVERT(VARCHAR(10),getdate(),111) +' '+ 'Date -111- YYYY/MM/DD'\nunion\nselect CONVERT(VARCHAR(12),getdate(),112) +' '+ 'Date -112- YYYYMMDD' -- 20100205\nunion\nselect CONVERT(VARCHAR(12),getdate(),113) +' '+ 'Date -113- DD MMM YYYY' -- 05 Feb 2010\n\n\nSELECT convert(varchar, getdate(), 20) -- 2010-02-05 10:25:14\nSELECT convert(varchar, getdate(), 23) -- 2010-02-05\nSELECT convert(varchar, getdate(), 24) -- 10:24:20\nSELECT convert(varchar, getdate(), 25) -- 2010-02-05 10:24:34.913\nSELECT convert(varchar, getdate(), 21) -- 2010-02-05 10:25:02.990\n\n\n---==================================\n-- To get the time\nselect CONVERT(VARCHAR(12),getdate(),108) +' '+ 'Date -108- HH:MM:SS' -- 10:05:53\n\nselect CONVERT(VARCHAR(12),getdate(),114) +' '+ 'Date -114- HH:MM:SS:MS' -- 10:09:46:223\nSELECT convert(varchar, getdate(), 22) -- 02/05/10 10:23:11 AM\n----=============================================\nSELECT getdate()+1\nSELECT month(getdate())+1\nSELECT year(getdate())+1\n" }, { "answer_id": 19590482, "author": "Dilip Kr Singh", "author_id": 1501276, "author_profile": "https://Stackoverflow.com/users/1501276", "pm_score": 3, "selected": false, "text": "DATEADD(DAY,20,GETDATE())\n" }, { "answer_id": 22148005, "author": "BJ Patel", "author_id": 2683759, "author_profile": "https://Stackoverflow.com/users/2683759", "pm_score": 4, "selected": false, "text": "select DateAdd(day, 1, GetDate())\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2894/" ]
167,509
<p>I have a GridView where one column is bound to an object property containing a nullable integer. I set SortExpression to the name of the property, and sorting works perfectly as long as all rows contain a value. If any rows contain null, however, I get an exception:</p> <p>System.InvalidOperationException : Failed to compare two elements in the array. Object reference not set to an instance of an object.</p> <p>How do I customize the sorting or comparison logic to handle the null case?</p>
[ { "answer_id": 167519, "author": "Seth Petry-Johnson", "author_id": 23632, "author_profile": "https://Stackoverflow.com/users/23632", "pm_score": 3, "selected": true, "text": "gridview.Sorting += new GridViewSortEventHandler(gridView_Sorting);\n\nprotected void gridView_Sorting(object sender, GridViewSortEventArgs e)\n{\n // Only add custom handling for the sort expression on the \n // Nullable<int> column\n if (e.SortExpression == \"MySortExpression\")\n {\n // Convert datasource to a List<T>\n list.Sort(new Comparison<MyObjectType>(delegate(MyObjectType item1, MyObjectType item2)\n {\n return Nullable.Compare<int>(item1.NullableIntProp, item2.NullableIntProp);\n }));\n\n // Bind the sorted list back to the gridview\n }\n else\n {\n // delegate to the gridview to handle its own sorting\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23632/" ]
167,533
<p>We have some raw voice audio that we need to distribute over the internet. We need decent quality, but it doesn't need to be of musical quality. Our main concern is usability by the consumer (i.e. what and where they can play it) and size of the download. My experience has shown that mp3s do not produce the best compression numbers for voice audio, but I am at a loss for what the best alternatives are. Ultimately we would like to automate the conversion process to allow the consumer to choose the quality vs. size level that they would like.</p>
[ { "answer_id": 25394260, "author": "hochl", "author_id": 589206, "author_profile": "https://Stackoverflow.com/users/589206", "pm_score": 3, "selected": false, "text": "ffmpeg -i x.wav -b:a 32k x.opus\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7819/" ]
167,542
<p>I'm trying to create a table with two columns comprising the primary key in MySQL, but I can't figure out the syntax. I understand single-column PKs, but the syntax isn't the same to create a primary key with two columns.</p>
[ { "answer_id": 167553, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": " CREATE TABLE `synthesis`.`INV_MasterItemList` (\n `MasterItemList_ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,\n `Customer_ID` INTEGER UNSIGNED NOT NULL,\n `Model_ID` INTEGER UNSIGNED NOT NULL,\n `Serial` VARCHAR(45) NOT NULL,\n PRIMARY KEY (`MasterItemList_ID`),\n UNIQUE INDEX `INDEX_UNIQUE`(`Customer_ID`, `Model_ID`, `Serial`)\n )\n" }, { "answer_id": 167561, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 4, "selected": true, "text": "CREATE TABLE table_name \n(\n c1 INT NOT NULL,\n c2 INT NOT NULL,\n PRIMARY KEY (c1, c2)\n)\n" }, { "answer_id": 167566, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 2, "selected": false, "text": "create table .....\n\n\nprimary key (`id1`, `id2`)\n)\n" }, { "answer_id": 167568, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 1, "selected": false, "text": "CREATE TABLE categories_description (\n categories_id int DEFAULT '0' NOT NULL,\n language_id int DEFAULT '1' NOT NULL,\n categories_name varchar(32) NOT NULL,\n PRIMARY KEY (categories_id, language_id),\n KEY idx_categories_name (categories_name)\n);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
167,562
<p>How can I know if a device is supported on a running Linux and if so, which device driver controls it? For instance, <code>lspci</code> on a server (PowerEdge 2900) gives:</p> <pre class="lang-none prettyprint-override"><code>00:00.0 Host bridge: Intel Corporation 5000X Chipset Memory Controller Hub (rev 12) 00:02.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 2 (rev 12) 00:03.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 3 (rev 12) 00:04.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 4 (rev 12) 00:05.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 5 (rev 12) 00:06.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x8 Port 6-7 (rev 12) 00:07.0 PCI bridge: Intel Corporation 5000 Series Chipset PCI Express x4 Port 7 (rev 12) 00:08.0 System peripheral: Intel Corporation 5000 Series Chipset DMA Engine (rev 12) 00:10.0 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.1 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:10.2 Host bridge: Intel Corporation 5000 Series Chipset FSB Registers (rev 12) 00:11.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:13.0 Host bridge: Intel Corporation 5000 Series Chipset Reserved Registers (rev 12) 00:15.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:16.0 Host bridge: Intel Corporation 5000 Series Chipset FBD Registers (rev 12) 00:1c.0 PCI bridge: Intel Corporation 631xESB/632xESB/3100 Chipset PCI Express Root Port 1 (rev 09) 00:1d.0 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #1 (rev 09) 00:1d.1 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #2 (rev 09) 00:1d.2 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #3 (rev 09) 00:1d.3 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset UHCI USB Controller #4 (rev 09) 00:1d.7 USB Controller: Intel Corporation 631xESB/632xESB/3100 Chipset EHCI USB2 Controller (rev 09) 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev d9) 00:1f.0 ISA bridge: Intel Corporation 631xESB/632xESB/3100 Chipset LPC Interface Controller (rev 09) 00:1f.1 IDE interface: Intel Corporation 631xESB/632xESB IDE Controller (rev 09) 00:1f.2 IDE interface: Intel Corporation 631xESB/632xESB/3100 Chipset SATA IDE Controller (rev 09) 01:00.0 PCI bridge: Intel Corporation 80333 Segment-A PCI Express-to-PCI Express Bridge 01:00.2 PCI bridge: Intel Corporation 80333 Segment-B PCI Express-to-PCI Express Bridge 02:0e.0 RAID bus controller: Dell PowerEdge Expandable RAID controller 5 04:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 05:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 06:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Upstream Port (rev 01) 06:00.3 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express to PCI-X Bridge (rev 01) 07:00.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E1 (rev 01) 07:01.0 PCI bridge: Intel Corporation 6311ESB/6321ESB PCI Express Downstream Port E2 (rev 01) 08:00.0 PCI bridge: Broadcom EPB PCI-Express to PCI-X Bridge (rev c3) 09:00.0 Ethernet controller: Broadcom Corporation NetXtreme II BCM5708 Gigabit Ethernet (rev 12) 0b:02.0 Multimedia audio controller: Creative Labs SB Audigy (rev 03) 0b:02.1 Input device controller: Creative Labs SB Audigy Game Port (rev 03) 0b:02.2 FireWire (IEEE 1394): Creative Labs SB Audigy FireWire Port 10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02) </code></pre> <p>How can I find:</p> <ol> <li>which device driver (kernel module) controls each device?</li> <li>which device is controlled by a device driver compiled <em>in</em> the kernel (and not as a module)</li> <li>which device doesn't have a device driver (compiled in or as a module)?</li> </ol> <p>This script (adapted from another in "Linux Kernel in a Nutshell") partially resolves #1:</p> <pre class="lang-bash prettyprint-override"><code>#!/bin/bash for i in $(find /sys/ -name modalias); do echo "----------------------------------" modalias=$(cat $i) echo "$(dirname $i) --&gt; $modalias" /sbin/modprobe --config /dev/null --show-depends $(cat $i) 2&gt;&amp;1 done </code></pre> <p>But there are some problems with it:</p> <ol> <li><p>I don't know of an <em>automated way</em> to convert <code>/sys/devices/pci0000:00/0000:00:1e.0/0000:10:0d.0 --&gt; pci:v00001002d0000515Esv00001028sd000001B1bc03sc00i00</code> to <code>10:0d.0 VGA compatible controller: ATI Technologies Inc ES1000 (rev 02)</code></p></li> <li><p>In some cases the devices are internal to the MB and I don't even know a way to find the real name of the device. For example:</p></li> </ol> <pre class="lang-none prettyprint-override"><code>/sys/devices/platform/dcdbas --&gt; platform:dcdbas /sys/devices/platform/iTCO_wdt --&gt; platform:iTCO_wdt /sys/devices/LNXSYSTM:00 --&gt; acpi:LNXSYSTM: /sys/devices/LNXSYSTM:00/device:00/PNP0C33:00 --&gt; acpi:PNP0C33:PNP0C01: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00 --&gt; acpi:PNP0A08:PNP0A03: /sys/devices/LNXSYSTM:00/device:00/PNP0A08:00/device:0d/PNP0200:00 --&gt; acpi:PNP0200: </code></pre> <p>and many others.</p> <ol start="3"> <li>When the device driver is <em>compiled in</em> (or doesn't exist) the response is <code>FATAL: Module _XXXX_ not found.</code> Indicating there is no module for the device.</li> </ol> <p>In some cases the driver is compiled in (e.g.)</p> <pre><code>/sys/devices/platform/serial8250 --&gt; platform:serial8250 FATAL: Module platform:serial8250 not found. /sys/devices/platform/i8042 --&gt; platform:i8042 FATAL: Module platform:i8042 not found. </code></pre> <p>In other cases, the driver just doesn't exist. But I don't know a way to tell the difference.</p> <p>Does anyone know?</p>
[ { "answer_id": 167606, "author": "Alex B", "author_id": 23643, "author_profile": "https://Stackoverflow.com/users/23643", "pm_score": 2, "selected": false, "text": "nvidia agpgart usbhid usbcore usbhid" }, { "answer_id": 168731, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "/sysfs/" }, { "answer_id": 999853, "author": "Robert S. Barnes", "author_id": 71074, "author_profile": "https://Stackoverflow.com/users/71074", "pm_score": 0, "selected": false, "text": "#!/bin/bash\n/sbin/lsmod | tail -n+2 | cut -d\" \" -f1 | xargs /sbin/modinfo -n | sort ; \n #!/usr/bin/perl -w\n\nuse strict;\nuse Getopt::Long;\n\nmy ($kernConfigIn, $kernConfigOut, $kernSourceDir, $lumSourceDir, $lumConfigIn, $lumConfigOut, $help);\n\nGetOptions(\n 'ksd=s' => \\$kernSourceDir,\n 'lsd=s' => \\$lumSourceDir,\n 'kci=s' => \\$kernConfigIn,\n 'lci=s' => \\$lumConfigIn,\n 'kco=s' => \\$kernConfigOut,\n 'lco=s' => \\$lumConfigOut,\n 'help' => \\$help);\n\nif ($help || !$kernSourceDir || !$lumSourceDir ) { Usage($0); }\n\nsub Usage { print \"usage error\\n\"; exit; };\n\nmy @modules = `/sbin/lsmod | tail -n+2 | cut -d\" \" -f1 | xargs /sbin/modinfo -n | sort ;`;\nmy @kconfig;\n\nforeach my $module (@modules) {\n my ($package, $path, $modName) = ( $module =~ m/\\/((?:kernel)|(?:ubuntu))\\/(.*)\\/(.*)\\.ko/) ;\n $package eq 'kernel' ? push @kconfig, kernel($package, $path, $modName) : ubuntu($package, $path, $modName); \n}\n\n# kernel package\nsub kernel {\n my ($package, $path, $modName) = @_;\n my $makefile = $kernSourceDir.$path.\"/Makefile\"; \n# print \"$package, $path, $modName\\n\";\n# print \"$makefile\\n\";\n my $option;\n chomp($option = `cat $makefile | sed -n \"s/^obj-\\\\\\$(CONFIG_\\\\([A-Z0-9_]*\\\\))\\\\W*+=.*\"$modName\"\\\\.o.*/CONFIG_\\\\1/p\"`);\n print \"$option\\n\";\n return $option;\n}\n\n# deal with lum configs\nsub ubuntu {\n\n}\n" }, { "answer_id": 3172162, "author": "anders", "author_id": 319241, "author_profile": "https://Stackoverflow.com/users/319241", "pm_score": 1, "selected": false, "text": " Kernel driver in use: wl\n Kernel modules: wl, ssb\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8013/" ]
167,567
<p>I have been asked to write a testing application that needs to test a new stored procedure on multiple rows in a database, in essence I want to do something like this:</p> <pre><code>[Test] public void TestSelect() { foreach(id in ids) { DataTable old = Database.call(&quot;old_stored_proc&quot;,id); DataTable new_ = Database.call(&quot;new_stored_proc&quot;,id); Assert.AreEqual(old.Rows[0][&quot;column&quot;],ne_.Rows[0][&quot;column&quot;]); } } </code></pre> <p>When I run this test, if 1 row doesn't match the other, the entire test fails; instead I would like to count how many times the assertion was passed and how many times it has failed. Is there a way to do this with NUnit?</p> <p>I realize that NUnit might be overkill and this is a simple task without it...I just wanted to learn it. ;)</p>
[ { "answer_id": 167598, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 1, "selected": false, "text": "Assert.Greater" }, { "answer_id": 167619, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": false, "text": "[Test]\npublic void TestSelect()\n{\n int errors = 0;\n foreach(id in ids)\n {\n DataTable old = Database.call(\"old_stored_proc\",id);\n DataTable new_ = Database.call(\"new_stored_proc\",id);\n\n if (old.Rows[0][\"column\"] != new_.Rows[0][\"column\"])\n {\n errors++;\n } \n }\n\n Assert.AreEqual(0, errors, \"There were \" + errors + \" errors.\");\n}\n" }, { "answer_id": 2926985, "author": "Yann Trevin", "author_id": 563, "author_profile": "https://Stackoverflow.com/users/563", "pm_score": 2, "selected": false, "text": "[Test]\npublic void MultipleTest()\n{\n Assert.Multiple(() =>\n {\n Assert.IsTrue(blabla);\n Assert.AreEqual(pik, pok);\n // etc.\n }\n}\n Assert.Multiple" }, { "answer_id": 23570997, "author": "yoyo", "author_id": 503688, "author_profile": "https://Stackoverflow.com/users/503688", "pm_score": 0, "selected": false, "text": "[Test]\npublic void TestEvenNumbers()\n{\n int[] numbers = new int[] { 2, 4, 12, 22, 13, 42 };\n numbers.AssertAll((num) => Assert.That((num % 2) == 0, \"{0} is an odd number\", num));\n}\n TestEvenNumbers:\n 5 of 6 tests passed; 0 inconclusive\nFAILED: 13: 13 is an odd number\n Expected: True\n But was: False\n\n Expected: 6\n But was: 5\n [Test]\npublic void TestSelect()\n{\n ids.AssertAll(CheckStoredProcedures);\n}\n\nprivate void CheckStoredProcedures(Id id)\n{\n DataTable old = Database.call(\"old_stored_proc\",id);\n DataTable new_ = Database.call(\"new_stored_proc\",id);\n\n Assert.AreEqual(old.Rows[0][\"column\"], new_.Rows[0][\"column\"]);\n}\n using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing NUnit.Framework;\n\npublic static class NUnitExtensions\n{\n public static void AssertAll<T>(this IEnumerable<T> objects, Action<T> test)\n {\n int total = 0;\n int passed = 0;\n int failed = 0;\n int inconclusive = 0;\n var sb = new StringBuilder();\n foreach (var obj in objects)\n {\n total++;\n try\n {\n test(obj);\n passed++;\n }\n catch (InconclusiveException assertion)\n {\n inconclusive++;\n string message = string.Format(\"INCONCLUSIVE: {0}: {1}\", obj.ToString(), assertion.Message);\n Console.WriteLine(message);\n sb.AppendLine(message);\n }\n catch (AssertionException assertion)\n {\n failed++;\n string message = string.Format(\"FAILED: {0}: {1}\", obj.ToString(), assertion.Message);\n Console.WriteLine(message);\n sb.AppendLine(message);\n }\n }\n\n if (passed != total)\n {\n string details = sb.ToString();\n string message = string.Format(\"{0} of {1} tests passed; {2} inconclusive\\n{3}\", passed, total, inconclusive, details);\n if (failed == 0)\n {\n Assert.Inconclusive(message);\n }\n else\n {\n Assert.AreEqual(total, passed, message);\n }\n }\n }\n}\n" }, { "answer_id": 50951617, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 0, "selected": false, "text": "[TestCase()] [Test]\n[TestCase(1234)]\n[TestCase(5678)]\n[TestCase(7654)]\npublic void TestSelect(int id)\n{\n DataTable old = Database.call(\"old_stored_proc\", id);\n DataTable new_ = Database.call(\"new_stored_proc\", id);\n\n Assert.AreEqual(old.Rows[0][\"column\"], new_.Rows[0][\"column\"]);\n}\n [TestCaseSource()]" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
167,576
<p>I would like this to be the ultimate discussion on how to check if a table exists in SQL Server 2000/2005 using SQL Statements.</p> <p>Here are two possible ways of doing it. Which one is the standard/best way of doing it?</p> <p>First way:</p> <pre><code>IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND TABLE_NAME='mytablename') SELECT 1 AS res ELSE SELECT 0 AS res; </code></pre> <p>Second way:</p> <pre><code>IF OBJECT_ID (N'mytablename', N'U') IS NOT NULL SELECT 1 AS res ELSE SELECT 0 AS res; </code></pre> <p><strong>MySQL</strong> provides the simple</p> <pre><code>SHOW TABLES LIKE '%tablename%'; </code></pre> <p>statement. I am looking for something similar.</p>
[ { "answer_id": 167610, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 8, "selected": false, "text": "OBJECT_ID IF OBJECT_ID('*objectName*', 'U') IS NOT NULL \n" }, { "answer_id": 167680, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 12, "selected": true, "text": "INFORMATION_SCHEMA IF (EXISTS (SELECT * \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'TheSchema' \n AND TABLE_NAME = 'TheTable'))\nBEGIN\n --Do Stuff\nEND\n" }, { "answer_id": 1601406, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 3, "selected": false, "text": "DECLARE @Catalog VARCHAR(255)\nSET @Catalog = 'MyDatabase'\n\nDECLARE @Schema VARCHAR(255)\nSET @Schema = 'dbo'\n\nDECLARE @Table VARCHAR(255)\nSET @Table = 'MyTable'\n\nIF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_CATALOG = @Catalog \n AND TABLE_SCHEMA = @Schema \n AND TABLE_NAME = @Table))\nBEGIN\n --do stuff\nEND\n" }, { "answer_id": 2155299, "author": "James Bloomer", "author_id": 38249, "author_profile": "https://Stackoverflow.com/users/38249", "pm_score": 8, "selected": false, "text": "if OBJECT_ID('tempdb..#test') is not null\n --- temp table exists\n" }, { "answer_id": 4760619, "author": "dko", "author_id": 528537, "author_profile": "https://Stackoverflow.com/users/528537", "pm_score": 3, "selected": false, "text": "create procedure Table_Exists\n@tbl varchar(50)\nas\nreturn (select count(*) from sysobjects where type = 'U' and name = @tbl)\ngo\n" }, { "answer_id": 5579755, "author": "dilip kumar singh", "author_id": 696619, "author_profile": "https://Stackoverflow.com/users/696619", "pm_score": 4, "selected": false, "text": "IF EXISTS \n(\n SELECT * \n FROM sys.objects \n WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') \n AND \n type in (N'U')\n)\nBEGIN\n\n -- Do whatever you need to here.\n\nEND\n Mapping_APCToFANavigator" }, { "answer_id": 9724871, "author": "Larry Leonard", "author_id": 1272181, "author_profile": "https://Stackoverflow.com/users/1272181", "pm_score": 5, "selected": false, "text": "if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n" }, { "answer_id": 19564163, "author": "Moccassin", "author_id": 2854813, "author_profile": "https://Stackoverflow.com/users/2854813", "pm_score": 2, "selected": false, "text": "IF EXISTS \n(\n SELECT * \n\n FROM INFORMATION_SCHEMA.TABLES \n\n WHERE TABLE_SCHEMA = 'PutSchemaHere' \n AND \n TABLE_NAME = 'PutTableNameHere'\n)\n" }, { "answer_id": 20141958, "author": "sansalk", "author_id": 1403070, "author_profile": "https://Stackoverflow.com/users/1403070", "pm_score": 5, "selected": false, "text": "IF OBJECT_ID('mytablename') IS NOT NULL \n" }, { "answer_id": 21635500, "author": "Maslow", "author_id": 57883, "author_profile": "https://Stackoverflow.com/users/57883", "pm_score": 0, "selected": false, "text": "let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )\nwhere oSchema !=null\nlet o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null\nwhere o!=null\n a" }, { "answer_id": 21685540, "author": "MarceloMadnezz", "author_id": 2611146, "author_profile": "https://Stackoverflow.com/users/2611146", "pm_score": 0, "selected": false, "text": "select name from SysObjects where xType='U' and name like '%xxx%' order by name\n" }, { "answer_id": 24912436, "author": "phil294", "author_id": 3779853, "author_profile": "https://Stackoverflow.com/users/3779853", "pm_score": 2, "selected": false, "text": " $sql = \"SELECT 1 FROM `db_name`.`table_name` LIMIT 1;\";\n $result = mysql_query($sql);\n if( $result == false )\n echo \"table DOES NOT EXIST\";\n else\n echo \"table exists\";\n" }, { "answer_id": 25372822, "author": "user3651072", "author_id": 3651072, "author_profile": "https://Stackoverflow.com/users/3651072", "pm_score": -1, "selected": false, "text": "if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n" }, { "answer_id": 26996845, "author": "Biniam Eyakem", "author_id": 946931, "author_profile": "https://Stackoverflow.com/users/946931", "pm_score": 2, "selected": false, "text": " IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL \n BEGIN \n print 'deleted table';\n drop table t \n END\n else \n begin \n print 'table not found' \n end\n\n Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)\n insert into t( name, lastname) values('john','doe');\n insert into t( name, lastname) values('rose',NULL);\n\n Select * from t\n1 john doe\n2 rose NULL\n\n -- clean\n drop table t\n" }, { "answer_id": 27602349, "author": "BrainCoder", "author_id": 1245631, "author_profile": "https://Stackoverflow.com/users/1245631", "pm_score": 8, "selected": false, "text": "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')\nBEGIN\n PRINT 'Table Exists'\nEND\n IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL\nBEGIN\n PRINT 'Table Exists'\nEND\n IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')\nBEGIN\n PRINT 'Table Exists'\nEND\n IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n" }, { "answer_id": 28115618, "author": "Marcello Miorelli", "author_id": 1501497, "author_profile": "https://Stackoverflow.com/users/1501497", "pm_score": 3, "selected": false, "text": "the_name object_id the_schema the_table the_type\n[Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table\n PRINT 'THE SERVER IS ' + @@SERVERNAME\n--select db_name()\nPRINT 'THE DATABASE IS ' + db_NAME() \nPRINT ''\nGO\n\nSET NOCOUNT ON\nGO\n\n--===================================================================================\n-- @TableName is the parameter\n-- the object we want to deal with (it might be an indexed view or a table)\n-- the schema might or might not be specified\n-- when not specified it is DBO\n--===================================================================================\n\nDECLARE @TableName SYSNAME\n\nSELECT @TableName = 'Facts.FactBackOrder'\n--===================================================================================\n--===================================================================================\nDECLARE @Schema SYSNAME\nDECLARE @I INT\nDECLARE @Z INT \n\nSELECT @TableName = LTRIM(RTRIM(@TableName))\nSELECT @Z = LEN(@TableName)\n\nIF (@Z = 0) BEGIN\n\n RAISERROR('Invalid @Tablename passed.',16,1)\n\nEND \n\nSELECT @I = CHARINDEX('.',@TableName )\n--SELECT @TableName ,@I\n\nIF @I > 0 BEGIN\n\n --===================================================================================\n -- a schema and table name have been passed\n -- example Facts.FactBackOrder \n -- @Schema = Fact\n -- @TableName = FactBackOrder\n --===================================================================================\n\n SELECT @Schema = SUBSTRING(@TABLENAME,1,@I-1)\n SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)\n\n\n\nEND\nELSE BEGIN\n\n --===================================================================================\n -- just a table name have been passed\n -- so the schema will be dbo\n -- example Orders\n -- @Schema = dbo\n -- @TableName = Orders\n --===================================================================================\n\n SELECT @Schema = 'DBO' \n\n\nEND\n\n --===================================================================================\n -- Check whether the @SchemaName is valid in the current database\n --===================================================================================\n\nIF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN\n\n RAISERROR('Invalid Schema Name.',16,1)\n\nEND \n\n--SELECT @Schema as [@Schema]\n-- ,@TableName as [@TableName]\n\n\nDECLARE @R1 TABLE (\n\n THE_NAME SYSNAME\n ,THE_SCHEMA SYSNAME\n ,THE_TABLE SYSNAME\n ,OBJECT_ID INT\n ,THE_TYPE SYSNAME\n ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)\n\n)\n\n;WITH RADHE_01 AS (\nSELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]\n ,the_schema=SCHEMA_NAME(O.schema_id)\n ,the_table=O.NAME\n ,object_id =o.object_id \n ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END \nfrom sys.objects O\nwhere O.is_ms_shipped = 0\nAND O.TYPE IN ('U','V')\n)\nINSERT INTO @R1 (\n THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n)\nSELECT the_name\n ,the_schema\n ,the_table\n ,object_id\n ,the_type\nFROM RADHE_01\nWHERE the_schema = @Schema \n AND the_table = @TableName\n\nIF (@@ROWCOUNT = 0) BEGIN \n\n RAISERROR('Invalid Table Name.',16,1)\n\nEND \nELSE BEGIN\n\n SELECT THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n\n FROM @R1\n\nEND \n" }, { "answer_id": 29676582, "author": "dipi evil", "author_id": 1016406, "author_profile": "https://Stackoverflow.com/users/1016406", "pm_score": 3, "selected": false, "text": "IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')\nBEGIN\n SELECT 1 AS 'res' \nEND\n" }, { "answer_id": 37974532, "author": "John Smith", "author_id": 3739391, "author_profile": "https://Stackoverflow.com/users/3739391", "pm_score": 5, "selected": false, "text": "OBJECT_ID INFORMATION_SCHEMA IF EXISTS (SELECT 1 \n FROM [database].INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE='BASE TABLE' \n AND TABLE_NAME='mytablename') \n SELECT 1 AS res ELSE SELECT 0 AS res;\n [database] [database] OBJECT_ID IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n if exists drop drop table if exists mytablename\n OBJECT_ID INFORMATION_SCHEMA" }, { "answer_id": 46071815, "author": "Mathieu Dierckx", "author_id": 4300486, "author_profile": "https://Stackoverflow.com/users/4300486", "pm_score": 0, "selected": false, "text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `checkIfTableExists`;\n\nCREATE PROCEDURE checkIfTableExists(\n IN databaseName CHAR(255),\n IN tableName CHAR(255),\n OUT boolExistsOrNot CHAR(40)\n)\n\n BEGIN\n SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES\n WHERE (TABLE_SCHEMA = databaseName)\n AND (TABLE_NAME = tableName);\n END $$\n\nDELIMITER ;\n CALL checkIfTableExists('muDbName', 'migrations', @output);\n" }, { "answer_id": 50924306, "author": "Krishnaraj Barvathaya", "author_id": 84979, "author_profile": "https://Stackoverflow.com/users/84979", "pm_score": 1, "selected": false, "text": "IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )\nBEGIN\n SELECT * FROM dbo.TableName;\nEND\nGO\n" }, { "answer_id": 55293422, "author": "Michael Quad", "author_id": 7128889, "author_profile": "https://Stackoverflow.com/users/7128889", "pm_score": 2, "selected": false, "text": "SELECT COUNT(*) FROM <yourTableNameHere>\n if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {\n // myTable doesn't exist..\n}\n" }, { "answer_id": 56361971, "author": "S Krishna", "author_id": 5850848, "author_profile": "https://Stackoverflow.com/users/5850848", "pm_score": -1, "selected": false, "text": "IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL\nPRINT 'Table Exists';\n" }, { "answer_id": 56867605, "author": "Mohammad Reza Shahrestani", "author_id": 6174449, "author_profile": "https://Stackoverflow.com/users/6174449", "pm_score": 2, "selected": false, "text": "IF EXISTS (\nSELECT *\nFROM INFORMATION_SCHEMA.TABLES\nWHERE \nTABLE_CATALOG = 'Database Name' and\nTABLE_NAME = 'Table Name' and \nTABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted\n\nBEGIN\n--TABLE EXISTS\nEND\n\nELSE BEGIN\n--TABLE DOES NOT EXISTS\nEND\n" }, { "answer_id": 57941500, "author": "Reza Jenabi", "author_id": 9549856, "author_profile": "https://Stackoverflow.com/users/9549856", "pm_score": 4, "selected": false, "text": "IF (OBJECT_ID('TableName') IS NOT NULL )\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n" }, { "answer_id": 59608790, "author": "Kelum Sampath Edirisinghe", "author_id": 9976255, "author_profile": "https://Stackoverflow.com/users/9976255", "pm_score": 0, "selected": false, "text": "IF Object_ID('TestView') IS NOT NULL\nDROP VIEW TestView\n\nGO\n\nCREATE VIEW TestView\n as\n . . .\n\nGO\n DECLARE @SQL as varchar(4000)\n\n-- set to body of view\nSET @SQL = 'SELECT X, Y, Z FROM TABLE' \n\nIF Object_ID('TestView') IS NULL\n SET @SQL = 'CREATE VIEW TestView AS ' + @SQL\nELSE \n SET @SQL = 'ALTER VIEW TestView AS ' + @SQL\n" }, { "answer_id": 60426669, "author": "Jitan Gupta", "author_id": 8178474, "author_profile": "https://Stackoverflow.com/users/8178474", "pm_score": 1, "selected": false, "text": "IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')\nBEGIN\n -- do whatever you want\nEND\n" }, { "answer_id": 73935575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "IF EXISTS (select * from sys.tables \nWHERE name='mytablename' )\nBEGIN\n print 'table exists in the database'\nEND\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
167,577
<p>I am working on a project that requires reliable access to historic feed entries which are not necessarily available in the current feed of the website. I have found several ways to access such data, but none of them give me all the characteristics I need.</p> <p>Look at this as a brainstorm. I will tell you how much I have found and you can contribute if you have any other ideas.</p> <ol> <li><p><a href="http://code.google.com/apis/ajaxfeeds/" rel="nofollow noreferrer">Google AJAX Feed API</a> - will limit you to 250 items</p></li> <li><p><a href="http://www.niallkennedy.com/blog/2005/12/google-reader-api.html" rel="nofollow noreferrer">Unofficial Google Reader API</a> - Perfect but unofficial and therefore unreliable (and perhaps quasi-illegal?). Also, the authentication seems to be tricky.</p></li> <li><p><a href="http://spinn3r.com/" rel="nofollow noreferrer">Spinn3r</a> - Costs a lot of money</p></li> <li><p>Spidering the <a href="http://www.archive.org" rel="nofollow noreferrer">internet archive</a> at the site of the feed - Lots of complexity, spotty coverage, only useful as a last resort</p></li> <li><p><a href="http://www.niallkennedy.com/blog/2005/12/my-yahoo-feed-a.html" rel="nofollow noreferrer">Yahoo! Feed API</a> or <a href="http://developer.yahoo.com/search/boss/" rel="nofollow noreferrer">Yahoo! Search BOSS</a> - The first looks more like an aggregator, meaning I'd need a different registration for each feed and the second should give more access to Yahoo's data but I can find no mention of feeds.</p></li> <li><p>(thanks to Lou Franco) <a href="http://www.bloglines.com/services/api/sync" rel="nofollow noreferrer">Bloglines Sync API</a> - Besides the problem of needing an account and being designed more as an aggregator, it does not have a way to add feeds to the account. So no retrieval of arbitrary feeds. You need to manually add them through the reader first.</p></li> <li><p>Other search engines/blog search/whatever?</p></li> </ol> <p>This is a really irritating problem as we are talking about semantic information that was once out there, is still (usually) valid, yet is difficult to access reliably, freely and without limits. Anybody know any alternative sources for feed entry goodness?</p>
[ { "answer_id": 167610, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 8, "selected": false, "text": "OBJECT_ID IF OBJECT_ID('*objectName*', 'U') IS NOT NULL \n" }, { "answer_id": 167680, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 12, "selected": true, "text": "INFORMATION_SCHEMA IF (EXISTS (SELECT * \n FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_SCHEMA = 'TheSchema' \n AND TABLE_NAME = 'TheTable'))\nBEGIN\n --Do Stuff\nEND\n" }, { "answer_id": 1601406, "author": "Even Mien", "author_id": 73794, "author_profile": "https://Stackoverflow.com/users/73794", "pm_score": 3, "selected": false, "text": "DECLARE @Catalog VARCHAR(255)\nSET @Catalog = 'MyDatabase'\n\nDECLARE @Schema VARCHAR(255)\nSET @Schema = 'dbo'\n\nDECLARE @Table VARCHAR(255)\nSET @Table = 'MyTable'\n\nIF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES \n WHERE TABLE_CATALOG = @Catalog \n AND TABLE_SCHEMA = @Schema \n AND TABLE_NAME = @Table))\nBEGIN\n --do stuff\nEND\n" }, { "answer_id": 2155299, "author": "James Bloomer", "author_id": 38249, "author_profile": "https://Stackoverflow.com/users/38249", "pm_score": 8, "selected": false, "text": "if OBJECT_ID('tempdb..#test') is not null\n --- temp table exists\n" }, { "answer_id": 4760619, "author": "dko", "author_id": 528537, "author_profile": "https://Stackoverflow.com/users/528537", "pm_score": 3, "selected": false, "text": "create procedure Table_Exists\n@tbl varchar(50)\nas\nreturn (select count(*) from sysobjects where type = 'U' and name = @tbl)\ngo\n" }, { "answer_id": 5579755, "author": "dilip kumar singh", "author_id": 696619, "author_profile": "https://Stackoverflow.com/users/696619", "pm_score": 4, "selected": false, "text": "IF EXISTS \n(\n SELECT * \n FROM sys.objects \n WHERE object_id = OBJECT_ID(N'[dbo].[Mapping_APCToFANavigator]') \n AND \n type in (N'U')\n)\nBEGIN\n\n -- Do whatever you need to here.\n\nEND\n Mapping_APCToFANavigator" }, { "answer_id": 9724871, "author": "Larry Leonard", "author_id": 1272181, "author_profile": "https://Stackoverflow.com/users/1272181", "pm_score": 5, "selected": false, "text": "if exists (select * from MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n" }, { "answer_id": 19564163, "author": "Moccassin", "author_id": 2854813, "author_profile": "https://Stackoverflow.com/users/2854813", "pm_score": 2, "selected": false, "text": "IF EXISTS \n(\n SELECT * \n\n FROM INFORMATION_SCHEMA.TABLES \n\n WHERE TABLE_SCHEMA = 'PutSchemaHere' \n AND \n TABLE_NAME = 'PutTableNameHere'\n)\n" }, { "answer_id": 20141958, "author": "sansalk", "author_id": 1403070, "author_profile": "https://Stackoverflow.com/users/1403070", "pm_score": 5, "selected": false, "text": "IF OBJECT_ID('mytablename') IS NOT NULL \n" }, { "answer_id": 21635500, "author": "Maslow", "author_id": 57883, "author_profile": "https://Stackoverflow.com/users/57883", "pm_score": 0, "selected": false, "text": "let oSchema = sys.Schemas.FirstOrDefault(s=>s.Name==a.schema )\nwhere oSchema !=null\nlet o=oSchema!=null?sys.Objects.FirstOrDefault (o => o.Name==a.item && o.Schema_id==oSchema.Schema_id):null\nwhere o!=null\n a" }, { "answer_id": 21685540, "author": "MarceloMadnezz", "author_id": 2611146, "author_profile": "https://Stackoverflow.com/users/2611146", "pm_score": 0, "selected": false, "text": "select name from SysObjects where xType='U' and name like '%xxx%' order by name\n" }, { "answer_id": 24912436, "author": "phil294", "author_id": 3779853, "author_profile": "https://Stackoverflow.com/users/3779853", "pm_score": 2, "selected": false, "text": " $sql = \"SELECT 1 FROM `db_name`.`table_name` LIMIT 1;\";\n $result = mysql_query($sql);\n if( $result == false )\n echo \"table DOES NOT EXIST\";\n else\n echo \"table exists\";\n" }, { "answer_id": 25372822, "author": "user3651072", "author_id": 3651072, "author_profile": "https://Stackoverflow.com/users/3651072", "pm_score": -1, "selected": false, "text": "if exists (select * from REMOTE_SERVER.MyOtherDatabase.sys.tables where name = 'MyTable')\n print 'Exists'\n" }, { "answer_id": 26996845, "author": "Biniam Eyakem", "author_id": 946931, "author_profile": "https://Stackoverflow.com/users/946931", "pm_score": 2, "selected": false, "text": " IF OBJECT_ID (N'dbo.T', N'U') IS NOT NULL \n BEGIN \n print 'deleted table';\n drop table t \n END\n else \n begin \n print 'table not found' \n end\n\n Create table t (id int identity(1,1) not null, name varchar(30) not null, lastname varchar(25) null)\n insert into t( name, lastname) values('john','doe');\n insert into t( name, lastname) values('rose',NULL);\n\n Select * from t\n1 john doe\n2 rose NULL\n\n -- clean\n drop table t\n" }, { "answer_id": 27602349, "author": "BrainCoder", "author_id": 1245631, "author_profile": "https://Stackoverflow.com/users/1245631", "pm_score": 8, "selected": false, "text": "IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')\nBEGIN\n PRINT 'Table Exists'\nEND\n IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL\nBEGIN\n PRINT 'Table Exists'\nEND\n IF EXISTS(SELECT 1 FROM sys.Objects WHERE Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')\nBEGIN\n PRINT 'Table Exists'\nEND\n IF EXISTS(SELECT 1 FROM sys.Tables WHERE Name = N'Customers' AND Type = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')\n BEGIN\n PRINT 'Table Exists'\n END\n" }, { "answer_id": 28115618, "author": "Marcello Miorelli", "author_id": 1501497, "author_profile": "https://Stackoverflow.com/users/1501497", "pm_score": 3, "selected": false, "text": "the_name object_id the_schema the_table the_type\n[Facts].[FactBackOrder] 758293761 Facts FactBackOrder Table\n PRINT 'THE SERVER IS ' + @@SERVERNAME\n--select db_name()\nPRINT 'THE DATABASE IS ' + db_NAME() \nPRINT ''\nGO\n\nSET NOCOUNT ON\nGO\n\n--===================================================================================\n-- @TableName is the parameter\n-- the object we want to deal with (it might be an indexed view or a table)\n-- the schema might or might not be specified\n-- when not specified it is DBO\n--===================================================================================\n\nDECLARE @TableName SYSNAME\n\nSELECT @TableName = 'Facts.FactBackOrder'\n--===================================================================================\n--===================================================================================\nDECLARE @Schema SYSNAME\nDECLARE @I INT\nDECLARE @Z INT \n\nSELECT @TableName = LTRIM(RTRIM(@TableName))\nSELECT @Z = LEN(@TableName)\n\nIF (@Z = 0) BEGIN\n\n RAISERROR('Invalid @Tablename passed.',16,1)\n\nEND \n\nSELECT @I = CHARINDEX('.',@TableName )\n--SELECT @TableName ,@I\n\nIF @I > 0 BEGIN\n\n --===================================================================================\n -- a schema and table name have been passed\n -- example Facts.FactBackOrder \n -- @Schema = Fact\n -- @TableName = FactBackOrder\n --===================================================================================\n\n SELECT @Schema = SUBSTRING(@TABLENAME,1,@I-1)\n SELECT @TableName = SUBSTRING(@TABLENAME,@I+1,@Z-@I)\n\n\n\nEND\nELSE BEGIN\n\n --===================================================================================\n -- just a table name have been passed\n -- so the schema will be dbo\n -- example Orders\n -- @Schema = dbo\n -- @TableName = Orders\n --===================================================================================\n\n SELECT @Schema = 'DBO' \n\n\nEND\n\n --===================================================================================\n -- Check whether the @SchemaName is valid in the current database\n --===================================================================================\n\nIF NOT EXISTS ( SELECT * FROM INFORMATION_SCHEMA.SCHEMATA K WHERE K.[SCHEMA_NAME] = @Schema ) BEGIN\n\n RAISERROR('Invalid Schema Name.',16,1)\n\nEND \n\n--SELECT @Schema as [@Schema]\n-- ,@TableName as [@TableName]\n\n\nDECLARE @R1 TABLE (\n\n THE_NAME SYSNAME\n ,THE_SCHEMA SYSNAME\n ,THE_TABLE SYSNAME\n ,OBJECT_ID INT\n ,THE_TYPE SYSNAME\n ,PRIMARY KEY CLUSTERED (THE_SCHEMA,THE_NAME)\n\n)\n\n;WITH RADHE_01 AS (\nSELECT QUOTENAME(SCHEMA_NAME(O.schema_id)) + '.' + QUOTENAME(O.NAME) AS [the_name]\n ,the_schema=SCHEMA_NAME(O.schema_id)\n ,the_table=O.NAME\n ,object_id =o.object_id \n ,[the_type]= CASE WHEN O.TYPE = 'U' THEN 'Table' ELSE 'View' END \nfrom sys.objects O\nwhere O.is_ms_shipped = 0\nAND O.TYPE IN ('U','V')\n)\nINSERT INTO @R1 (\n THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n)\nSELECT the_name\n ,the_schema\n ,the_table\n ,object_id\n ,the_type\nFROM RADHE_01\nWHERE the_schema = @Schema \n AND the_table = @TableName\n\nIF (@@ROWCOUNT = 0) BEGIN \n\n RAISERROR('Invalid Table Name.',16,1)\n\nEND \nELSE BEGIN\n\n SELECT THE_NAME \n ,THE_SCHEMA \n ,THE_TABLE \n ,OBJECT_ID\n ,THE_TYPE \n\n FROM @R1\n\nEND \n" }, { "answer_id": 29676582, "author": "dipi evil", "author_id": 1016406, "author_profile": "https://Stackoverflow.com/users/1016406", "pm_score": 3, "selected": false, "text": "IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')\nBEGIN\n SELECT 1 AS 'res' \nEND\n" }, { "answer_id": 37974532, "author": "John Smith", "author_id": 3739391, "author_profile": "https://Stackoverflow.com/users/3739391", "pm_score": 5, "selected": false, "text": "OBJECT_ID INFORMATION_SCHEMA IF EXISTS (SELECT 1 \n FROM [database].INFORMATION_SCHEMA.TABLES \n WHERE TABLE_TYPE='BASE TABLE' \n AND TABLE_NAME='mytablename') \n SELECT 1 AS res ELSE SELECT 0 AS res;\n [database] [database] OBJECT_ID IF OBJECT_ID (N'db1.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n IF OBJECT_ID (N'db2.schema.table1', N'U') IS NOT NULL \n SELECT 1 AS res ELSE SELECT 0 AS res;\n if exists drop drop table if exists mytablename\n OBJECT_ID INFORMATION_SCHEMA" }, { "answer_id": 46071815, "author": "Mathieu Dierckx", "author_id": 4300486, "author_profile": "https://Stackoverflow.com/users/4300486", "pm_score": 0, "selected": false, "text": "DELIMITER $$\n\nDROP PROCEDURE IF EXISTS `checkIfTableExists`;\n\nCREATE PROCEDURE checkIfTableExists(\n IN databaseName CHAR(255),\n IN tableName CHAR(255),\n OUT boolExistsOrNot CHAR(40)\n)\n\n BEGIN\n SELECT count(*) INTO boolExistsOrNot FROM information_schema.TABLES\n WHERE (TABLE_SCHEMA = databaseName)\n AND (TABLE_NAME = tableName);\n END $$\n\nDELIMITER ;\n CALL checkIfTableExists('muDbName', 'migrations', @output);\n" }, { "answer_id": 50924306, "author": "Krishnaraj Barvathaya", "author_id": 84979, "author_profile": "https://Stackoverflow.com/users/84979", "pm_score": 1, "selected": false, "text": "IF EXISTS ( SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.TableName') AND OBJECTPROPERTY(id, N'IsUserTable') = 1 )\nBEGIN\n SELECT * FROM dbo.TableName;\nEND\nGO\n" }, { "answer_id": 55293422, "author": "Michael Quad", "author_id": 7128889, "author_profile": "https://Stackoverflow.com/users/7128889", "pm_score": 2, "selected": false, "text": "SELECT COUNT(*) FROM <yourTableNameHere>\n if (sqlexec(conectionHandle, 'SELECT COUNT(*) FROM myTable') == -1) {\n // myTable doesn't exist..\n}\n" }, { "answer_id": 56361971, "author": "S Krishna", "author_id": 5850848, "author_profile": "https://Stackoverflow.com/users/5850848", "pm_score": -1, "selected": false, "text": "IF(SELECT TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'YourTableName') IS NOT NULL\nPRINT 'Table Exists';\n" }, { "answer_id": 56867605, "author": "Mohammad Reza Shahrestani", "author_id": 6174449, "author_profile": "https://Stackoverflow.com/users/6174449", "pm_score": 2, "selected": false, "text": "IF EXISTS (\nSELECT *\nFROM INFORMATION_SCHEMA.TABLES\nWHERE \nTABLE_CATALOG = 'Database Name' and\nTABLE_NAME = 'Table Name' and \nTABLE_SCHEMA = 'Schema Name') -- Database and Schema name in where statement can be deleted\n\nBEGIN\n--TABLE EXISTS\nEND\n\nELSE BEGIN\n--TABLE DOES NOT EXISTS\nEND\n" }, { "answer_id": 57941500, "author": "Reza Jenabi", "author_id": 9549856, "author_profile": "https://Stackoverflow.com/users/9549856", "pm_score": 4, "selected": false, "text": "IF (OBJECT_ID('TableName') IS NOT NULL )\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n IF (EXISTS (SELECT * FROM sys.tables WHERE [name] = 'TableName'))\nBEGIN\n PRINT 'Table Exists'\nEND\nELSE\nBEGIN \n PRINT 'Table NOT Exists'\nEND\n" }, { "answer_id": 59608790, "author": "Kelum Sampath Edirisinghe", "author_id": 9976255, "author_profile": "https://Stackoverflow.com/users/9976255", "pm_score": 0, "selected": false, "text": "IF Object_ID('TestView') IS NOT NULL\nDROP VIEW TestView\n\nGO\n\nCREATE VIEW TestView\n as\n . . .\n\nGO\n DECLARE @SQL as varchar(4000)\n\n-- set to body of view\nSET @SQL = 'SELECT X, Y, Z FROM TABLE' \n\nIF Object_ID('TestView') IS NULL\n SET @SQL = 'CREATE VIEW TestView AS ' + @SQL\nELSE \n SET @SQL = 'ALTER VIEW TestView AS ' + @SQL\n" }, { "answer_id": 60426669, "author": "Jitan Gupta", "author_id": 8178474, "author_profile": "https://Stackoverflow.com/users/8178474", "pm_score": 1, "selected": false, "text": "IF EXISTS(SELECT 1 FROM [change-to-your-database].SYS.TABLES WHERE NAME = 'change-to-your-table-name')\nBEGIN\n -- do whatever you want\nEND\n" }, { "answer_id": 73935575, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "IF EXISTS (select * from sys.tables \nWHERE name='mytablename' )\nBEGIN\n print 'table exists in the database'\nEND\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24461/" ]
167,587
<p>I'm trying to load assemblies in a separate app domain, but am running into a very strange problem. Here's some code:</p> <pre><code> public static void LoadAssembly(string assemblyPath) { string pathToDll = Assembly.GetCallingAssembly().CodeBase; AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = pathToDll }; AppDomain newDomain = AppDomain.CreateDomain("AssemblyLoader",null,domainSetup); AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap( pathToDll, typeof(AssemblyLoader).FullName); } </code></pre> <p>AssemblyLoader is another class in the same assembly as this one, and it inherits from MarshalByRef, however for some strange reason, I get a cast exception every time I try to run this. I even hardcoded the path to the DLL instead of using GetCallingAssembly().CodeBase yet I keep getting this exception. </p> <p>I understand it's hard to answer a question like this without actually seeing it and having more information, but maybe someone has run into a similar situation and would know the common "gotchas" and what I should look out for.</p> <p>EDIT: The reason I don't want to load it directly is because this is just part of the code. The ultimate goal is that this class will have a method that load assemblies, gets their GUID and some other info about them and stores them in a database for a project I'm working on. Therefore, if I load this assembly in a separate app domain, I can load the others there too and then unload the app domain. No point in having all these assemblies loaded for the duration of the app, if I only need that data.</p>
[ { "answer_id": 167658, "author": "TheXenocide", "author_id": 8543, "author_profile": "https://Stackoverflow.com/users/8543", "pm_score": 0, "selected": false, "text": "AssemblyLoader loader = (AssemblyLoader)newDomain.CreateInstanceFromAndUnwrap(\n typeof(AssemblyLoader).Assembly.FullName,\n typeof(AssemblyLoader).FullName);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15861/" ]
167,602
<p>I have a class which implements UserControl. In .NET 2005, a Dispose method is automatically created in the MyClass.Designer.cs partial class file that looks like this:</p> <pre><code> protected override void Dispose(bool disposing) { if (disposing &amp;&amp; (components != null)) { components.Dispose(); } base.Dispose(disposing); } </code></pre> <p>If I want to add my own Dispose functionality, where would I put it? Since this file is generated, I don't want to add code here and risk it getting blown away.</p>
[ { "answer_id": 167627, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 3, "selected": false, "text": "Dispose" }, { "answer_id": 167642, "author": "Michael Damatov", "author_id": 23372, "author_profile": "https://Stackoverflow.com/users/23372", "pm_score": 7, "selected": true, "text": "Dispose" }, { "answer_id": 330018, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "Component Disposed UserControl private void OnDispose(object sender, EventArgs e)\n{\n // do stuff on dispose\n}\n Load Disposed += OnDispose;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22252/" ]
167,622
<p>What are the major difference between bindable LINQ and continuous LINQ?</p> <p>•Bindable LINQ: www.codeplex.com/bindablelinq</p> <p>•Continuous LINQ: www.codeplex.com/clinq</p> <p>One more project was added basing on the provided feedback:</p> <p>•Obtics: obtics.codeplex.com</p>
[ { "answer_id": 174924, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 6, "selected": true, "text": "from item in theSource select item ;\n from item in theSource.AsBindable() select item ;\n var theSource = new ContinuousCollection<Customer>();\nvar theResultSet = from item in theSource where item.Age > 25 select item;\n//theResultSet.Count would equal 0.\n theSource.Add(new Customer(\"Bob\", \"Barker\" , 35, Gender.Male)); //Age == 35\n//theResultSet.Count would now equal 1.\n contactsListBox.ItemsSource = from c in customers\n where c.Name.StartsWith(textBox1.Text)\n select c;\n" }, { "answer_id": 606571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "var theResultSet = ExpressionObserver.Execute(\n () => from item in theSource where item.Age > 25 select item\n).Cascade();\n" }, { "answer_id": 12163131, "author": "Nestor", "author_id": 122732, "author_profile": "https://Stackoverflow.com/users/122732", "pm_score": 1, "selected": false, "text": "var _source = CreateSource_6People(); //(David, 27), (Mark, 15), (Steve, 30), (Jordan, 43), (Shiva, 30), (Erb, 43)\nIBindable<int> bindable = _source.AsBindable().Sum(x => x.Age);\nvar agesSum = 27+15+30+43+30+43;\nAssert.AreEqual(agesSum, bindable.Current); //PASSES\n\n_source[0].Age += 1;\nAssert.AreEqual(agesSum + 1, bindable.Current); //FAILS... DISAPPOINTING\n" }, { "answer_id": 58950913, "author": "Igor Buchelnikov", "author_id": 2663791, "author_profile": "https://Stackoverflow.com/users/2663791", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing IBCode.ObservableComputations;\n\nnamespace ObservableComputationsExamples\n{\n public class Order : INotifyPropertyChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Num {get; set;}\n\n private decimal _price;\n public decimal Price\n {\n get => _price;\n set\n {\n _price = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Price)));\n }\n }\n\n public Order(int num, decimal price)\n {\n Num = num;\n _price = price;\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n ObservableCollection<Order> orders = \n new ObservableCollection<Order>(new []\n {\n new Order(1, 15),\n new Order(2, 15),\n new Order(3, 25),\n new Order(4, 27),\n new Order(5, 30),\n new Order(6, 75),\n new Order(7, 80),\n });\n\n //********************************************\n // We start using ObservableComputations here!\n Filtering<Order> expensiveOrders = orders.Filtering(o => o.Price > 25); \n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n expensiveOrders.CollectionChanged += (sender, eventArgs) =>\n {\n // see the changes (add, remove, replace, move, reset) here\n };\n\n // Start the changing...\n orders.Add(new Order(8, 30));\n orders.Add(new Order(9, 10));\n orders[0].Price = 60;\n orders[4].Price = 10;\n orders.Move(5, 1);\n orders[1] = new Order(10, 17);\n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n Console.ReadLine();\n }\n\n static void checkFiltering(\n ObservableCollection<Order> orders, \n Filtering<Order> expensiveOrders)\n {\n Console.WriteLine(expensiveOrders.SequenceEqual(\n orders.Where(o => o.Price > 25)));\n }\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ]
167,628
<p>We are managing our development with Subversion over HTTPS, Bugzilla, and Mediawiki. Some of our developers have expressed an interest in migrating to Trac, so I have to evaluate what the cost of doing so would be. </p> <p>For both the wiki and bugzilla, we would need to either migrate the existing data into Trac or a way to integrate with trac. Having two apps to create wiki pages or log bugs would not be acceptable. Also, currently each of these applications requires a separate sign on so we would need to map each of these accounts into Trac.</p> <p>So know of any easy methods of importing or integrating these systems with Trac and/or a tutorial for doing so?</p>
[ { "answer_id": 174924, "author": "KyleLanser", "author_id": 12923, "author_profile": "https://Stackoverflow.com/users/12923", "pm_score": 6, "selected": true, "text": "from item in theSource select item ;\n from item in theSource.AsBindable() select item ;\n var theSource = new ContinuousCollection<Customer>();\nvar theResultSet = from item in theSource where item.Age > 25 select item;\n//theResultSet.Count would equal 0.\n theSource.Add(new Customer(\"Bob\", \"Barker\" , 35, Gender.Male)); //Age == 35\n//theResultSet.Count would now equal 1.\n contactsListBox.ItemsSource = from c in customers\n where c.Name.StartsWith(textBox1.Text)\n select c;\n" }, { "answer_id": 606571, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "var theResultSet = ExpressionObserver.Execute(\n () => from item in theSource where item.Age > 25 select item\n).Cascade();\n" }, { "answer_id": 12163131, "author": "Nestor", "author_id": 122732, "author_profile": "https://Stackoverflow.com/users/122732", "pm_score": 1, "selected": false, "text": "var _source = CreateSource_6People(); //(David, 27), (Mark, 15), (Steve, 30), (Jordan, 43), (Shiva, 30), (Erb, 43)\nIBindable<int> bindable = _source.AsBindable().Sum(x => x.Age);\nvar agesSum = 27+15+30+43+30+43;\nAssert.AreEqual(agesSum, bindable.Current); //PASSES\n\n_source[0].Age += 1;\nAssert.AreEqual(agesSum + 1, bindable.Current); //FAILS... DISAPPOINTING\n" }, { "answer_id": 58950913, "author": "Igor Buchelnikov", "author_id": 2663791, "author_profile": "https://Stackoverflow.com/users/2663791", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.ObjectModel;\nusing System.ComponentModel;\nusing System.Linq;\nusing IBCode.ObservableComputations;\n\nnamespace ObservableComputationsExamples\n{\n public class Order : INotifyPropertyChanged\n {\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Num {get; set;}\n\n private decimal _price;\n public decimal Price\n {\n get => _price;\n set\n {\n _price = value;\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Price)));\n }\n }\n\n public Order(int num, decimal price)\n {\n Num = num;\n _price = price;\n }\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n ObservableCollection<Order> orders = \n new ObservableCollection<Order>(new []\n {\n new Order(1, 15),\n new Order(2, 15),\n new Order(3, 25),\n new Order(4, 27),\n new Order(5, 30),\n new Order(6, 75),\n new Order(7, 80),\n });\n\n //********************************************\n // We start using ObservableComputations here!\n Filtering<Order> expensiveOrders = orders.Filtering(o => o.Price > 25); \n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n expensiveOrders.CollectionChanged += (sender, eventArgs) =>\n {\n // see the changes (add, remove, replace, move, reset) here\n };\n\n // Start the changing...\n orders.Add(new Order(8, 30));\n orders.Add(new Order(9, 10));\n orders[0].Price = 60;\n orders[4].Price = 10;\n orders.Move(5, 1);\n orders[1] = new Order(10, 17);\n\n checkFiltering(orders, expensiveOrders); // Prints \"True\"\n\n Console.ReadLine();\n }\n\n static void checkFiltering(\n ObservableCollection<Order> orders, \n Filtering<Order> expensiveOrders)\n {\n Console.WriteLine(expensiveOrders.SequenceEqual(\n orders.Where(o => o.Price > 25)));\n }\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
167,635
<p>Let's say I 've added a library foo.so.1.1.1 to a path that is included in <code>/etc/ld.so.conf</code> When I run ldconfig on the system I get the links foo.so.1.1 and foo.so.1 to foo.so.1.1.1</p> <p>How can I change the behavior to also get the foo.so link to foo.so.1.1.1?</p>
[ { "answer_id": 167702, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 3, "selected": false, "text": "ln -s /usr/lib/foo.so.1.1.1 /usr/lib/foo.so\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6403/" ]
167,643
<p>How do I write the SQL code to INSERT (or UPDATE) an array of values (with probably an attendant array of fieldnames, or with a matrix with them both) without simple iteration?</p>
[ { "answer_id": 167738, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": 1, "selected": false, "text": "INSERT SELECT INSERT recipient_table (field1, field2)\nSELECT field1_from, field2_from\nFROM donor_table\nWHERE field1_from = 'condition'\n" }, { "answer_id": 196104, "author": "xnagyg", "author_id": 2622295, "author_profile": "https://Stackoverflow.com/users/2622295", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION dbo.Split(@String nvarchar(4000), @Delimiter char(1))\nreturns @Results TABLE (Items nvarchar(4000))\nas\nbegin\ndeclare @index int\ndeclare @slice nvarchar(4000)\n\nselect @index = 1\nif @String is null return\n\nwhile @index != 0\n\nbegin\nselect @index = charindex(@Delimiter,@String)\nif @index !=0\nselect @slice = left(@String,@index - 1)\nelse\nselect @slice = @String\n\ninsert into @Results(Items) values(@slice)\nselect @String = right(@String,len(@String) - @index)\nif len(@String) = 0 break\nend return\nend\n select * from dbo.split('a,b,c,d,e,f,g,h,i,j,k,l', ',')\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ]
167,657
<p>When IE8 is released, will the following code work to add a conditional stylesheet?</p> <pre><code>&lt;!--[if IE 8]&gt; &lt;link rel="stylesheet" type="text/css" href="ie-8.0.css" /&gt; &lt;![endif]--&gt; </code></pre> <p>I've read conflicting reports as to whether this works with the beta. I'm hoping someone can share their experience. Thanks.</p>
[ { "answer_id": 168131, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 5, "selected": false, "text": "http://127.0.0.1/mysite/mypage.php <-- IE8 by default (updated!)\nhttp://localhost/mysite/mypage.php <-- IE8 by default (updated!)\nhttp://machinename/mysite/mypage.php <-- IE7 by default\nhttp://192.168.100.x/mysite/mypage.php <-- IE7 by default\nhttp://google.com/ <-- IE8 by default\n javascript:\nvar vMode=document.documentMode;\nvar rMode='IE5 Quirks Mode';\nif(vMode==8){\n rMode='IE8 Standards Mode';\n} else if(vMode==7){\n rMode='IE7 Strict Mode';\n}\nalert('Rendering in: '+rMode);\n" }, { "answer_id": 1777148, "author": "Eze", "author_id": 216278, "author_profile": "https://Stackoverflow.com/users/216278", "pm_score": 0, "selected": false, "text": ".niceclass {some:properties;more:properties;} .parentclass .niceclass {some:properties;more:properties;} #parentselector .niceclass {some:properties;more:properties;}" }, { "answer_id": 1968690, "author": "Carsten", "author_id": 239495, "author_profile": "https://Stackoverflow.com/users/239495", "pm_score": 0, "selected": false, "text": "* + html #test[id] { color:lime } \n * + html #test,\n html+body #test,\n * html body #test\n { color:lime }\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13850/" ]
167,697
<p>We're working with a semi-centralized git repository here where I work. Each developer has their own subtree in the central git repository, so it looks something like this:</p> <pre>master alice/branch1 alice/branch2 bob/branch1 michael/feature release/1.0 release/1.1</pre> <p>Working locally in my tree I have <code>topic/feature</code>, which corresponds to <code>michael/feature</code> in the central tree.</p> <p>I've been using</p> <pre><code>git push origin topic/feature:michael/feature </code></pre> <p>to push my changes to the remote tree. However, this is cumbersome and prone to mistakes (e.g. omitting the developer name, misspelling the feature name, etc.).</p> <p>I'm looking for a cleaner way to do this. For instance, "<code>git push</code>". I suspect that setting a different remote with a modified fetch refspec will do it, but I'm not sure how exactly to do it. I'm also not sure how to modify my current branch definitions to use the different remote.</p> <p>My current <code>.git/config</code> looks something like:</p> <pre>[remote "origin"] url = git://central/git/project fetch = +refs/heads/*:refs/remotes/origin/* [branch "topic/feature"] remote = origin merge = refs/heads/michael/project</pre> <p><strong>Edit:</strong> I'd also like to apply this to pulls/fetches. But does the <code>branch.&lt;name&gt;.merge</code> take care of that?</p> <p>I'll continue to research this and post here if I find something, but I'm hoping to get some other good ideas.</p> <p><strong>Edit 2:</strong> I've decided I'll keep local and remote branch names the same. It appears it will be the least work and least prone to future problems.</p>
[ { "answer_id": 169110, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 2, "selected": false, "text": "push = refs/heads/master:master\npush = refs/heads/topic/feature:michael/feature\n" }, { "answer_id": 169777, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 3, "selected": true, "text": "git push git config remote.origin.push refs/heads/topic/BRANCH_NAME:michael/BRANCH_NAME\n" }, { "answer_id": 9693905, "author": "studgeek", "author_id": 255961, "author_profile": "https://Stackoverflow.com/users/255961", "pm_score": 1, "selected": false, "text": "git remote add heroku git@heroku.com:YOURAPPNAME.git\ngit checkout -b heroku -t heroku/master\n" }, { "answer_id": 64501952, "author": "Adwait Mathkari", "author_id": 9413125, "author_profile": "https://Stackoverflow.com/users/9413125", "pm_score": 2, "selected": false, "text": "git branch --set-upstream-to=origin/remoteBranch localBranch\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17688/" ]
167,705
<p>How do I load the edited <code>.emacs</code> file without restarting Emacs?</p>
[ { "answer_id": 7116603, "author": "tkf", "author_id": 264050, "author_profile": "https://Stackoverflow.com/users/264050", "pm_score": 3, "selected": false, "text": "*scratch* (load-file user-init-file)\n C-x C-e" }, { "answer_id": 9501113, "author": "Shantanu", "author_id": 1056532, "author_profile": "https://Stackoverflow.com/users/1056532", "pm_score": 1, "selected": false, "text": "C-x C-e" }, { "answer_id": 19201256, "author": "Geremia", "author_id": 1429450, "author_profile": "https://Stackoverflow.com/users/1429450", "pm_score": 3, "selected": false, "text": "M-x load-file ENTER\n~/.emacs\nENTER\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8522/" ]
167,735
<p>I am looking for a pseudo random number generator which would be specialized to work fast when it is given a seed before generating each number. Most generators I have seen so far assume you set seed once and then generate a long sequence of numbers. The only thing which looks somewhat similar to I have seen so far is Perlin Noise, but it generates too "smooth" data - for similar inputs it tends to produce similar results.</p> <p>The declaration of the generator should look something like:</p> <pre><code>int RandomNumber1(int seed); </code></pre> <p>Or:</p> <pre><code>int RandomNumber3(int seedX, int seedY, int seedZ); </code></pre> <p>I think having good RandomNumber1 should be enough, as it is possible to implement RandomNumber3 by hashing its inputs and passing the result into the RandomNumber1, but I wrote the 2nd prototype in case some implementation could use the independent inputs.</p> <p>The intended use for this generator is to use it for procedural content generator, like generating a forest by placing trees in a grid and determining a random tree species and random spatial offsets for each location.</p> <p>The generator needs to be very efficient (below 500 CPU cycles), because the procedural content is created in huge quantities in real time during rendering.</p>
[ { "answer_id": 167764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "uint32_t hash( uint32_t a)\n a = (a ^ 61) ^ (a >> 16);\n a = a + (a << 3);\n a = a ^ (a >> 4);\n a = a * 0x27d4eb2d;\n a = a ^ (a >> 15);\n return a;\n}\n" }, { "answer_id": 168078, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 2, "selected": false, "text": "std::tr1::ranlux3 #include <random>\n#include <iostream>\n#include <iterator>\n#include <functional>\n#include <algorithm>\n#include <ctime>\nusing namespace std;\nusing namespace std::tr1;\nint main(){\n random_device trueRand;\n ranlux3 rng(trueRand); // produces randomness out of thin air\n // see pseudo-random number generators\n uniform_int<> six(1,6); // distribution that maps to 1..6\n // see random number distributions\n variate_generator<ranlux3&, uniform_int<> >\n die(rng, six); // glues randomness with mapping\n\n // simulate rolling a die\n generate_n( ostream_iterator<int>(cout, \" \"), 10, ref(die));\n}\n 2 4 4 2 4 5 4 3 6 2\n" }, { "answer_id": 215818, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 2, "selected": false, "text": "v = 36969*(v & 65535) + (v >> 16);\nu = 18000*(u & 65535) + (u >> 16);\nreturn (v << 16) + (u & 65535);\n" }, { "answer_id": 1759161, "author": "mikera", "author_id": 214010, "author_profile": "https://Stackoverflow.com/users/214010", "pm_score": 0, "selected": false, "text": "/**\n * State for random number generation\n */\nprivate static volatile long state=xorShift64(System.nanoTime()|0xCAFEBABE);\n\n/**\n * Gets a long random value\n * @return Random long value based on static state\n */\npublic static long nextLong() {\n long a=state;\n state = xorShift64(a);\n return a;\n}\n\n/**\n * XORShift algorithm - credit to George Marsaglia!\n * @param a initial state\n * @return new state\n */\npublic static final long xorShift64(long a) {\n a ^= (a << 21);\n a ^= (a >>> 35);\n a ^= (a << 4);\n return a;\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16673/" ]
167,740
<p>I recently began profiling an osgi java application that I am writing using VisualVM. One thing I have noticed is that when the application starts sending data to a client (over JMS), the number of loaded classes starts increasing at a steady rate. The Heap size and the PermGen size remains constant, however. The number of classes never falls, even after it stops sending data. Is this a memory leak? I think it is, because the loaded classes have to be stored somewhere, however the heap and permgen never increase even after I run the application for several hours.</p> <p>For the screenshot of my profiling application go <a href="http://sites.google.com/site/javaperformacescreenshot/Home/profile.png" rel="noreferrer">here</a></p>
[ { "answer_id": 167971, "author": "Kyle", "author_id": 3335, "author_profile": "https://Stackoverflow.com/users/3335", "pm_score": 4, "selected": true, "text": "JAXBContext context = JAXBContext.newInstance(this.getClass());\n" }, { "answer_id": 168056, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 2, "selected": false, "text": "-XX:+CMSPermGenSweepingEnabled -XX:+CMSClassUnloadingEnabled\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3335/" ]
167,743
<p>What's a simple way to implement a c++ Win32 program to...<br /> - display an 800x600x24 uncompressed bitmap image<br /> - in a window without borders (the only thing visible is the image)<br /> - that closes after ten seconds<br /> - and doesn't use MFC</p>
[ { "answer_id": 167918, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 2, "selected": false, "text": "_ _ _ _ _ _ _" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191808/" ]
167,746
<p>I am trying to write a Windows Form and ASP.NET C# front-end and MSAccess backend for a pretty small database concept I have. </p> <p>I have written this application once before in just MSAccess but I now need the app and database to be in different places. I have now figured out (thanks to a StackOverflow user) that ADO will be a bad choice because it has to have a connection open all of the time. </p> <p>I bought Microsoft ADO.Net 2.0 Step-by-Step and I have read through some of it and understand (I think) the basic concepts at play in ADO.NET. (Datasets and the like)</p> <p>Where I get confused is the actual implementation. What I want to know is do any of you know of a C# project that has a database backend which is open source that I can go look at the code and see how they did it. I find I learn better that way. The book has a CD with code examples that I may turn to, but I would rather see real code in a real app. </p>
[ { "answer_id": 167918, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 2, "selected": false, "text": "_ _ _ _ _ _ _" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19802/" ]
167,752
<p>I would like to add a typing speed indicator just below the textarea we use on our contact form. It is just for fun and to give the user some interactivity with the page while they are completing the form.</p> <p>It should display the average speed while typing and keep the last average when the keystrokes are idle. When they leave the textarea the last average should stick.</p> <p>Ideally I would like to have a jQuery plugin if it is available.</p> <p>[Edit] this was originally for just a few of my websites. But after I posted the question it struck me how this would be a neat feature for SO. If you agree <a href="http://stackoverflow.uservoice.com/pages/general/suggestions/32755" rel="noreferrer">vote here</a></p>
[ { "answer_id": 167828, "author": "Jared", "author_id": 1980, "author_profile": "https://Stackoverflow.com/users/1980", "pm_score": -1, "selected": false, "text": "var lastrun = new Date();\ntextarea.onkeyup = function() {\n var words = textarea.value.split(' ');\n var minutes_since_last_check = somefunctiontogetminutesdifference(new Date(), lastrun);\n var wpm = (words.length-1)/minutes_since_last_check;\n //show the wpm in a div or something\n};\n" }, { "answer_id": 167902, "author": "enobrev", "author_id": 14651, "author_profile": "https://Stackoverflow.com/users/14651", "pm_score": 5, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n <title>Type Speed</title>\n <script type=\"text/javascript\" src=\"js/jquery-1.2.6.js\"></script>\n <style type=\"text/css\">\n form {\n margin: 20px auto;\n width: 500px;\n }\n\n #textariffic {\n width: 400px;\n height: 400px;\n font-size: 12px;\n font-family: monospace;\n line-height: 15px;\n }\n </style>\n <script type=\"text/javascript\">\n $(function() {\n $('textarea')\n .keyup(checkSpeed);\n });\n\n var iLastTime = 0;\n var iTime = 0;\n var iTotal = 0;\n var iKeys = 0;\n\n function checkSpeed() {\n iTime = new Date().getTime();\n\n if (iLastTime != 0) {\n iKeys++;\n iTotal += iTime - iLastTime;\n iWords = $('textarea').val().split(/\\s/).length;\n $('#CPM').html(Math.round(iKeys / iTotal * 6000, 2));\n $('#WPM').html(Math.round(iWords / iTotal * 6000, 2));\n }\n\n iLastTime = iTime;\n }\n\n </script>\n </head>\n <body>\n <form id=\"tipper\">\n <textarea id=\"textariffic\"></textarea>\n <p>\n <span class=\"label\">CPM</span>\n <span id=\"CPM\">0</span>\n </p>\n <p>\n <span class=\"label\">WPM</span>\n <span id=\"WPM\">0</span>\n </p>\n </form>\n </body>\n</html>\n" }, { "answer_id": 22908660, "author": "Xsi", "author_id": 1835606, "author_profile": "https://Stackoverflow.com/users/1835606", "pm_score": 2, "selected": false, "text": "<textarea id=\"b\" onblur=\"clc();\"></textarea>\n<script>\nt=0;\ndocument.getElementById('b').onkeypress=function()\n{\nt==0 ? s=new Date() : e=new Date();\nt=1;\n}\nfunction clc()\n{\nd = e.getTime() - s.getTime();\nc = b.value.length;\nb.value += \"\\n\"+c+\"s in \"+d+\"ms: \"+c/d+\" cpms\";\n}\n</script>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
167,760
<p>I have a class holding complex scientific computations. It is set up to only allow a user to create a properly instantiated case. To properly test the code, however, requires setting internal state variables directly, since the reference documents supply this data in their test cases. Done improperly, however, it can invalidate the state.<p> So I must have the ability, a member function, to set internal variables from the unit test programs. But I want to <b>strongly discourage</b> normal users from calling this function. (Yes, a determined user can muck with anything... but I don't want to <i>advertise</i> that there is a way to do something <i>wrong</i>.)<p> It would be nice to be able to tell Intellisense to not show the function, for instance.<p> The best solution I have at the moment is to just name the function something like: DangerousSet().<p> What other options do I have?<P> <b>Follow-Up</b><p> I found Amy B's answer most useful to my situation. Thanks!<br> Mufasa's suggestion to use reflection was great, but harder to implement (for me).<br> Chris' suggestion of using a decorator was good, but didn't pan out.<br> BFree's suggestion on XML is also good, and was already in use, but doesn't really solve the problem.<p> Finally, BillTheLizard's suggestion that the problem is in the source documents is not something I can control. International experts publish highly technical books and journal articles for use by their community. The fact that they don't address my particular needs is a fact of life. There simply are no alternative documents.</p>
[ { "answer_id": 167767, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 4, "selected": false, "text": "DangerousSet internal public DangerousSet [assembly:InternalsVisibleTo(\"YourTestAssembly\")] [assembly:InternalsVisibleTo(\"TestAssembly1\"), \n InternalsVisibleTo(\"TestAssembly2\")]\n" }, { "answer_id": 167769, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 0, "selected": false, "text": "protected" }, { "answer_id": 167770, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 3, "selected": false, "text": "[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n EditorBrowsableAttribute" }, { "answer_id": 168097, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "public class ComplexCalculation\n{\n protected int favoriteNumber;\n public int FavoriteNumber\n {\n get { return favoriteNumber; }\n }\n}\n public class ComplexCalculationTest : ComplexCalculation\n{\n public void SetFavoriteNumber(int newFavoriteNumber)\n {\n this.favoriteNumber = newFavoriteNumber;\n }\n}\n public void Test()\n {\n ComplexCalculationTest myTestObject = new ComplexCalculationTest();\n myTestObject.SetFavoriteNumber(3);\n ComplexCalculation myObject = myTestObject;\n\n if (myObject.FavoriteNumber == 3)\n Console.WriteLine(\"Win!\");\n\n }\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10722/" ]
167,761
<p>I'd like to be able to add a class to images that adds a border that makes them look like a stack of photos. Anyone know how to do this?</p> <p>Clarifications: Ideally something like the stack shown <a href="http://designreviver.com/tutorials/create-an-interactive-stack-of-photos/" rel="nofollow noreferrer">here</a> but it doesn't need to be interactive and only needs to work for a single photo. I also don't mind using javascript if needed (jQuery would be preferred though).</p>
[ { "answer_id": 167798, "author": "Mikezx6r", "author_id": 5382, "author_profile": "https://Stackoverflow.com/users/5382", "pm_score": 0, "selected": false, "text": "<div class=\"img-shadow\"><img ...></div>\n\n.img-shadow {style.css (line 456)\nbackground-color:#505050;\nfloat:left;\nmargin:5px 0 0 0;\n}\n.img-shadow img {style.css (line 461)\nbackground-color:#FFFFFF;\nborder:3px solid #000000;\ndisplay:block;\nmargin:-8px 8px 8px -8px;\npadding:10px;\nposition:relative;\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12842/" ]
167,772
<p>I have a Ruby on Rails application that I'm writing where a user has the option to edit an invoice. They need to be able to reassign the order of the rows. Right now I have an index column in the db which is used as the default sort mechanism. I just exposed that and allowed the user to edit it. </p> <p>This is not very elegant. I'd like the user to be able to drag and drop table rows. I've used Scriptaculous and Prototype a bit and am familiar with them. I've done drag and drop lists, but haven't done table rows quite like this. Anyone have any suggestions for not only reordering but capturing the reorder efficiently?</p> <p>Also, the user can dynamically create a new row in JS right now, so that row has to be reorderable as well. </p> <p>Bonus points if it can be done with RJS instead of direct JavaScript.</p>
[ { "answer_id": 167905, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "sortables.addItems(node);\n" }, { "answer_id": 167993, "author": "Mark S.", "author_id": 13968, "author_profile": "https://Stackoverflow.com/users/13968", "pm_score": 2, "selected": false, "text": "...\n<table id=\"invoices\">\n <thead>\n <tr>\n <th>Id</th>\n <th>Description</th>\n </tr>\n </thead>\n <tbody id=\"line_items\">\n <%= render :partial => 'invoice_line_item', :collection => @invoice.invoice_line_items.sort %>\n </tbody>\n</table>\n\n<%= sortable_element('line_items', {:url => {:action => :update_index}, :tag => :tr, :constraint => :vertical}) -%>\n...\n ...\ndef update_index\n params[\"line_items\"].each_with_index do |id, index|\n InvoiceLineItem.update(id, :index => index)\n end\n render :nothing => true\nend\n...\n" }, { "answer_id": 21474164, "author": "EpokK", "author_id": 1875004, "author_profile": "https://Stackoverflow.com/users/1875004", "pm_score": 0, "selected": false, "text": "Prototype Scriptaculous Sortable.create('yourTable', {\n tag: 'tr',\n handles: $$('a.move'),\n onUpdate: function() {\n console.log('onUpdate');\n }\n});\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13968/" ]
167,808
<p>I have created a user control to handle adding comments to certain business entities, like contacts and customers. Works great ... except for one issue.</p> <p>I am using a ListView control to edit and delete comments, and a separate area, on the same user control to add a new comment. All of this is wrapped in an UpdatePanel.</p> <p><img src="https://farm4.static.flickr.com/3239/2909377399_888d42b595.jpg?v=0" alt="Screenshot"></p> <p>Here is my scenario ... the user adds a new comment ... the page does a postback, the data is successfully saved, and the ListView control is updated to show the new comment. Now, if the user <strong>refreshes</strong> the browser, it will naturally postback again and will add another duplicate record. </p> <p>Any ideas on how best to prevent this?</p>
[ { "answer_id": 167832, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 0, "selected": false, "text": "Page.IsPostBack if(IsPostBack) {\n //do your data-saving code...\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
167,827
<p>Friends/family/etc ask me what I do and it always causes me pause while I think of how to explain it. They know what a software developer is but how can I explain what SCM is in 10 words?</p>
[ { "answer_id": 167992, "author": "John Ferguson", "author_id": 8312, "author_profile": "https://Stackoverflow.com/users/8312", "pm_score": 2, "selected": true, "text": "from many good parts:\none programme on your PC;\nlose track, get winter\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24881/" ]
167,844
<p>Disclaimer: I am new to Winforms.</p> <p>I need to declare a datatable that I can load with data when the main form loads. I then want to be able to reference the datatable from within events like when a button is clicked etc.</p> <p>Where/how should I declare this?</p>
[ { "answer_id": 168019, "author": "Saif Khan", "author_id": 23667, "author_profile": "https://Stackoverflow.com/users/23667", "pm_score": 0, "selected": false, "text": "Public \n\nClass Form3\n\nPrivate myTable as New DataTable\n\nPrivate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\nMsgBox(t.Rows.Count)\n\nEnd Sub\n\nPrivate Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click\n\nMsgBox(t.Rows.Count)\n\nEnd Sub\n\n\nEnd Class\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
167,852
<p>I am hosting a WCF service in a Windows Service on one of our servers. After making it work in basicHttpBinding and building a test client in .NET (which finally worked) I went along and try to access it from PHP using the SoapClient class. The final consumer will be a PHP site so I need to make it consumable in PHP.</p> <p>I got stumped when I had to enter the WSDL url in the constructor of the SoapClient class in the PHP code. Where is the WSDL? All I have is :</p> <p><a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> and <a href="http://172.27.7.123:8000/WordService/mex" rel="noreferrer">http://172.27.7.123:8000/WordService/mex</a></p> <p>None of these do not expose WSDL.</p> <p>Being a newbie in WCF I might have asked a dumb thing (or I might have a wrong assumption somewhere). Please be gentle :D</p> <p>And no, <a href="http://172.27.7.123:8000/WordService?wsdl" rel="noreferrer">http://172.27.7.123:8000/WordService?wsdl</a> does not show anything different than <a href="http://172.27.7.123:8000/WordService" rel="noreferrer">http://172.27.7.123:8000/WordService</a> :(</p> <p>Am I forced to host it in IIS? Am I forced to use a regular WebService?</p>
[ { "answer_id": 167968, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<system.serviceModel>\n <services>\n\n <service \n <!-- Namespace.ServiceClass implementation -->\n name=\"WcfService1.Service1\" \n\n <!-- User behaviour defined below -->\n behaviorConfiguration=\"SimpleServiceBehaviour\"> \n\n <endpoint \n address=\"\" \n binding=\"basicHttpBinding\"\n <!-- Namespace.Interface that defines our service contract -->\n contract=\"WcfService1.IService1\"/>\n\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"SimpleServiceBehaviour\">\n\n <serviceMetadata \n <!-- We allow HTTP GET -->\n httpGetEnabled=\"true\" \n\n <!-- Conform to WS-Policy 1.5 when generating metadata -->\n policyVersion=\"Policy15\"/>\n\n </behavior>\n </serviceBehaviors>\n </behaviors>\n</system.serviceModel>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1796/" ]
167,862
<p>One of the vagaries of my development system (Codegear C++Builder) is that some of the auto-generated headers insist on having... </p> <pre><code>using namespace xyzzy </code></pre> <p>...statements in them, which impact on my code when I least want or expect it.</p> <p>Is there a way I can somehow cancel/override a previous "using" statement to avoid this.</p> <p>Maybe...</p> <pre><code>unusing namespace xyzzy; </code></pre>
[ { "answer_id": 168007, "author": "jk.", "author_id": 21284, "author_profile": "https://Stackoverflow.com/users/21284", "pm_score": 6, "selected": false, "text": "using namespace {\n using namespace xyzzy;\n\n} // stop using namespace xyzzy here\n" }, { "answer_id": 168023, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 1, "selected": false, "text": "use use" }, { "answer_id": 168027, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": false, "text": "string x; // Doesn't work due to conflicting declarations\n::string y; // use the class from the global namespace\nstd::string z; // use the string class from the std namespace\n" }, { "answer_id": 168033, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 7, "selected": true, "text": "namespace codegear {\n #include \"codegear_header.h\"\n} // namespace codegear\n" }, { "answer_id": 4652630, "author": "cdelacroix", "author_id": 570553, "author_profile": "https://Stackoverflow.com/users/570553", "pm_score": 3, "selected": false, "text": "using namespace System;" }, { "answer_id": 43629955, "author": "Narendra kumawat", "author_id": 7918558, "author_profile": "https://Stackoverflow.com/users/7918558", "pm_score": 0, "selected": false, "text": "#include<iostream>\n#include<stdio.h>\nnamespace namespace1 {\n int t = 10;\n}\nnamespace namespace2 {\n int t = 20;\n}\nint main() {\nusing namespace namespace1;\n printf(\"%d\" , t);\n printf(\"%d\" , namespace2::t);\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
167,888
<p>I need to be able to GZip compress a file in an Excel VBA function. Specifically I need to be able to use the 'deflate' algorithm.</p> <p>Is there a way to do this without having to exec a command line application? With no dependency on external tools the code will be more robust.</p> <p>Ideally the code would make use of pre-installed VBA or COM library functions - I don't want to have to implement this logic myself or install DLLs etc.</p> <p>If possible, I want installation of the function to be as simple as adding a .xla to the available Excel Add-Ins. No DLLs, EXEs, registry entries etc. required.</p> <p><strong>Edit</strong> Can I make use of the .NET GZipStream to do this?</p>
[ { "answer_id": 167907, "author": "JPLemme", "author_id": 1019, "author_profile": "https://Stackoverflow.com/users/1019", "pm_score": 0, "selected": false, "text": "Sub main()\n ActiveWorkbook.Save\n Open \"macrotest.xls\" For Binary Access Read As #1\n Open \"newfile.zip\" For Binary Access Write As #2\n 'do your stuff here\n Close #2\n Close #1\nEnd Sub\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4023/" ]
167,904
<p>Say there are two possible solutions to a problem: the first is quick but hacky; the second is preferable but would take longer to implement. You need to solve the problem fast, so you decide to get the hack in place as quickly as you can, planning to start work on the better solution afterwards. The trouble is, as soon as the problem is alleviated, it plummets down the to-do list. You're still planning to put in the better solution at some point, but it's hard to justify implementing it right now. Suddenly you find you've spent five years using the less-than-perfect solution, cursing it the while.</p> <p>Does this sound familiar? I know it's happened more than once where I work. One colleague describes deliberately making a bad GUI so that it wouldn't be accidentally adopted long-term. Do you have a better strategy?</p>
[ { "answer_id": 169836, "author": "mm2001", "author_id": 19506, "author_profile": "https://Stackoverflow.com/users/19506", "pm_score": 1, "selected": false, "text": "HACK XXX HACK" }, { "answer_id": 205054, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 2, "selected": false, "text": "// TODO: Better solution required.\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
167,909
<p>I hate Physics, but I love software development. When I go back to school after Thanksgiving, I'll be taking two more quarters of Physics before I'm done with the horrid thing. I am currently reading postings on the F# units of measurement feature, but I've never used a language like F#. Would it be suitable to write applications so I can perhaps learn something about Physics while doing something I like?</p> <p>I'm interested in command-line applications (even those that I can just execute and have spit out an answer without needing inputs) for things like kinematics, planar motion, Newton's Laws, gravitation, work, energy, momentum and impulse, systems of particles, rotational kinematics and dynamics, angular momentum, static equilibrium, oscillatory motion, wave motion, sound, physical optics, electrostatics, Gauss' law, electric field and potential, capacitance, resistance, DC circuits, magnetic field, Ampere's law, and inductance.</p> <p>The reason I'm interested in F# is because of the units of measure functionality that the language provides.</p>
[ { "answer_id": 168110, "author": "Chris Smith", "author_id": 322, "author_profile": "https://Stackoverflow.com/users/322", "pm_score": 5, "selected": true, "text": "let distance : float<meters> = gravity * 3.0<seconds>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
167,916
<p>I have a few questions about optimizing this type of load.</p> <p>One builds a new table of data to be loaded into a partitioned table and then builds the indexes on this new table. </p> <ol> <li><p>Should you build the index with the COMPUTE STATISTICS option or use the Cascade option of the DBMS_Stats?</p></li> <li><p>Should you gather stats on the table before the swap or on the partition after the swap?</p></li> <li><p>If you do it after the swap and you specify the partition name in the parameter list, what interplay does the granularity parameter have? For instance, if I specify a partition name and then set granularity to 'GLOBAL AND PARTITION' does that do Global at all? Does it do <em>just</em> that one partition?</p></li> </ol>
[ { "answer_id": 168359, "author": "Adam Hawkes", "author_id": 6703, "author_profile": "https://Stackoverflow.com/users/6703", "pm_score": 0, "selected": false, "text": "DBMS_STATS COMPUTE STATISTICS" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
167,923
<p>This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.</p> <p>Just to be clear...regex <code>.*Dog.*</code> would take </p> <pre><code>Cat Dog My Dog Her Dog Mouse </code></pre> <p>and return </p> <pre><code>Cat Dog ::::: Pattern .*Dog.* repeats 2 more times. Mouse #!/usr/bin/env python # import re import types def remove_repeats (l_string, l_regex): """Take a string, remove similar lines and replace with a summary message. l_regex accepts strings and tuples. """ # Convert string to tuple. if type(l_regex) == types.StringType: l_regex = l_regex, for t in l_regex: r = '' p = '' for l in l_string.splitlines(True): if l.startswith('::::: Pattern'): r = r + l else: if re.search(t, l): # If line matches regex. m += 1 if m == 1: # If this is first match in a set of lines add line to file. r = r + l elif m &gt; 1: # Else update the message string. p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n' else: if p: # Write the message string if it has value. r = r + p p = '' m = 0 r = r + l if p: # Write the message if loop ended in a pattern. r = r + p p = '' l_string = r # Reset string to modified string. return l_string </code></pre>
[ { "answer_id": 168009, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": true, "text": "def rematcher(re_str, iterable):\n\n matcher= re.compile(re_str)\n in_match= 0\n for item in iterable:\n if matcher.match(item):\n if in_match == 0:\n yield item\n in_match+= 1\n else:\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n in_match= 0\n yield item\n if in_match > 1:\n yield \"%s repeats %d more times\\n\" % (re_str, in_match-1)\n\nimport sys, re\n\nfor line in rematcher(\".*Dog.*\", sys.stdin):\n sys.stdout.write(line)\n final_string= '\\n'.join(rematcher(\".*Dog.*\", your_initial_string.split(\"\\n\")))\n" }, { "answer_id": 168052, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env python\n#\n\nimport re\nimport types\n\ndef remove_repeats (l_string, l_regex):\n \"\"\"Take a string, remove similar lines and replace with a summary message.\n\n l_regex accepts strings/patterns or tuples of strings/patterns.\n \"\"\"\n\n # Convert string/pattern to tuple.\n if not hasattr(l_regex, '__iter__'):\n l_regex = l_regex,\n\n ret = []\n last_regex = None\n count = 0\n\n for line in l_string.splitlines(True):\n if last_regex:\n # Previus line matched one of the regexes\n if re.match(last_regex, line):\n # This one does too\n count += 1\n continue # skip to next line\n elif count > 1:\n ret.append(\"::::: Pattern %r repeats %d more times.\\n\" % (last_regex, count-1))\n count = 0\n last_regex = None\n\n ret.append(line)\n\n # Look for other patterns that could match\n for regex in l_regex:\n if re.match(regex, line):\n # Found one\n last_regex = regex\n count = 1\n break # exit inner loop\n\n return ''.join(ret)\n" }, { "answer_id": 1250162, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": ".*Dog.*\n Dog\n #! /usr/bin/env python\n\nimport re # regular expressions\nimport fileinput # read from STDIN or file\n\nmy_regex = '.*Dog.*'\nmy_matches = 0\n\nfor line in fileinput.input():\n line = line.strip()\n\n if re.search(my_regex, line):\n if my_matches == 0:\n print(line)\n my_matches = my_matches + 1\n else:\n if my_matches != 0:\n print('::::: Pattern %s repeats %i more times.' % (my_regex, my_matches - 1))\n print(line)\n my_matches = 0\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ]
167,927
<p>Can someone please provide an implementation of a C function that gets invoked to dump the current stack? It's for a x86 linux system. It can be invoked in 2 ways: explicitly by another function, or after a crash (probably as a trap/int handler). The output can be either to the screen or to a file, as indicated by a parameter (handle). A clear explanation/comments of how the stack is unwound would obviously be very helpful. Thank you.</p>
[ { "answer_id": 2360876, "author": "jschmier", "author_id": 203667, "author_profile": "https://Stackoverflow.com/users/203667", "pm_score": 1, "selected": false, "text": "backtrace() backtrace() backtrace()" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8638/" ]
167,946
<p>As part of the base class for some extensive unit testing, I am writing a helper function which recursively compares the nodes of one XmlDocument object to another in C# (.NET). Some requirements of this:</p> <ul> <li>The first document is the <strong>source</strong>, e.g. what I want the XML document to look like. Thus the second is the one I want to find differences in and it must not contain <em>extra</em> nodes not in the first document.</li> <li>Must throw an exception when too many significant differences are found, and it should be easily understood by a human glancing at the description.</li> <li>Child element order is important, attributes can be in any order.</li> <li>Some attributes are ignorable; specifically <code>xsi:schemaLocation</code> and <code>xmlns:xsi</code>, though I would like to be able to pass in which ones are.</li> <li>Prefixes for namespaces must match in both attributes and elements.</li> <li>Whitespace between elements is irrelevant.</li> <li>Elements will <em>either</em> have child elements <em>or</em> <code>InnerText</code>, but not both.</li> </ul> <p>While I'm scrapping something together: <strong>has anyone written such code and would it be possible to share it here?</strong></p> <p>On an aside, what would you call the first and second documents? I've been referring to them as "source" and "target", but it feels wrong since the <strong>source</strong> is what I want the <strong>target</strong> to look like, else I throw an exception.</p>
[ { "answer_id": 30056490, "author": "Two Cents", "author_id": 4866984, "author_profile": "https://Stackoverflow.com/users/4866984", "pm_score": 3, "selected": false, "text": "public bool XMLCompare(XElement primary, XElement secondary)\n{\n if (primary.HasAttributes) {\n if (primary.Attributes().Count() != secondary.Attributes().Count())\n return false;\n foreach (XAttribute attr in primary.Attributes()) {\n if (secondary.Attribute(attr.Name.LocalName) == null)\n return false;\n if (attr.Value.ToLower() != secondary.Attribute(attr.Name.LocalName).Value.ToLower())\n return false;\n }\n }\n if (primary.HasElements) {\n if (primary.Elements().Count() != secondary.Elements().Count())\n return false;\n for (var i = 0; i <= primary.Elements().Count() - 1; i++) {\n if (XMLCompare(primary.Elements().Skip(i).Take(1).Single(), secondary.Elements().Skip(i).Take(1).Single()) == false)\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 46117075, "author": "Chetan Mehra", "author_id": 1725131, "author_profile": "https://Stackoverflow.com/users/1725131", "pm_score": 0, "selected": false, "text": "private static bool compareXML(XmlNode node, XmlNode comparenode)\n {\n\n if (node.Value != comparenode.Value)\n return false;\n\n if (node.Attributes.Count>0)\n {\n foreach (XmlAttribute parentnodeattribute in node.Attributes)\n {\n string parentattributename = parentnodeattribute.Name;\n string parentattributevalue = parentnodeattribute.Value;\n if (parentattributevalue != comparenode.Attributes[parentattributename].Value)\n {\n return false;\n }\n\n }\n\n }\n\n if(node.HasChildNodes)\n {\n sortXML(comparenode);\n if (node.ChildNodes.Count != comparenode.ChildNodes.Count)\n return false;\n for(int i=0; i<node.ChildNodes.Count;i++)\n {\n\n string name = node.ChildNodes[i].LocalName;\n if (compareXML(node.ChildNodes[i], comparenode.ChildNodes[i]) == false)\n return false;\n }\n\n }\n\n\n\n return true;\n }\n private static void sortXML(XmlNode documentElement)\n {\n int i = 1;\n SortAttributes(documentElement.Attributes);\n SortElements(documentElement);\n foreach (XmlNode childNode in documentElement.ChildNodes)\n {\n sortXML(childNode);\n\n }\n }\n\n\n\n private static void SortElements(XmlNode rootNode)\n {\n\n\n\n for(int j = 0; j < rootNode.ChildNodes.Count; j++) {\n for (int i = 1; i < rootNode.ChildNodes.Count; i++)\n {\n if (String.Compare(rootNode.ChildNodes[i].Name, rootNode.ChildNodes[1 - 1].Name) < 0)\n {\n rootNode.InsertBefore(rootNode.ChildNodes[i], rootNode.ChildNodes[i - 1]);\n\n }\n\n\n }\n }\n // Console.WriteLine(j++);\n\n\n }\n private static void SortAttributes(XmlAttributeCollection attribCol)\n {\n if (attribCol == null)\n return;\n bool changed = true;\n while (changed)\n {\n changed = false;\n for (int i = 1; i < attribCol.Count; i++)\n {\n if (String.Compare(attribCol[i].Name, attribCol[i - 1].Name) < 0)\n {\n //Replace\n attribCol.InsertBefore(attribCol[i], attribCol[i - 1]);\n changed = true;\n\n }\n }\n }\n }\n" }, { "answer_id": 53870378, "author": "Mirek", "author_id": 823680, "author_profile": "https://Stackoverflow.com/users/823680", "pm_score": 3, "selected": false, "text": "XNode.DeepEquals var xDoc1 = XDocument.Parse(xmlString1);\nvar xDoc2 = XDocument.Parse(xmlString2);\n\nbool isSame = XNode.DeepEquals(xDoc1.Document, xDoc2.Document);\n//Assert.IsTrue(isSame);\n" }, { "answer_id": 66549508, "author": "Vikas Lalwani", "author_id": 3559462, "author_profile": "https://Stackoverflow.com/users/3559462", "pm_score": 1, "selected": false, "text": "public static bool CheckXMLDifference(string xmlInput, string xmlOutput)\n {\n Diff myDiff = DiffBuilder.Compare(Input.FromString(xmlInput))\n .WithTest(Input.FromString(xmlOutput))\n .CheckForSimilar().CheckForIdentical()\n .IgnoreComments()\n .IgnoreWhitespace().NormalizeWhitespace().Build();\n\n if(myDiff.Differences.Count() == 0)\n {\n // when there is no difference \n // files are identical, return true;\n return true;\n }\n else\n {\n //return false when there is 1 or more difference in file\n return false;\n }\n\n }\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
167,952
<p>Null or empty string -- is one better than the other to represent no data in a table column? (I specifically use MySQL, but I'm thinking this is system-independent.) Are there major advantages/disadvantages to using one over the other, or is it simply programmer preference?</p>
[ { "answer_id": 167981, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "select 1 from (select '' as col from dual) where col is null;\n" }, { "answer_id": 167986, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "field = '' field is null" }, { "answer_id": 168051, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "NULL NULL '' ''" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7596/" ]
167,954
<p>So I build an array of various dates. Birthdays, anniversaries, and holidays. I'd like to order the array by which one is happening next, essentially sort October to September (wrapping to next year)</p> <p>so if my array is </p> <pre><code>$a = ([0]=&gt;"1980-04-14", [1]=&gt;"2007-06-08", [2]=&gt;"2008-12-25", [3]=&gt;"1978-11-03") </code></pre> <p>I'd like to sort it so it is arranged</p> <pre><code>$a = ([0]=&gt;"1978-11-03", [1]=&gt;"2008-12-25", [2]=&gt;"1980-04-14", [3]=&gt;"2007-06-08") </code></pre> <p>because the november 'event' is the one that will happen next (based on it being october right now).</p> <p>I'm trying usort where my cmp function is </p> <pre><code>function cmp($a, $b) { $a_tmp = split("-", $a); $b_tmp = split("-", $b); return strcmp($a_tmp[1], $b_tmp[1]); } </code></pre> <p>I am not sure how to modify this to get my desired effect.</p>
[ { "answer_id": 167995, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": -1, "selected": false, "text": "$date1 = split(\"-\", $a);\n$date2 = split(\"-\", $b);\n$seconds1 = mktime(0,0,0,$date1[1],$date1[2],$date1[0]);\n$seconds2 = mktime(0,0,0,$date2[1],$date2[2],$date2[0]);\n// eliminate years\n$seconds1 %= 31536000;\n$seconds2 %= 31536000;\nreturn $seconds1 - $seconds2;\n" }, { "answer_id": 168002, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "#!/bin/perl -w\n\n# Sort sequence of dates by next occurrence of anniversary.\n# Today's \"birthdays\" count as low (will appear first in sequence)\n\nuse strict;\n\nmy $refdate = \"2008-10-05\";\n\nmy @list = (\n \"1980-04-14\", \"2007-06-08\",\n \"2008-12-25\", \"1978-11-03\",\n \"2008-10-04\", \"2008-10-05\",\n \"2008-10-06\", \"2008-02-29\"\n);\n\nsub date_on_or_after\n{\n my($actdate, $refdate) = @_;\n my($answer) = $actdate;\n if ($actdate lt $refdate) # String compare OK with ISO8601 format\n {\n my($act_yy, $act_mm, $act_dd) = split /-/, $actdate;\n my($ref_yy, $ref_mm, $ref_dd) = split /-/, $refdate;\n $ref_yy++ if ($act_mm < $ref_mm || ($act_mm == $ref_mm && $act_dd < $ref_dd));\n $answer = \"$ref_yy-$act_mm-$act_dd\";\n }\n return $answer;\n}\n\nsub anniversary_compare\n{\n my $r1 = date_on_or_after($a, $refdate);\n my $r2 = date_on_or_after($b, $refdate);\n return $r1 cmp $r2;\n}\n\nmy @result = sort anniversary_compare @list;\n\nprint \"Before:\\n\";\nprint \"* $_\\n\" foreach (@list);\nprint \"Reference date: $refdate\\n\";\nprint \"After:\\n\";\nprint \"* $_\\n\" foreach (@result);\n Before:\n* 1980-04-14\n* 2007-06-08\n* 2008-12-25\n* 1978-11-03\n* 2008-10-04\n* 2008-10-05\n* 2008-10-06\n* 2008-02-29\nReference date: 2008-10-05\nAfter:\n* 2008-10-05\n* 2008-10-06\n* 1978-11-03\n* 2008-12-25\n* 2008-02-29\n* 1980-04-14\n* 2007-06-08\n* 2008-10-04\n" }, { "answer_id": 168010, "author": "Jack B Nimble", "author_id": 3800, "author_profile": "https://Stackoverflow.com/users/3800", "pm_score": 0, "selected": false, "text": "function cmp($a, $b)\n{\n $a_tmp = explode('-', $a['date']);\n $b_tmp = explode('-', $b['date']);\n if ($a_tmp[1] < date('m')) {\n $a_tmp[1] += 12;\n }\n if ($b_tmp[1] < date('m')) {\n $b_tmp[1] += 12;\n }\n return strcmp($a_tmp[1] . $a_tmp[2], $b_tmp[1] . $b_tmp[2]);\n} \n" }, { "answer_id": 168079, "author": "Neil Williams", "author_id": 9617, "author_profile": "https://Stackoverflow.com/users/9617", "pm_score": 3, "selected": true, "text": "function relative_year_day($date) {\n $value = date('z', strtotime($date)) - date('z');\n\n if ($value < 0)\n $value += 365;\n\n return $value;\n}\n\nfunction cmp($a, $b)\n{\n $aValue = relative_year_day($a);\n $bValue = relative_year_day($b);\n\n if ($aValue == $bValue)\n return 0;\n\n return ($aValue < $bValue) ? -1 : 1;\n}\n\n$a = array(\"1980-04-14\", \"2007-06-08\",\n \"2008-12-25\", \"1978-11-03\");\n\nusort($a, \"cmp\");\n" }, { "answer_id": 168086, "author": "JimmyJ", "author_id": 2083, "author_profile": "https://Stackoverflow.com/users/2083", "pm_score": 0, "selected": false, "text": "for ($i=0; $i<count($a); $i++){\n if ($currentTimestamp > $a[$i]){\n unset($a[$i]);\n }\n}\n" }, { "answer_id": 180063, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 0, "selected": false, "text": "$a = array_combine(array_map('strtotime', $a), $a);\nksort($a);\n function dateCmp($date1, $date2) {\n return (strtotime($date1) > strtotime($date2))?1:-1;\n}\n\nusort($a, 'dateCmp');\n uasort($a, 'dateCmp');\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3800/" ]
167,990
<p>I am developing a small web app project (ColdFusion) and I am trying to keep my project split into multiple files during development, but deploy just one file on completion.</p> <p>I have references to external files, for instance:</p> <pre><code>&lt;script type="text/javascript" src="jquery-1.2.6.pack.js"&gt;&lt;/script&gt; &lt;link type="text/css" rel="stylesheet" href="project.css" /&gt; </code></pre> <p>And when I build my project, I want to have the files included and embedded within the single finished product file.</p> <pre><code>&lt;script type="text/javascript"&gt;eval(function(p,a,c,k,e,r) [...]&lt;/script&gt; &lt;style type="text/css"&gt;div{font:normal;} [...]&lt;/style&gt; </code></pre> <p>Anyway, it doesn't look like there is a basic way for Ant to do this. Anyone know?</p>
[ { "answer_id": 169052, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 2, "selected": false, "text": "<property\n name=\"filename\"\n value=\"jquery-1.2.6.pack.js\"\n/>\n\n<loadfile\n property=\"contents\"\n srcfile=\"${filename}\"\n/>\n\n<replace dir=\".\">\n <include name=\"index.cfm\"/>\n <replacetoken><![CDATA[<script type=\"text/javascript\" src=\"${filename}\"></script>]]></replacetoken>\n <replacevalue><![CDATA[<script type=\"text/javascript\">${contents}</script>]]></replacevalue>\n</replace>\n" }, { "answer_id": 175269, "author": "Nathan Strutz", "author_id": 5918, "author_profile": "https://Stackoverflow.com/users/5918", "pm_score": 2, "selected": true, "text": "<script language=\"groovy\" src=\"build.groovy\" />\n f = new File(\"${targetDir}/index.cfm\")\nfContent = f.text\nfContent = jsReplace(fContent)\nfContent = cssReplace(fContent)\nf.write(fContent)\n\n// JS Replacement\ndef jsReplace(htmlFileText) {\n println \"Groovy: Replacing Javascript includes\"\n // extract all matched javascript src links\n def jsRegex = /<script [^>]*src=\\\"([^\\\"]+)\\\"><\\/script>/\n def matcher = (htmlFileText =~ jsRegex)\n for (i in matcher) {\n // read external files in\n def includeText = new File(matcher.group(1)).text\n // sanitize the string for being regex replace string (dollar signs like jQuery/Prototype will screw it up)\n includeText = java.util.regex.Matcher.quoteReplacement(includeText)\n // weak compression (might as well)\n includeText = includeText.replaceAll(/\\/\\/.*/, \"\") // remove single-line comments (like this!)\n includeText = includeText.replaceAll(/[\\n\\r\\f\\s]+/, \" \") // replace all whitespace with single space\n // return content with embedded file\n htmlFileText = htmlFileText.replaceFirst('<script [^>]*src=\"'+ matcher.group(1) +'\"[^>]*></script>', '<script type=\"text/javascript\">'+ includeText+'</script>');\n }\n return htmlFileText;\n}\n\n// CSS Replacement\ndef cssReplace(htmlFileText) {\n println \"Groovy: Replacing CSS includes\"\n // extract all matched CSS style href links\n def cssRegex = /<link [^>]*href=\\\"([^\\\"]+)\\\"[^>]*>(<\\/link>)?/\n def matcher = (htmlFileText =~ cssRegex)\n for (i in matcher) {\n // read external files in\n def includeText = new File(matcher.group(1)).text\n // compress CSS\n includeText = includeText.replaceAll(/[\\n\\r\\t\\f\\s]+/, \" \")\n // sanitize the string for being regex replace string (dollar signs like jQuery/Prototype will screw it up)\n includeText = java.util.regex.Matcher.quoteReplacement(includeText)\n // return content with embedded file\n htmlFileText = htmlFileText.replaceFirst('<link [^>]*href=\"'+ matcher.group(1) +'\"[^>]*>(<\\\\/link>)?', '<style type=\\\"text/css\\\">'+ includeText+'</style>');\n }\n return htmlFileText;\n}\n" }, { "answer_id": 265841, "author": "Mnementh", "author_id": 21005, "author_profile": "https://Stackoverflow.com/users/21005", "pm_score": 2, "selected": false, "text": "<target name=\"replace\">\n <property name=\"js-filename\" value=\"jquery-1.2.6.pack.js\"/>\n <property name=\"css-filename\" value=\"project.css\"/>\n <loadfile property=\"js-file\" srcfile=\"${js-filename}\"/>\n <loadfile property=\"css-file\" srcfile=\"${css-filename}\"/>\n <replace file=\"input.txt\">\n <replacefilter token=\"&lt;script type=&quot;text/javascript&quot; src=&quot;${js-filename}&quot;&gt;&lt;/script&gt;\" value=\"&lt;script type=&quot;text/javascript&quot;&gt;${js-file}&lt;/script&gt;\"/>\n <replacefilter token=\"&lt;link type=&quot;text/css&quot; rel=&quot;stylesheet&quot; href=&quot;${css-filename}&quot; /&gt;\" value=\"&lt;style type=&quot;text/css&quot;&gt;${css-file}&lt;/style&gt;\"/>\n </replace>\n</target>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/167990", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5918/" ]
168,017
<p>Does any one know how can I convert a BSTR to an int in VC++ 2008</p> <p>Thanks in advance.</p>
[ { "answer_id": 168021, "author": "Scott Hanselman", "author_id": 6380, "author_profile": "https://Stackoverflow.com/users/6380", "pm_score": 3, "selected": false, "text": "VarI4FromStr HRESULT VarI4FromStr(\n _In_ LPCOLESTR strIn,\n _In_ LCID lcid,\n _In_ ULONG dwFlags,\n _Out_ LONG *plOut\n);\n" }, { "answer_id": 168028, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 1, "selected": false, "text": "BSTR s = SysAllocString(L\"42\");\nint i = _wtoi(s);\n" }, { "answer_id": 168029, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "int i = _wtoi( mybstr );\n" }, { "answer_id": 168034, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 5, "selected": true, "text": "wchar_t *" }, { "answer_id": 168040, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 1, "selected": false, "text": "#include <boost/lexical_cast.hpp>\n#include <iostream>\n\nint main()\n{\n wchar_t plop[] = L\"123\";\n int value = boost::lexical_cast<int>(plop);\n\n std::cout << value << std::endl;\n}\n" }, { "answer_id": 168209, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 1, "selected": false, "text": "std::wistringstream iss(mybstr); // Should convert from bstr to wchar_t* for the constructor\niss >> myint; // Puts the converted string value in to myint\nif(iss.bad() || iss.fail())\n{\n // conversion failed\n}\n" }, { "answer_id": 169151, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 0, "selected": false, "text": "BSTR wchar_t* SysStringLen(NULL) wcslen(NULL)" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24927/" ]
168,022
<p>I'm implementing a search algorithm (let's call it MyAlg) in a python package. Since the algorithm is super-duper complicated, the package has to contain an auxiliary class for algorithm options. Currently I'm developing the entire package by myself (and I'm not a programmer), however I expect 1-2 programmers to join the project later. This would be my first project that will involve external programmers. Thus, in order to make their lifes easier, how should I name this class: Options, OptionsMyAlg, MyAlgOptions or anything else?</p> <p>What would you suggest me to read in this topic except for <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/articles/Wrong.html</a> ?</p> <p>Thank you Yuri [cross posted from here: <a href="http://discuss.joelonsoftware.com/default.asp?design.4.684669.0" rel="nofollow noreferrer">http://discuss.joelonsoftware.com/default.asp?design.4.684669.0</a> will update the answers in both places]</p>
[ { "answer_id": 168085, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "Options open os Error from some_module import * open" }, { "answer_id": 168107, "author": "jblocksom", "author_id": 20626, "author_profile": "https://Stackoverflow.com/users/20626", "pm_score": 2, "selected": false, "text": "import myalg\n\nsearchOpts = myalg.Options()\nsearchOpts.whatever()\n\nmySearcher = myalg.SearchAlg(searchOpts)\nmySearcher.search(\"where's waldo?\")\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
168,037
<p>I have an application that takes the quality results for a manufacturing process and creates graphs both to show Pareto charts of the bad, and also to show production throughput.</p> <p>To automate the task of testing these statistical procedures I would like to deterministically be able to add records into the database and have the quality tech go to certain graphs and compare to a known good graph. But, I also would like to simulate the results so they would go into the database as if a user was running through the testing process.</p> <p>One idea I have had is to fill a list with i number good, j number bad1, k number bad 2, etc. And then somehow randomly sort the list before insertion into the database.</p> <p>So, my question, is there a standard algorithm to take a sorted list of values and create a randomly sorted list? </p>
[ { "answer_id": 168075, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 0, "selected": false, "text": "Random rnd = new Random();\nList<int> orderedList = new List<int>();\nList<int> randomList = new List<int>();\nwhile (orderedList.Count != 0)\n{\n int index = rnd.Next(0, orderedList.Count);\n randomList.Add(orderedList[index]);\n orderedList.RemoveAt(index);\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ]
168,046
<p>I'm maintaining a library that contains compiled objects that need to be linked into a 3rd party executable. sometimes the executable has been compiled for Solaris, sometimes as a 32bit Linux Application, sometimes its a 64bit linux application. What I'd love to do is pass one "path" to the library, and have the application then automatically pick up the right flavor of the library. It'd be OK if it only worked on linux, so that I could just define the path in terms of the OS. </p> <p>this particular case is for a library of PLI/VPI functions I want to link into a verilog simulator.</p> <p>What I have now is</p> <pre><code>root/path/${MYPLILIB_VER}/rootname/${MYPLIFLAVOR}/plilib.so </code></pre> <p>where flavor is one of</p> <pre><code>solaris linux linux64 </code></pre> <p>The flavor depends on the os, and if Linux, if running on a 64bit platform, it also depends on which version 32/64bit of the program I am running. I'm looking for a better way.. </p>
[ { "answer_id": 1005462, "author": "Steve K", "author_id": 121394, "author_profile": "https://Stackoverflow.com/users/121394", "pm_score": 0, "selected": false, "text": "LD_LIBRARY_PATH" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6314/" ]
168,073
<p>I'm currently writing a website that allows people to download Excel and text files. Is there a way to redirect to a different page when they click, so that we run javascript and do analytics (i.e. keep download count)? Currently, nothing prevents the user from simply right-clicking and saving. </p> <p>Edit: </p> <p>To be more specific, it would be nice for a single or double click of a file link to redirect to a temporary download page for analytics, then have the file be downloaded.</p>
[ { "answer_id": 168121, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 0, "selected": false, "text": "redirect(controller:\"book\",action:\"list\")\n" }, { "answer_id": 171574, "author": "mbrevoort", "author_id": 18228, "author_profile": "https://Stackoverflow.com/users/18228", "pm_score": 3, "selected": true, "text": "<a href=\"/path-to-download-file\" onclick=\"record_download('filename')\">myfile.txt</a>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6833/" ]
168,080
<p>I have a some JPA entities that inherit from one another and uses discriminator to determine what class to be created (untested as of yet).</p> <pre><code>@Entity(name="switches") @DiscriminatorColumn(name="type") @DiscriminatorValue(value="500") public class DmsSwitch extends Switch implements Serializable {} @MappedSuperclass public abstract class Switch implements ISwitch {} @Entity(name="switch_accounts") public class SwitchAccounts implements Serializable { @ManyToOne() @JoinColumn(name="switch_id") DmsSwitch _switch; } </code></pre> <p>So in the SwitchAccounts class I would like to use the base class Switch because I don't know which object will be created until runtime. How can I achieve this?</p>
[ { "answer_id": 168728, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 2, "selected": false, "text": "@Entity(name=\"switches\")\n@DiscriminatorColumn(name=\"type\")\n@DiscriminatorValue(value=\"400\")\npublic class Switch implements ISwitch {\n // Implementation details\n}\n\n@Entity(name=\"switches\")\n@DiscriminatorValue(value=\"500\")\npublic class DmsSwitch extends Switch implements Serializable {\n // implementation\n}\n\n@Entity(name=\"switches\")\n@DiscriminatorValue(value=\"600\")\npublic class SomeOtherSwitch extends Switch implements Serializable {\n // implementation\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
168,084
<p>Usually pagination queries look like this. Is there a better way instead of making two almost equal methods, one of which executing "select *..." and the other one "count *..."?</p> <pre><code>public List&lt;Cat&gt; findCats(String name, int offset, int limit) { Query q = session.createQuery("from Cat where name=:name"); q.setString("name", name); if (offset &gt; 0) { q.setFirstResult(offset); } if (limit &gt; 0) { q.setMaxResults(limit); } return q.list(); } public Long countCats(String name) { Query q = session.createQuery("select count(*) from Cat where name=:name"); q.setString("name", name); return (Long) q.uniqueResult(); } </code></pre>
[ { "answer_id": 168858, "author": "anjanb", "author_id": 11142, "author_profile": "https://Stackoverflow.com/users/11142", "pm_score": -1, "selected": false, "text": "Query q = sess.createQuery(\"from DomesticCat cat\");\nq.setFirstResult(20);\nq.setMaxResults(10);\nList cats = q.list();\n" }, { "answer_id": 169315, "author": "mike", "author_id": 19217, "author_profile": "https://Stackoverflow.com/users/19217", "pm_score": 2, "selected": false, "text": "mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name\n -> WHERE id > 100 LIMIT 10;\nmysql> SELECT FOUND_ROWS();\n" }, { "answer_id": 240003, "author": "tobinharris", "author_id": 1136215, "author_profile": "https://Stackoverflow.com/users/1136215", "pm_score": 2, "selected": false, "text": "var hql = \"from Item where i.Age > :age\"\nvar countHql = \"select count(*) \" + hql;\n\nIMultiQuery multiQuery = _session.CreateMultiQuery()\n .Add(s.CreateQuery(hql)\n .SetInt32(\"age\", 50).SetFirstResult(10))\n .Add(s.CreateQuery(countHql)\n .SetInt32(\"age\", 50));\n\nvar results = multiQuery.List();\nvar items = (IList<Item>) results[0];\nvar count = (long)((IList<Item>) results[1])[0];\n var itemSpec = (from i in Item where i.Age > age);\nvar count = itemSpec.Count();\nvar list = itemSpec.Skip(10).Take(10).AsList(); \n" }, { "answer_id": 767606, "author": "ruslan", "author_id": 89935, "author_profile": "https://Stackoverflow.com/users/89935", "pm_score": 1, "selected": false, "text": "select \n COUNT(Table.Column) OVER() as TotalRowsCount,\n Table.Column,\n Table.Column2\nfrom Table ...\n query.setMaxResults(pageNumber * itemsPerPage)\n ScrollableResults result = null;\ntry {\n result = query.scroll();\n int totalRowsNumber = result.getInteger(0);\n int from = // calculate the index of row to get for the expected page if any\n\n /*\n * Reading data form page and using Transformers.ALIAS_TO_ENTITY_MAP\n * to make life easier.\n */ \n}\nfinally {\n if (result != null) \n result.close()\n}\n" }, { "answer_id": 17148956, "author": "kommradHomer", "author_id": 489364, "author_profile": "https://Stackoverflow.com/users/489364", "pm_score": 0, "selected": false, "text": "SessionFactory sessionFactory = ((org.hibernate.Session) mEntityManager.getDelegate()).getSessionFactory();\nMySQLCalcFoundRowsInterceptor foundRowsInterceptor = new MySQLCalcFoundRowsInterceptor( sessionFactory );\nSession session = sessionFactory.openSession( foundRowsInterceptor );\n\ntry {\n org.hibernate.Query query = session.createQuery( ... ) // Note: JPA-QL, not createNativeQuery!\n query.setFirstResult( ... );\n query.setMaxResults( ... );\n\n List entities = query.list();\n long foundRows = foundRowsInterceptor.getFoundRows();\n\n ...\n\n} finally {\n\n // Disconnect() is good practice, but close() causes problems. Note, however, that\n // disconnect could lead to lazy-loading problems if the returned list of entities has\n // lazy relations\n\n session.disconnect();\n}\n" }, { "answer_id": 26499062, "author": "Yinzara", "author_id": 1304288, "author_profile": "https://Stackoverflow.com/users/1304288", "pm_score": 3, "selected": false, "text": "<bean id=\"foundRowCalculator\" class=\"my.hibernate.classes.MySQLCalcFoundRowsInterceptor\" />\n <!-- p:sessionFactoryBeanName=\"mySessionFactory\"/ -->\n\n<bean id=\"mySessionFactory\"\n class=\"org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean\"\n p:dataSource-ref=\"dataSource\"\n p:packagesToScan=\"my.hibernate.classes\"\n p:entityInterceptor-ref=\"foundRowCalculator\"/>\n package my.hibernate.classes;\n\npublic class PagedResponse<T> {\n public final List<T> items;\n public final int total;\n public PagedResponse(List<T> items, int total) {\n this.items = items;\n this.total = total;\n }\n}\n package my.hibernate.classes;\n\nimport org.hibernate.Criteria;\nimport org.hibernate.Query;\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic abstract class BaseDAO {\n\n @Autowired\n private MySQLCalcFoundRowsInterceptor rowCounter;\n\n public <T> PagedResponse<T> getPagedResponse(Criteria crit, int firstResult, int maxResults) {\n rowCounter.setCalcFoundRows(true);\n try {\n @SuppressWarnings(\"unchecked\")\n return new PagedResponse<T>(\n crit.\n setFirstResult(firstResult).\n setMaxResults(maxResults).\n list(),\n rowCounter.getFoundRows());\n } finally {\n rowCounter.reset();\n }\n }\n\n public <T> PagedResponse<T> getPagedResponse(Query query, int firstResult, int maxResults) {\n rowCounter.setCalcFoundRows(true);\n try {\n @SuppressWarnings(\"unchecked\")\n return new PagedResponse<T>(\n query.\n setFirstResult(firstResult).\n setMaxResults(maxResults).\n list(),\n rowCounter.getFoundRows());\n } finally {\n rowCounter.reset();\n }\n }\n}\n package my.hibernate.classes;\n\nimport org.hibernate.SessionFactory;\nimport org.hibernate.criterion.Restrictions\nimport org.springframework.beans.factory.annotation.Autowired;\n\npublic class MyEntityDAO extends BaseDAO {\n\n @Autowired\n private SessionFactory sessionFactory;\n\n public PagedResponse<MyEntity> getPagedEntitiesWithPropertyValue(String propVal, int firstResult, int maxResults) {\n return getPagedResponse(\n sessionFactory.\n getCurrentSession().\n createCriteria(MyEntity.class).\n add(Restrictions.eq(\"prop\", propVal)),\n firstResult, \n maxResults);\n }\n}\n package my.hibernate.classes;\n\nimport java.io.IOException;\nimport java.sql.Connection;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\nimport org.hibernate.EmptyInterceptor;\nimport org.hibernate.HibernateException;\nimport org.hibernate.SessionFactory;\nimport org.hibernate.Transaction;\nimport org.hibernate.jdbc.Work;\nimport org.springframework.beans.BeansException;\nimport org.springframework.beans.factory.BeanFactory;\nimport org.springframework.beans.factory.BeanFactoryAware;\n\npublic class MySQLCalcFoundRowsInterceptor extends EmptyInterceptor implements BeanFactoryAware {\n\n\n\n /**\n * \n */\n private static final long serialVersionUID = 2745492452467374139L;\n\n //\n // Private statics\n //\n\n private final static String SELECT_PREFIX = \"select \";\n\n private final static String CALC_FOUND_ROWS_HINT = \"SQL_CALC_FOUND_ROWS \";\n\n private final static String SELECT_FOUND_ROWS = \"select FOUND_ROWS()\";\n\n //\n // Private members\n //\n private SessionFactory sessionFactory;\n\n private BeanFactory beanFactory;\n\n private String sessionFactoryBeanName;\n\n private ThreadLocal<Boolean> mCalcFoundRows = new ThreadLocal<Boolean>();\n\n private ThreadLocal<Integer> mSQLStatementsPrepared = new ThreadLocal<Integer>() {\n @Override\n protected Integer initialValue() {\n return Integer.valueOf(0);\n }\n };\n\n private ThreadLocal<Integer> mFoundRows = new ThreadLocal<Integer>();\n\n\n\n private void init() {\n if (sessionFactory == null) {\n if (sessionFactoryBeanName != null) {\n sessionFactory = beanFactory.getBean(sessionFactoryBeanName, SessionFactory.class);\n } else {\n try {\n sessionFactory = beanFactory.getBean(\"sessionFactory\", SessionFactory.class);\n } catch (RuntimeException exp) {\n\n }\n if (sessionFactory == null) {\n sessionFactory = beanFactory.getBean(SessionFactory.class); \n }\n }\n }\n }\n\n @Override\n public String onPrepareStatement(String sql) {\n if (mCalcFoundRows.get() == null || !mCalcFoundRows.get().booleanValue()) {\n return sql;\n }\n switch (mSQLStatementsPrepared.get()) {\n\n case 0: {\n mSQLStatementsPrepared.set(mSQLStatementsPrepared.get() + 1);\n\n // First time, prefix CALC_FOUND_ROWS_HINT\n\n StringBuilder builder = new StringBuilder(sql);\n int indexOf = builder.indexOf(SELECT_PREFIX);\n\n if (indexOf == -1) {\n throw new HibernateException(\"First SQL statement did not contain '\" + SELECT_PREFIX + \"'\");\n }\n\n builder.insert(indexOf + SELECT_PREFIX.length(), CALC_FOUND_ROWS_HINT);\n return builder.toString();\n }\n\n case 1: {\n mSQLStatementsPrepared.set(mSQLStatementsPrepared.get() + 1);\n\n // Before any secondary selects, capture FOUND_ROWS. If no secondary\n // selects are\n // ever executed, getFoundRows() will capture FOUND_ROWS\n // just-in-time when called\n // directly\n\n captureFoundRows();\n return sql;\n }\n\n default:\n // Pass-through untouched\n return sql;\n }\n }\n\n public void reset() {\n if (mCalcFoundRows.get() != null && mCalcFoundRows.get().booleanValue()) {\n mSQLStatementsPrepared.remove();\n mFoundRows.remove();\n mCalcFoundRows.remove();\n }\n }\n\n @Override\n public void afterTransactionCompletion(Transaction tx) {\n reset();\n }\n\n public void setCalcFoundRows(boolean calc) {\n if (calc) {\n mCalcFoundRows.set(Boolean.TRUE);\n } else {\n reset();\n }\n }\n\n public int getFoundRows() {\n if (mCalcFoundRows.get() == null || !mCalcFoundRows.get().booleanValue()) {\n throw new IllegalStateException(\"Attempted to getFoundRows without first calling 'setCalcFoundRows'\");\n }\n if (mFoundRows.get() == null) {\n captureFoundRows();\n }\n\n return mFoundRows.get();\n }\n\n //\n // Private methods\n //\n\n private void captureFoundRows() {\n init();\n\n // Sanity checks\n\n if (mFoundRows.get() != null) {\n throw new HibernateException(\"'\" + SELECT_FOUND_ROWS + \"' called more than once\");\n }\n\n if (mSQLStatementsPrepared.get() < 1) {\n throw new HibernateException(\"'\" + SELECT_FOUND_ROWS + \"' called before '\" + SELECT_PREFIX + CALC_FOUND_ROWS_HINT + \"'\");\n }\n\n // Fetch the total number of rows\n\n sessionFactory.getCurrentSession().doWork(new Work() {\n @Override\n public void execute(Connection connection) throws SQLException {\n final Statement stmt = connection.createStatement();\n ResultSet rs = null;\n try {\n rs = stmt.executeQuery(SELECT_FOUND_ROWS);\n if (rs.next()) {\n mFoundRows.set(rs.getInt(1));\n } else {\n mFoundRows.set(0);\n }\n } finally {\n if (rs != null) {\n rs.close();\n }\n try {\n stmt.close();\n } catch (RuntimeException exp) {\n\n }\n }\n }\n });\n }\n\n public void setSessionFactoryBeanName(String sessionFactoryBeanName) {\n this.sessionFactoryBeanName = sessionFactoryBeanName;\n }\n\n @Override\n public void setBeanFactory(BeanFactory arg0) throws BeansException {\n this.beanFactory = arg0;\n }\n\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
168,116
<p>Here's a link to Windows <a href="http://msdn.microsoft.com/en-us/library/ms683218(VS.85).aspx" rel="nofollow noreferrer">documentation</a>.</p> <p>Basically I would like to get similar data, but on Linux. If not all is possible, then at least some parts.</p>
[ { "answer_id": 168123, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 1, "selected": false, "text": "/proc/<PID>/ man 5 proc" }, { "answer_id": 168693, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 2, "selected": false, "text": "/proc/ /io" }, { "answer_id": 170842, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 3, "selected": true, "text": "CONFIG\\_TASK\\_IO\\_ACCOUNTING" }, { "answer_id": 171216, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 1, "selected": false, "text": "CONFIG_TASK_IO_ACCOUNTING" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9403/" ]
168,119
<p>I have a pretty unusual problem (for me). I am writing an application that will allow a user to change their system time forward or back either by explicit date (change my date to 6/3/1955) or by increment using buttons (go forward 1 month).</p> <p>I'm writing this to help some of my users test some software that requires jumps like this in order to simulate real world usage of a billing system.</p> <p>Changing the time in Delphi is of course very easy:</p> <pre><code>SetDateTime(2008,05,21,16,07,21,00); </code></pre> <p>But I'm not sure if Delphi (2006) has any built in helpers for date math, which is one of my least favorite things :)</p> <p>Any suggestions for the best way to handle this? I'd prefer to stay native as the winapi datetime calls suck.</p> <p>Thanks!</p>
[ { "answer_id": 190434, "author": "user26293", "author_id": 26293, "author_profile": "https://Stackoverflow.com/users/26293", "pm_score": 3, "selected": false, "text": "procedure SetSystemDateTime(aDateTime: TDateTime);\nvar\n lSystemTime: TSystemTime;\n lTimeZone: TTimeZoneInformation;\n begin\n GetTimeZoneInformation(lTimeZone);\n aDateTime := aDateTime + (lTimeZone.Bias / 1440);\n DateTimeToSystemTime(aDateTime, lSystemTime);\n setSystemTime(lSystemTime);\nend;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ]
168,150
<p>I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.</p> <p>I understand the usage as it pertains to LINQ queries and I looked at <a href="https://stackoverflow.com/questions/48668/how-should-anonymous-types-be-used-in-c">this SO post</a> which asked a similar question. Most of the examples I've seen on the net are related to LINQ queries, which is cool. I saw some somewhat contrived examples too but not really anything where I saw a lot of value. </p> <p>Do you have a novel use for anonymous types where you think it really provides you some utility?</p>
[ { "answer_id": 168159, "author": "Giovanni Galbo", "author_id": 4050, "author_profile": "https://Stackoverflow.com/users/4050", "pm_score": 2, "selected": false, "text": "var x = new { a = 1, b = 2 };\n" }, { "answer_id": 172629, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 4, "selected": true, "text": "foreach Dictionary<int, string> employees = new Dictionary<int, string>\n{\n { 1, \"Bob\" },\n { 2, \"Alice\" },\n { 3, \"Fred\" },\n};\n\n// standard iteration\nforeach (var pair in employees)\n Console.WriteLine(\"ID: {0}, Name: {1}\", pair.Key, pair.Value);\n\n// alias Key/Value as ID/Name\nforeach (var emp in employees.Select(p => new { ID = p.Key, Name = p.Value }))\n Console.WriteLine(\"ID: {0}, Name: {1}\", emp.ID, emp.Name);\n foreach ID Name" }, { "answer_id": 172674, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 2, "selected": false, "text": "\nHtml.ActionLink(\"A Link\", \"Resolve\", new { onclick = \"someJavascriptFn();\" })\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7862/" ]
168,169
<p>Has anyone else seen people do this:</p> <pre><code>private string _name; public string Name{ get{ return _name; } set{ _name = value;}}</code></pre> <p>I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?</p>
[ { "answer_id": 168221, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 6, "selected": true, "text": "public string Name { get; set; }\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19038/" ]
168,171
<p>Can someone provide a regular expression for parsing name/value pairs from a string? The pairs are separated by commas, and the value can optionally be enclosed in quotes. For example:</p> <pre><code>AssemblyName=foo.dll,ClassName="SomeClass",Parameters="Some,Parameters" </code></pre>
[ { "answer_id": 168196, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 6, "selected": true, "text": "/([^=,]*)=(\"[^\"]*\"|[^,\"]*)/\n /((?:\"[^\"]*\"|[^=,])*)=((?:\"[^\"]*\"|[^=,])*)/\n\nkey=value,\"key with \"\" in it\"=\"value with \"\" in it\",key=value\" \"with\" \"spaces\n /([^=,]*)=(\"(?:\\\\.|[^\"\\\\]+)*\"|[^,\"]*)/\n\nkey=value,key=\"value\",key=\"val\\\"ue\"\n /((?:\\\\.|[^=,]+)*)=(\"(?:\\\\.|[^\"\\\\]+)*\"|(?:\\\\.|[^,\"\\\\]+)*)/\n\nkey=value,key=\"value\",key=\"val\\\"ue\",ke\\,y=val\\,ue\n" }, { "answer_id": 168358, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "/\\s*([^=,\\s]+)\\s*=\\s*(?:\"((?:[^\"]|\"\")*)\"|([^,\"]*))\\s*,?/\n #!/bin/perl -w\n\nuse strict;\nmy $qr = qr/\\s*([^=,\\s]+)\\s*=\\s*(?:\"((?:[^\"]|\"\")*)\"|([^,\"]*))\\s*,?/;\n\nwhile (<>)\n{\n while (m/$qr/)\n {\n print \"1= $1, 2 = $2, 3 = $3\\n\";\n $_ =~ s/$qr//;\n }\n}\n" }, { "answer_id": 209317, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "Perl 5.10 %+ perlretut" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]
168,173
<p>I have a webpage that pulls information from a database, converts it to .csv format, and writes the file to the HTTPResponse. </p> <pre><code>string csv = GetCSV(); Response.Clear(); Response.ContentType = "text/csv"; Response.Write(csv); </code></pre> <p>This works fine, and the file is sent to the client with no problems. However, when the file is sent to the client, the name of the current page is used, instead of a more friendly name (like "data.csv").</p> <p><img src="https://ktrauberman.files.wordpress.com/2008/10/exportcsv.gif" alt="alt text"></p> <p>My question is, how can I change the name of the file that is written to the output stream without writing the file to disk and redirecting the client to the file's url? </p> <p><strong>EDIT: Thanks for the responses guys. I got 4 of the same response, so I just chose the first one as the answer.</strong></p>
[ { "answer_id": 168182, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": true, "text": "Response.AddHeader(\"content-disposition\", \"attachment; filename=NewFileName.csv\");\n" }, { "answer_id": 168187, "author": "Matt Lacey", "author_id": 1755, "author_profile": "https://Stackoverflow.com/users/1755", "pm_score": 2, "selected": false, "text": "Response.AddHeader(\"content-disposition\", \"attachment; filename=File.doc\")\n" }, { "answer_id": 168188, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 2, "selected": false, "text": "Content-Disposition: attachment; filename=data.csv\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21461/" ]
168,214
<p>What is the easiest way to encode a PHP string for output to a JavaScript variable?</p> <p>I have a PHP string which includes quotes and newlines. I need the contents of this string to be put into a JavaScript variable.</p> <p>Normally, I would just construct my JavaScript in a PHP file, à la:</p> <pre><code>&lt;script&gt; var myvar = "&lt;?php echo $myVarValue;?&gt;"; &lt;/script&gt; </code></pre> <p>However, this doesn't work when <code>$myVarValue</code> contains quotes or newlines.</p>
[ { "answer_id": 168255, "author": "Adam", "author_id": 1366, "author_profile": "https://Stackoverflow.com/users/1366", "pm_score": -1, "selected": false, "text": "<script>\n var myvar = {$MyVarValue};\n</script>\n" }, { "answer_id": 168265, "author": "Chris MacDonald", "author_id": 18146, "author_profile": "https://Stackoverflow.com/users/18146", "pm_score": 1, "selected": false, "text": "string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )\n * '&' (ampersand) becomes '&amp;'\n* '\"' (double quote) becomes '&quot;' when ENT_NOQUOTES is not set.\n* ''' (single quote) becomes '&#039;' only when ENT_QUOTES is set.\n* '<' (less than) becomes '&lt;'\n* '>' (greater than) becomes '&gt;'\n" }, { "answer_id": 168272, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 5, "selected": false, "text": "function escapeJavaScriptText($string)\n{\n return str_replace(\"\\n\", '\\n', str_replace('\"', '\\\"', addcslashes(str_replace(\"\\r\", '', (string)$string), \"\\0..\\37'\\\\\")));\n}\n" }, { "answer_id": 168332, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n myvar = unescape('<?=rawurlencode($myvar)?>');\n</script>\n" }, { "answer_id": 169035, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 10, "selected": true, "text": "<script>\n var myvar = <?php echo json_encode($myVarValue); ?>;\n</script>\n $myVarValue json_encode </script>" }, { "answer_id": 442949, "author": "pr1001", "author_id": 46768, "author_profile": "https://Stackoverflow.com/users/46768", "pm_score": 5, "selected": false, "text": "<script>\n var myvar = decodeURIComponent(\"<?php echo rawurlencode($myVarValue); ?>\");\n</script>\n rawurlencode() decodeURIComponent()" }, { "answer_id": 2426927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "function escapeJavaScriptText($string) \n{ \n return str_replace(\"\\n\", '\\n', str_replace('\"', '\\\"', addcslashes(str_replace(\"\\r\", '', (string)$string), \"\\0..\\37'\\\\\"))); \n} \n" }, { "answer_id": 3580539, "author": "ioTus", "author_id": 432448, "author_profile": "https://Stackoverflow.com/users/432448", "pm_score": -1, "selected": false, "text": "$someString\n <form id=\"pagePhpVars\" method=\"post\">\n<input type=\"hidden\" name=\"phpString1\" id=\"phpString1\" value=\"'.$someString.'\" />\n</form>\n <script type=\"text/javascript\" charset=\"UTF-8\">\n var moonUnitAlpha = document.getElementById('phpString1').value;\n</script>\n" }, { "answer_id": 5763433, "author": "giraff", "author_id": 75017, "author_profile": "https://Stackoverflow.com/users/75017", "pm_score": 4, "selected": false, "text": "function javascript_escape($str) {\n $new_str = '';\n\n $str_len = strlen($str);\n for($i = 0; $i < $str_len; $i++) {\n $new_str .= '\\\\x' . sprintf('%02x', ord(substr($str, $i, 1)));\n }\n\n return $new_str;\n}\n json_encode() \" <div onclick=\"alert(???)\" />\n" }, { "answer_id": 12971648, "author": "Craig Francis", "author_id": 6632, "author_profile": "https://Stackoverflow.com/users/6632", "pm_score": 2, "selected": false, "text": "addslashes() </script> <?php\n $value = 'XXX</script><script>alert(document.cookie);</script>';\n?>\n\n<script type=\"text/javascript\">\n var foo = <?= json_encode($value) ?>; // Use this\n var foo = '<?= addslashes($value) ?>'; // Avoid, allows XSS!\n</script>\n" }, { "answer_id": 13627734, "author": "Kld", "author_id": 1551411, "author_profile": "https://Stackoverflow.com/users/1551411", "pm_score": 3, "selected": false, "text": "<script>\nvar myVar = <?php echo json_encode($myVarValue); ?>;\n</script>\n <script>\nvar myVar = <?= json_encode($myVarValue) ?>;\n</script>\n" }, { "answer_id": 21003517, "author": "Ry-", "author_id": 707111, "author_profile": "https://Stackoverflow.com/users/707111", "pm_score": 2, "selected": false, "text": "data-* function inline_json_encode($obj) {\n return str_replace('<!--', '<\\!--', json_encode($obj));\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13238/" ]
168,218
<p>I was considering creating a separate SQLite database for certain apps on a Django project.<br> However, I did not want to use direct SQLite access if possible. Django-style ORM access to these database would be ideal.<br> Is this possible?</p> <p>Thank you.</p>
[ { "answer_id": 170251, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "QuerySet Query __init__() QuerySet query django.db.models.sql.Query __init__() Query connection django.db.backends.BaseDatabaseWrapper get_query_set() QuerySet" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143732/" ]
168,236
<p>I am trying to set attributes for an IFRAME html control from the code-behind aspx.cs file.</p> <p>I came across a <a href="https://web.archive.org/web/20210128094503/http://geekswithblogs.net/ranganh/archive/2005/04/25/37635.aspx" rel="nofollow noreferrer">post</a> that says you can use FindControl to find the non-asp controls using:</p> <p>The aspx file contains:</p> <pre><code>&lt;iframe id=&quot;contentPanel1&quot; runat=&quot;server&quot; /&gt; </code></pre> <p>and then the code-behind file contains:</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { HtmlControl contentPanel1 = (HtmlControl)this.FindControl(&quot;contentPanel1&quot;); if (contentPanel1 != null) contentPanel1.Attributes[&quot;src&quot;] = &quot;http://www.stackoverflow.com&quot;; } </code></pre> <p>Except that it's not finding the control, contentPanel1 is null.</p> <hr /> <p><strong>Update 1</strong></p> <p>Looking at the rendered html:</p> <pre><code>&lt;iframe id=&quot;ctl00_ContentPlaceHolder1_contentPanel1&quot;&gt;&lt;/iframe&gt; </code></pre> <p>i tried changing the code-behind to:</p> <pre><code>HtmlControl contentPanel1 = (HtmlControl)this.FindControl(&quot;ctl00_ContentPlaceHolder1_contentPanel1&quot;); if (contentPanel1 != null) contentPanel1.Attributes[&quot;src&quot;] = &quot;http://www.clis.com&quot;; </code></pre> <p>But it didn't help.</p> <p>i am using a MasterPage.</p> <hr /> <p><strong>Update 2</strong></p> <p>Changing the aspx file to:</p> <pre><code>&lt;iframe id=&quot;contentPanel1&quot; name=&quot;contentPanel1&quot; runat=&quot;server&quot; /&gt; </code></pre> <p>also didn't help</p> <hr /> <p><strong>Answer</strong></p> <p>The answer is obvious, and unworthy of even asking the original question. If you have the aspx code:</p> <pre><code>&lt;iframe id=&quot;contentPanel1&quot; runat=&quot;server&quot; /&gt; </code></pre> <p>and want to access the iframe from the code-behind file, you just access it:</p> <pre><code>this.contentPanel1.Attributes[&quot;src&quot;] = &quot;http://www.stackoverflow.com&quot;; </code></pre>
[ { "answer_id": 168286, "author": "Joe Ratzer", "author_id": 4092, "author_profile": "https://Stackoverflow.com/users/4092", "pm_score": 1, "selected": false, "text": "this.Master.FindControl(\"ContentId\").FindControl(\"controlId\")\n" }, { "answer_id": 168306, "author": "RyanFetz", "author_id": 23776, "author_profile": "https://Stackoverflow.com/users/23776", "pm_score": 0, "selected": false, "text": " protected virtual Control FindControlRecursive(Control root, String id)\n {\n if (root.ID == id) { return root; }\n foreach (Control c in root.Controls)\n {\n Control t = FindControlRecursive(c, id);\n if (t != null)\n {\n return t;\n }\n }\n return null;\n }\n" }, { "answer_id": 168321, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 5, "selected": true, "text": "\ncontentPanel1.Attribute = value;\n" }, { "answer_id": 9170096, "author": "Mark Ibanez", "author_id": 1193662, "author_profile": "https://Stackoverflow.com/users/1193662", "pm_score": 4, "selected": false, "text": "<iframe id=\"ContentIframe\" runat=\"server\"></iframe>\n ContentIframe.Attributes[\"src\"] = \"stackoverflow.com\";\n" }, { "answer_id": 11776708, "author": "Sedecimdies", "author_id": 1571280, "author_profile": "https://Stackoverflow.com/users/1571280", "pm_score": 0, "selected": false, "text": "<iframe id=\"yourIframe\" clientIDMode=\"static\" runat=\"server\"></iframe>\n clientIDMode Static" }, { "answer_id": 16412074, "author": "andyc", "author_id": 2357037, "author_profile": "https://Stackoverflow.com/users/2357037", "pm_score": 0, "selected": false, "text": "add src=\"<%=_frame1%>\" //to the iframe id=\"frame1\" html control\npublic string _frame1 = \"http://www.google.com\";\n" }, { "answer_id": 22537937, "author": "Jorge", "author_id": 1528483, "author_profile": "https://Stackoverflow.com/users/1528483", "pm_score": 1, "selected": false, "text": "<body>\n\n<iframe id=\"iFrame1\" runat=\"server\"></iframe>\n\n<form id=\"form1\" runat=\"server\">\n\n<div>\n <iframe id=\"iFrame2\" runat=\"server\"></iframe>\n</div>\n</form>\n iFrame1.Attributes[\"src\"] FindControl(\"iFrame2\") as System.Web.UI.HtmlControls.HtmlGenericControl\n" }, { "answer_id": 24265916, "author": "Rajib Chy", "author_id": 3301985, "author_profile": "https://Stackoverflow.com/users/3301985", "pm_score": -1, "selected": false, "text": "<iframe id=\"fblikes\" runat=\"server\"></iframe>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
168,249
<p>Let's say I have a multithreaded C++ program that handles requests in the form of a function call to <code>handleRequest(string key)</code>. Each call to <code>handleRequest</code> occurs in a separate thread, and there are an arbitrarily large number of possible values for <code>key</code>.</p> <p>I want the following behavior:</p> <ul> <li>Simultaneous calls to <code>handleRequest(key)</code> are serialized when they have the same value for <code>key</code>.</li> <li>Global serialization is minimized.</li> </ul> <p>The body of <code>handleRequest</code> might look like this:</p> <pre><code>void handleRequest(string key) { KeyLock lock(key); // Handle the request. } </code></pre> <p><b>Question:</b> How would I implement <code>KeyLock</code> to get the required behavior?</p> <p>A naive implementation might start off like this:</p> <pre><code>KeyLock::KeyLock(string key) { global_lock-&gt;Lock(); internal_lock_ = global_key_map[key]; if (internal_lock_ == NULL) { internal_lock_ = new Lock(); global_key_map[key] = internal_lock_; } global_lock-&gt;Unlock(); internal_lock_-&gt;Lock(); } KeyLock::~KeyLock() { internal_lock_-&gt;Unlock(); // Remove internal_lock_ from global_key_map iff no other threads are waiting for it. } </code></pre> <p>...but that requires a global lock at the beginning and end of each request, and the creation of a separate <code>Lock</code> object for each request. If contention is high between calls to <code>handleRequest</code>, that might not be a problem, but it could impose a lot of overhead if contention is low.</p>
[ { "answer_id": 168282, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 2, "selected": false, "text": "std::map<std::string, MutexType> MutexType" }, { "answer_id": 169106, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "locks[107]" }, { "answer_id": 169192, "author": "eschercycle", "author_id": 24923, "author_profile": "https://Stackoverflow.com/users/24923", "pm_score": 0, "selected": false, "text": "handleRequest Callback multimap<string, Callback*> global_key_map key Callback* global_key_map LockAndCall(string key, Callback* callback) {\n global_lock.Lock();\n if (global_key_map.contains(key)) {\n iterator iter = global_key_map.insert(key, callback);\n while (true) {\n global_lock.Unlock();\n iter->second->Call();\n global_lock.Lock();\n global_key_map.erase(iter);\n iter = global_key_map.find(key);\n if (iter == global_key_map.end()) {\n global_lock.Unlock();\n return;\n }\n }\n } else {\n global_key_map.insert(key, callback);\n global_lock.Unlock();\n }\n}\n" }, { "answer_id": 412233, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " /**\n * StringLock class for string based locking mechanism\n * e.g. usage\n * StringLock strLock;\n * strLock.Lock(\"row1\");\n * strLock.UnLock(\"row1\");\n */\n class StringLock {\n public:\n /**\n * Constructor\n * Initializes the mutexes\n */\n StringLock() {\n pthread_mutex_init(&mtxGlobal, NULL);\n }\n /**\n * Lock Function\n * The thread will return immediately if the string is not locked\n * The thread will wait if the string is locked until it gets a turn\n * @param string the string to lock\n */\n void Lock(string lockString) {\n pthread_mutex_lock(&mtxGlobal);\n TListIds *listId = NULL;\n TWaiter *wtr = new TWaiter;\n wtr->evPtr = NULL;\n wtr->threadId = pthread_self();\n if (lockMap.find(lockString) == lockMap.end()) {\n listId = new TListIds();\n listId->insert(listId->end(), wtr);\n lockMap[lockString] = listId;\n pthread_mutex_unlock(&mtxGlobal);\n } else {\n wtr->evPtr = new Event(false);\n listId = lockMap[lockString];\n listId->insert(listId->end(), wtr);\n pthread_mutex_unlock(&mtxGlobal);\n wtr->evPtr->Wait();\n }\n }\n /**\n * UnLock Function\n * @param string the string to unlock\n */\n void UnLock(string lockString) {\n pthread_mutex_lock(&mtxGlobal);\n TListIds *listID = NULL;\n if (lockMap.find(lockString) != lockMap.end()) {\n lockMap[lockString]->pop_front();\n listID = lockMap[lockString];\n if (!(listID->empty())) {\n TWaiter *wtr = listID->front();\n Event *thdEvent = wtr->evPtr;\n thdEvent->Signal();\n } else {\n lockMap.erase(lockString);\n delete listID;\n }\n }\n pthread_mutex_unlock(&mtxGlobal);\n }\n protected:\n struct TWaiter {\n Event *evPtr;\n long threadId;\n };\n StringLock(StringLock &);\n void operator=(StringLock&);\n typedef list TListIds;\n typedef map TMapLockHolders;\n typedef map TMapLockWaiters;\n private:\n pthread_mutex_t mtxGlobal;\n TMapLockWaiters lockMap;\n };\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24923/" ]
168,280
<p>I want to allow an Excel report to be viewed embedded in a WebPage... is there a way?</p> <ul> <li><p>I don't want to use an ActiveX, or OWC (Office Web Components), I just want to open an existing file from the internet explorer application.</p></li> <li><p>I don't want users to download and then open it.</p></li> </ul> <p>Using an iframe wouldn't be a problem, but my preliminary tests weren't successful</p> <p>Any ideas? Is it at all possible?</p>
[ { "answer_id": 168351, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": -1, "selected": false, "text": "<iframe src=\"file:\\\\yourpath\\yourfile.xls\" width=\"100%\" height=\"500\"></iframe>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
168,317
<p>We have a SmartClient built in C# that stubornly remains open when the PC its running on is being restarted. This halts the restart process unless the user first closes the SmartClient or there is some other manual intervention.</p> <p>This is causing problems when the infrastructure team remotely installs new software that requires a machine reboot.</p> <p>Any ideas for getting the SmartClient app to recognize the shutdown/restart event from Windows and gracefully kill itself?</p> <p><strong>UPDATE:</strong> This is a highly threaded application with multiple gui threads. yes, multiple gui threads. Its really a consolidation of many project that in and of themselves could be standalone applications - all of which are launched and managed from a single exe that centralizes those management methods and keeps track of those threads. I don't believe using background threads is an option.</p>
[ { "answer_id": 168365, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 4, "selected": true, "text": "...\nMicrosoft.Win32.SystemEvents.SessionEnded +=new\n Microsoft.Win32.SessionEndedEventHandler(shutdownHandler);\n\n...\n\nprivate void shutdownHandler(object sender, Microsoft.Win32.SessionEndedEventArgs e) {\n // Do stuff\n}\n" }, { "answer_id": 168405, "author": "Catalin DICU", "author_id": 13030, "author_profile": "https://Stackoverflow.com/users/13030", "pm_score": 1, "selected": false, "text": "ManualResetEvent Mutex WM_CLOSE Application.Run(new Form1()); AppDomain" }, { "answer_id": 168482, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": false, "text": "WM_QUERYENDSESSION FormClosing CloseReason == WindowsShutDown FormClosing" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24179/" ]
168,369
<p>After working for a few days with Eclipse Java I totally got addicted to pressing <kbd>Ctrl</kbd> and clicking on an identifier to go to its definition. Since then I've been looking for a way to achieve this in Visual Studio as well.</p> <p>I realize VS has right click, Go to definition, and that <kbd>F12</kbd> does the same. I also realize that Visual Assist does something similar with <kbd>Alt</kbd> + <kbd>G</kbd>. Yet none of these are as perfect as <kbd>Ctrl</kbd> + click. </p> <p>I've actually tried my luck for a few hours trying to write a VS plugin to do it but didn't get anywhere in the time frame I thought reasonable for this.</p> <p>Does anyone know how this could be achieved? A ready plugin? A macro of some kind?</p>
[ { "answer_id": 33536128, "author": "Se Song", "author_id": 3458608, "author_profile": "https://Stackoverflow.com/users/3458608", "pm_score": 6, "selected": false, "text": "Go To Definition TOOLS Extensions and Updates" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
168,396
<p>Is there a way to use .NET reflection to capture the values of all parameters/local variables?</p>
[ { "answer_id": 168425, "author": "RyanFetz", "author_id": 23776, "author_profile": "https://Stackoverflow.com/users/23776", "pm_score": 0, "selected": false, "text": "System.Diagnostics.StackTrace sTrace = new System.Diagnostics.StackTrace(true);\nfor (Int32 frameCount = 0; frameCount < sTrace.FrameCount; frameCount++){ \n System.Diagnostics.StackFrame sFrame = sTrace.GetFrame(frameCount);\n System.Reflection.MethodBase thisMethod = sFrame.GetMethod();\n if (thisMethod == currentMethod){\n if (frameCount + 1 <= sTrace.FrameCount){\n System.Diagnostics.StackFrame prevFrame = sTrace.GetFrame(frameCount + 1);\n System.Reflection.MethodBase prevMethod = prevFrame.GetMethod();\n }\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7529/" ]
168,402
<p>I have run across an XML Schema with the following definition:</p> <pre><code>&lt;xs:simpleType name="ClassRankType"&gt; &lt;xs:restriction base="xs:integer"&gt; &lt;xs:totalDigits value="4"/&gt; &lt;xs:minInclusive value="1"/&gt; &lt;xs:maxInclusive value="9999"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; </code></pre> <p>However, it seems to me that <code>totalDigits</code> is redundant. I am somewhat new to XML Schema, and want to make sure I'm not missing something.</p> <p>What is the actual behavior of <code>totalDigits</code> vs. <code>maxInclusive</code>?</p> <p>Can <code>totalDigits</code> always be represented with a combination of <code>minInclusive</code> and <code>MaxInclusive</code>? </p> <p>How does <code>totalDigits</code> affect negative numbers?</p>
[ { "answer_id": 168466, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": true, "text": "minInclusive maxInclusive totalDigits <xsd:totalDigits>" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24954/" ]
168,408
<p>It looks like I had a fundamental misunderstanding about C++ :&lt;</p> <p>I like the polymorphic container solution. Thank you SO, for bringing that to my attention :)</p> <hr> <p>So, we have a need to create a relatively generic container type object. It also happens to encapsulate some business related logic. However, we need to store essentially arbitrary data in this container - everything from primitive data types to complex classes.</p> <p>Thus, one would immediately jump to the idea of a template class and be done with it. However, I have noticed C++ polymorphism and templates do not play well together. Being that there is some complex logic that we are going to have to work, I would rather just stick with either templates OR polymorphism, and not try to fight C++ by making it do both.</p> <p>Finally, given that I want to do one or the other, I would prefer polymorphism. I find it much easier to represent constraints like "this container contains Comparable types" - a la java.</p> <p>Bringing me to the topic of question: At the most abstract, I imagine that I could have a "Container" pure virtual interface that has something akin to "push(void* data) and pop(void* data)" (for the record, I am not actually trying to implement a stack).</p> <p>However, I don't really like void* at the top level, not to mention the signature is going to change every time I want to add a constraint to the type of data a concrete container can work with.</p> <p>Summarizing: We have relatively complex containers that have various ways to retrieve elements. We want to be able to vary the constraints on the elements that can go into the containers. Elements should work with multiple kinds of containers (so long as they meet the constraints of that particular container).</p> <p>Edit: I should also mention that the containers themselves need to be polymorphic. That is my primary reason for not wanting to use templated C++.</p> <p>So - should I drop my love for Java type interfaces and go with templates? Should I use void* and statically cast everything? Or should I go with an empty class definition "Element" that declares nothing and use that as my top level class in the "Element" hierarchy?</p> <p>One of the reasons why I love stack overflow is that many of the responses provide some interesting insight on other approaches that I hadn't not have even considered. So thank you in advance for your insights and comments.</p>
[ { "answer_id": 168442, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 3, "selected": false, "text": "void push(T* new_element) void* Storable Storable* void* void push(Storable* new_element)" }, { "answer_id": 168451, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 3, "selected": false, "text": "Container std::vector std::list Container" }, { "answer_id": 168509, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "template <typename T>\nclass Container\n{\npublic: \n\n // You'll likely want to use shared_ptr<T> instead.\n virtual void push(T *element) = 0;\n virtual T *pop() = 0;\n virtual void InvokeSomeMethodOnAllItems() = 0;\n};\n\ntemplate <typename T>\nclass List : public Container<T>\n{\n iterator begin();\n iterator end();\npublic:\n virtual void push(T *element) {...}\n virtual T* pop() { ... }\n virtual void InvokeSomeMethodOnAllItems() \n {\n for(iterator currItem = begin(); currItem != end(); ++currItem)\n {\n T* item = *currItem;\n item->SomeMethod();\n }\n }\n};\n class Item\n{\npublic:\n virtual void SomeMethod() = 0;\n};\n\nclass ConcreteItem\n{\npublic:\n virtual void SomeMethod() \n {\n // Do something\n }\n}; \n\nvoid AddItemToContainer(Container<Item> &container, Item *item)\n{\n container.push(item);\n}\n\n...\n\nList<Item> listInstance;\nAddItemToContainer(listInstance, new ConcreteItem());\nlistInstance.InvokeSomeMethodOnAllItems();\n class Item\n{\npublic:\n virtual void SomeMethod() = 0;\n typedef int CanBeContainedInList;\n};\n\ntemplate <typename T>\nclass List : public Container<T>\n{\n typedef typename T::CanBeContainedInList ListGuard;\n // ... as before\n};\n" }, { "answer_id": 168583, "author": "Reddog", "author_id": 24965, "author_profile": "https://Stackoverflow.com/users/24965", "pm_score": 0, "selected": false, "text": "class Whatever\n{\n void MyPolymorphicMethod(Container<IComparable*> &listOfComparables);\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14621/" ]
168,409
<p>What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?</p>
[ { "answer_id": 168424, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 8, "selected": false, "text": "import glob\nimport os\n\nsearch_dir = \"/mydir/\"\n# remove anything from the list that is not a file (directories, symlinks)\n# thanks to J.F. Sebastion for pointing out that the requirement was a list \n# of files (presumably not including directories) \nfiles = list(filter(os.path.isfile, glob.glob(search_dir + \"*\")))\nfiles.sort(key=lambda x: os.path.getmtime(x))\n import os\n\nsearch_dir = \"/mydir/\"\nos.chdir(search_dir)\nfiles = filter(os.path.isfile, os.listdir(search_dir))\nfiles = [os.path.join(search_dir, f) for f in files] # add path to each file\nfiles.sort(key=lambda x: os.path.getmtime(x))\n" }, { "answer_id": 168435, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "import os\nimport time\nfrom pprint import pprint\n\npprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(\".\")], key = lambda x: x[1].st_ctime)])\n" }, { "answer_id": 168580, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 5, "selected": false, "text": "def getfiles(dirpath):\n a = [s for s in os.listdir(dirpath)\n if os.path.isfile(os.path.join(dirpath, s))]\n a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))\n return a\n" }, { "answer_id": 168658, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 3, "selected": false, "text": "sorted(filter(os.path.isfile, os.listdir('.')), \n key=lambda p: os.stat(p).st_mtime)\n os.walk('.').next()[-1] os.path.isfile os.stat" }, { "answer_id": 539024, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "dirpath import os\nfrom pathlib import Path\n\npaths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)\n files files.sort(key=os.path.getctime)\n glob @Greg Hewgill #!/usr/bin/env python\nfrom stat import S_ISREG, ST_CTIME, ST_MODE\nimport os, sys, time\n\n# path to the directory (relative or absolute)\ndirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'\n\n# get all entries in the directory w/ stats\nentries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))\nentries = ((os.stat(path), path) for path in entries)\n\n# leave only regular files, insert creation date\nentries = ((stat[ST_CTIME], path)\n for stat, path in entries if S_ISREG(stat[ST_MODE]))\n#NOTE: on Windows `ST_CTIME` is a creation date \n# but on Unix it could be something else\n#NOTE: use `ST_MTIME` to sort by a modification date\n \nfor cdate, path in sorted(entries):\n print time.ctime(cdate), os.path.basename(path)\n $ python stat_creation_date.py\nThu Feb 11 13:31:07 2009 stat_creation_date.py\n" }, { "answer_id": 4914674, "author": "gypaetus", "author_id": 605436, "author_profile": "https://Stackoverflow.com/users/605436", "pm_score": 5, "selected": false, "text": "os.path.getmtime os.stat import os \n\nos.chdir(directory)\nsorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)\n" }, { "answer_id": 7801791, "author": "cumulus13", "author_id": 1000188, "author_profile": "https://Stackoverflow.com/users/1000188", "pm_score": 1, "selected": false, "text": "import os, stat, sys\nimport time\n\ndirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'\n\nlistdir = os.listdir(dirpath)\n\nfor i in listdir:\n os.chdir(dirpath)\n data_001 = os.path.realpath(i)\n listdir_stat1 = os.stat(data_001)\n listdir_stat2 = ((os.stat(data_001), data_001))\n print time.ctime(listdir_stat1.st_ctime), data_001\n" }, { "answer_id": 18783474, "author": "dinos66", "author_id": 1961612, "author_profile": "https://Stackoverflow.com/users/1961612", "pm_score": 4, "selected": false, "text": "dataset_path='/mydir/' \nfiles = glob.glob(dataset_path+\"/morepath/*.extension\") \nfiles.sort(key=os.path.getmtime)\n" }, { "answer_id": 30381619, "author": "Nic", "author_id": 4130524, "author_profile": "https://Stackoverflow.com/users/4130524", "pm_score": 4, "selected": false, "text": "import os \n\npath = '/path/to/files/'\nname_list = os.listdir(path)\nfull_list = [os.path.join(path,i) for i in name_list]\ntime_sorted_list = sorted(full_list, key=os.path.getmtime)\n\nprint time_sorted_list\n\n# if you want just the filenames sorted, simply remove the dir from each\nsorted_filename_list = [ os.path.basename(i) for i in time_sorted_list]\nprint sorted_filename_list\n" }, { "answer_id": 45643927, "author": "Paolo Benvenuto", "author_id": 1242139, "author_profile": "https://Stackoverflow.com/users/1242139", "pm_score": 1, "selected": false, "text": "import time\nimport datetime\nsorted(filter(os.path.isfile, os.listdir('.')), \n key=lambda p: os.path.exists(p) and os.stat(p).st_mtime or time.mktime(datetime.now().timetuple())\n" }, { "answer_id": 46231690, "author": "ignorant", "author_id": 2029648, "author_profile": "https://Stackoverflow.com/users/2029648", "pm_score": 4, "selected": false, "text": "from pathlib import Path\nsorted(Path('.').iterdir(), key=lambda f: f.stat().st_mtime)\n" }, { "answer_id": 55499815, "author": "TXN_747", "author_id": 4220424, "author_profile": "https://Stackoverflow.com/users/4220424", "pm_score": 0, "selected": false, "text": "def get_sorted_files(src_dir, regex_ext='*', sort_reverse=False): \n files_to_evaluate = [os.path.join(src_dir, f) for f in os.listdir(src_dir) if re.search(r'.*\\.({})$'.format(regex_ext), f)]\n files_to_evaluate.sort(key=os.path.getmtime, reverse=sort_reverse)\n return files_to_evaluate\n" }, { "answer_id": 57831290, "author": "Arash", "author_id": 10937550, "author_profile": "https://Stackoverflow.com/users/10937550", "pm_score": 3, "selected": false, "text": "# *** the shortest and best way ***\n# getmtime --> sort by modified time\n# getctime --> sort by created time\n\nimport glob,os\n\nlst_files = glob.glob(\"*.txt\")\nlst_files.sort(key=os.path.getmtime)\nprint(\"\\n\".join(lst_files))\n" }, { "answer_id": 58031458, "author": "n1nj4", "author_id": 2387835, "author_profile": "https://Stackoverflow.com/users/2387835", "pm_score": 2, "selected": false, "text": "os.scandir pathlib import os\nsorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)\n" }, { "answer_id": 58772122, "author": "Pygirl", "author_id": 6660373, "author_profile": "https://Stackoverflow.com/users/6660373", "pm_score": 4, "selected": false, "text": "from pathlib import Path\nimport os\n\nsorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)\n sorted(Path('./').iterdir(), key=os.path.getmtime)\n sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)\n" }, { "answer_id": 62169394, "author": "haqrafiul", "author_id": 13459502, "author_profile": "https://Stackoverflow.com/users/13459502", "pm_score": 2, "selected": false, "text": "import os\n\nfolder_path = r'D:\\Movies\\extra\\new\\dramas' # your path\nos.chdir(folder_path) # make the path active\nx = sorted(os.listdir(), key=os.path.getctime) # sorted using creation time\n\nfolder = 0\n\nfor folder in range(len(x)):\n print(x[folder]) # print all the foldername inside the folder_path\n folder = +1\n" }, { "answer_id": 66012868, "author": "Mayank", "author_id": 11728685, "author_profile": "https://Stackoverflow.com/users/11728685", "pm_score": -1, "selected": false, "text": "os.listdir import os\nlast_modified=os.listdir()[::-1]\n" }, { "answer_id": 71833978, "author": "Aps", "author_id": 13079256, "author_profile": "https://Stackoverflow.com/users/13079256", "pm_score": 0, "selected": false, "text": "import glob, os\nfrom pathlib import Path\npath = os.path.expanduser(file_location+\"/\"+date_file) \nos.chdir(path) \nsaved_file=glob.glob('*.xlsx')\nsaved_file.sort(key=os.path.getmtime)\n\nprint(saved_file)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24953/" ]
168,415
<p>For my current project, I need to request XML data over a tcp/ip socket connection. For this, I am using the TcpClient class:</p> <pre><code>Dim client As New TcpClient() client.Connect(server, port) Dim stream As NetworkStream = client.GetStream() stream.Write(request) stream.Read(buffer, 0, buffer.length) // Output buffer and return results... </code></pre> <p>Now this works fine and dandy for small responses. However, when I start receiving larger blocks of data, it appears that the data gets pushed over the socket connection in bursts. When this happens, the stream.Read call only reads the first burst, and thus I miss out on the rest of the response. </p> <p>What's the best way to handle this issue? Initially I tried to just loop until I had a valid XML document, but I found that in between stream.Read calls the underlying stream would sometimes get shut down and I would miss out on the last portion of the data.</p>
[ { "answer_id": 168418, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 3, "selected": true, "text": "int bytes_read = 0;\nwhile (bytes_read < buffer.Length)\n bytes_read += stream.Read(buffer, bytes_read, buffer.length - bytes_read);\n int bytes_read = 0;\ntry\n{\n int i = 0;\n while ( 0 < (i = stream.Read(buffer, bytes_read, buffer.Length - bytes_read) )\n bytes_read += i;\n}\ncatch (Exception e)\n{\n//recover\n}\nfinally\n{\nif (stream != null)\n stream.Close();\n}\n" }, { "answer_id": 539052, "author": "Tute", "author_id": 4386, "author_profile": "https://Stackoverflow.com/users/4386", "pm_score": 0, "selected": false, "text": "string response;\n\nTcpClient client = new TcpClient();\nclient.Connect(server, port);\nusing (NetworkStream ns = c.GetStream())\nusing (MemoryStream ms = new MemoryStream())\n{\n ns.Write(request);\n\n byte[] buffer = new byte[512];\n int bytes = 0;\n\n while(ns.DataAvailable)\n {\n bytes = ns.Read(buffer,0, buffer.Length);\n ms.Write(buffer, 0, bytes);\n }\n\n response = Encoding.ASCII.GetString(ms.ToArray());\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
168,423
<p>I have a personal wiki that I take notes on. The wiki's pages are in a subversion working copy directory, "pages", and I set their permissions to 664, owned by www-data:www-data. My username is in the "www-data" group, so I can checkin and mess with the pages manually.</p> <p>For a while, I had an issue because every time I ran a checkin, the files would be owned by me:www-data instead of www-data:www-data, and I would no longer be able to change the wiki files through my web interface! I solved the issue by flipping the setgid bit on the "pages" directory, but I'm still confused as to why this happened in the first place:</p> <p>Every time I check something into subversion, it appears as if svn deletes it and recreates it. Why? Does this behavior support some functionality that I'm not aware of? Is there a way to change it?</p> <p>Thanks!</p>
[ { "answer_id": 178496, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "find -type d -exec chgrp www-data {} + \nfind -type d -exec chmod g+s {} + \n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
168,427
<p>Which of <a href="http://en.wikipedia.org/wiki/Crystal_Reports" rel="noreferrer">Crystal Reports</a> and <a href="http://en.wikipedia.org/wiki/SQL_Server_Reporting_Services" rel="noreferrer">SSRS</a> (SQL Server Reporting Services) is better to use?</p>
[ { "answer_id": 171536, "author": "Peter Wone", "author_id": 1715673, "author_profile": "https://Stackoverflow.com/users/1715673", "pm_score": 7, "selected": false, "text": "SELECT COUNT(*) FROM SOMETABLE WHERE 1=0" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14299/" ]
168,438
<p>I'm trying to parse objects to XML in Delphi, so I read about calling the object's ClassInfo method to get its RTTI info.</p> <p>The thing is, this apparently only works for TPersistent objects. Otherwise, I have to specifically add a compiler directive {$M+} to the source code for the compiler to generate RTTI info.</p> <p>So I happily added the directive, only to find that, even if it did return something from the ClassInfo call (it used to return nil), now I cannot retrieve the class' properties, fields or methods from it. It's like it created the object empty.</p> <p>Any idea what am I missing here? Thanks!</p>
[ { "answer_id": 168476, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 4, "selected": true, "text": "published" }, { "answer_id": 46253778, "author": "Edgar Pavão", "author_id": 8527033, "author_profile": "https://Stackoverflow.com/users/8527033", "pm_score": 0, "selected": false, "text": "type\n TTest = class\n public\n procedure Test;\n end;\n var\n LContext: TRttiContext;\n LType: TRttiType;\n LTest: TTest;\nbegin\n LContext := TRttiContext.Create;\n for LType in LContext.GetTypes do\n begin\n if LType.IsInstance then\n begin\n WriteLn(LType.Name);\n end;\n end;\nend;\n var\n LContext: TRttiContext;\n LType: TRttiType;\n LTest: TTest;\nbegin\n LTest := TTest.Create; //Here i´m using TTest.\n //Could be in another part of the program\n\n LContext := TRttiContext.Create;\n for LType in LContext.GetTypes do\n begin\n if LType.IsInstance then\n begin\n WriteLn(LType.Name);\n end;\n end;\nend;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16732/" ]
168,455
<p>How do you post data to an iframe?</p>
[ { "answer_id": 168488, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 10, "selected": true, "text": "target=\"\" <form /> <form action=\"do_stuff.aspx\" method=\"post\" target=\"my_iframe\">\n <input type=\"submit\" value=\"Do Stuff!\">\n</form>\n\n<!-- when the form is submitted, the server response will appear in this iframe -->\n<iframe name=\"my_iframe\" src=\"not_submitted_yet.aspx\"></iframe>\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC\n \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n <head>\n <title>Form Iframe Demo</title>\n </head>\n <body>\n <form action=\"do_stuff.asp\" method=\"post\" target=\"my_frame\">\n <input type=\"text\" name=\"someText\" value=\"Some Text\">\n <input type=\"submit\">\n </form>\n <iframe name=\"my_frame\" src=\"do_stuff.asp\">\n </iframe>\n </body>\n</html>\n <%@Language=\"JScript\"%><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC\n \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html>\n <head>\n <title>Form Iframe Demo</title>\n </head>\n <body>\n <% if (Request.Form.Count) { %>\n You typed: <%=Request.Form(\"someText\").Item%>\n <% } else { %>\n (not submitted)\n <% } %>\n </body>\n</html>\n" }, { "answer_id": 11131626, "author": "kapil", "author_id": 980571, "author_profile": "https://Stackoverflow.com/users/980571", "pm_score": 5, "selected": false, "text": "<form action=\"action\" method=\"post\" target=\"output_frame\">\n <!-- input elements here --> \n</form>\n<iframe name=\"output_frame\" src=\"\" id=\"output_frame\" width=\"XX\" height=\"YY\">\n</iframe> \n <script>\n$( \"#uploadDialog\" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false, \n open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });\n\nfunction startUpload()\n{ \n $(\"#uploadDialog\").dialog(\"open\");\n}\n\nfunction stopUpload()\n{ \n $(\"#uploadDialog\").dialog(\"close\");\n}\n</script>\n\n<div id=\"uploadDialog\" title=\"Please Wait!!!\">\n <center>\n <img src=\"/imagePath/loading.gif\" width=\"100\" height=\"100\"/>\n <br/>\n Loading Details...\n </center>\n </div>\n\n<FORM ENCTYPE=\"multipart/form-data\" ACTION=\"Action\" METHOD=\"POST\" target=\"upload_target\" onsubmit=\"startUpload()\"> \n<!-- input file elements here--> \n</FORM>\n\n<iframe id=\"upload_target\" name=\"upload_target\" src=\"#\" style=\"width:0;height:0;border:0px solid #fff;\" onload=\"stopUpload()\"> \n </iframe>\n" }, { "answer_id": 50438495, "author": "Dr Fred", "author_id": 468445, "author_profile": "https://Stackoverflow.com/users/468445", "pm_score": 2, "selected": false, "text": "function postToIframe(data,url,target){\n $('body').append('<form action=\"'+url+'\" method=\"post\" target=\"'+target+'\" id=\"postToIframe\"></form>');\n $.each(data,function(n,v){\n $('#postToIframe').append('<input type=\"hidden\" name=\"'+n+'\" value=\"'+v+'\" />');\n });\n $('#postToIframe').submit().remove();\n}\n data={last_name:'Smith',first_name:'John'}\n" }, { "answer_id": 53092796, "author": "Dominique Fortin", "author_id": 1571709, "author_profile": "https://Stackoverflow.com/users/1571709", "pm_score": 0, "selected": false, "text": "...\nvar el = document.getElementById('targetFrame');\n\nvar doc, frame_win = getIframeWindow(el); // getIframeWindow is defined below\n\nif (frame_win) {\n doc = (window.contentDocument || window.document);\n}\n\nif (doc) {\n doc.forms[0].someInputName.value = someValue;\n ...\n doc.forms[0].submit();\n}\n...\n function getIframeWindow(iframe_object) {\n var doc;\n\n if (iframe_object.contentWindow) {\n return iframe_object.contentWindow;\n }\n\n if (iframe_object.window) {\n return iframe_object.window;\n } \n\n if (!doc && iframe_object.contentDocument) {\n doc = iframe_object.contentDocument;\n } \n\n if (!doc && iframe_object.document) {\n doc = iframe_object.document;\n }\n\n if (doc && doc.defaultView) {\n return doc.defaultView;\n }\n\n if (doc && doc.parentWindow) {\n return doc.parentWindow;\n }\n\n return undefined;\n}\n" }, { "answer_id": 70588441, "author": "vinayp", "author_id": 14117367, "author_profile": "https://Stackoverflow.com/users/14117367", "pm_score": 0, "selected": false, "text": "var allParams = { xyz, abc }\n\n var parentElm = document.getElementBy... // your own element where you want to create the iframe\n\n // create an iframe \n var addIframe = document.createElement('iframe');\n addIframe.setAttribute('name', 'sample-iframe');\n addIframe.style.height = height ? height : \"360px\";\n addIframe.style.width = width ? width : \"360px\";\n parentElm.appendChild(addIframe)\n\n // make an post request\n var form, input;\n form = document.createElement(\"form\");\n form.action = 'example.com';\n form.method = \"post\";\n form.target = \"sample-iframe\";\n Object.keys(allParams).forEach(function (elm) {\n console.log('elm: ', elm, allParams[elm]);\n input = document.createElement(\"input\");\n input.name = elm;\n input.value = allParams[elm];\n input.type = \"hidden\";\n form.appendChild(input);\n })\n parentElm.appendChild(form);\n form.submit();\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24958/" ]
168,464
<p>Since <em>length</em> is a JavaScript property, does it matter whether I use</p> <pre><code>for( var i = 0; i &lt; myArray.length; i++ ) </code></pre> <p>OR</p> <pre><code>var myArrayLength = myArray.length; for( var i = 0; i &lt; myArrayLength ; i++ ) </code></pre> <p>­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 168473, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": false, "text": "for(var i = 0, iLen = myArray.length; i < iLen; i++)\n" }, { "answer_id": 168479, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "for (var i = 0, length = col.length; i < length; i++)\n" }, { "answer_id": 168514, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 0, "selected": false, "text": "function p(f) { var d1=new Date(); for(var i=0;i<20;i++) f(); print(new Date()-d1) }\np(function(){for(var i=0;i<1000000; i++) ;})\np(function(){var a = new Array(1000000); for(var i=0;i<a.length; i++) ;})\n> 823\n> 1283\n" }, { "answer_id": 169073, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 1, "selected": false, "text": "push, pop, array[array.length]=0, etc NodeList document.getElementsBySelector" }, { "answer_id": 172610, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 0, "selected": false, "text": "if(i=0, iMax=object.length; iMax>i; i++)\n" }, { "answer_id": 172647, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 2, "selected": false, "text": "var arr = [1,2,3];\nfor(var i = 0; i < arr.length; i++){\n console.debug(\"i = \" + i);\n console.debug(\"indexed value = \" + arr[i])\n arr.pop();\n}\n i = 0\nindexed value = 1\ni = 1\nindexed value = 2\n var arr = [1,2,3];\nvar l = arr.length;\nfor(var i = 0; i < l; i++){\n console.debug(\"i = \" + i);\n console.debug(\"indexed value = \" + arr[i])\n arr.pop();\n}\n i = 0\nindexed value = 1\ni = 1\nindexed value = 2\ni = 2\nindexed value = undefined\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
168,486
<p>For my customer I occasionally do work in their live database in order to fix a problem they have created for themselves, or in order to fix bad data that my product's bugs created. Much like Unix root access, it's just dangerous. What lessons should I learn ahead of time?</p> <p>What is the #1 thing you do to be careful about operating on live data?</p>
[ { "answer_id": 168508, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "WHERE DELETE UPDATE" }, { "answer_id": 168529, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 7, "selected": false, "text": "BEGIN TRANSACTION;\n" }, { "answer_id": 168532, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 4, "selected": false, "text": "UPDATE [table-name] WHERE [conditions] SET [columns-and-values] update person set email = 'bob@bob.com' WHERE DELETE" }, { "answer_id": 168535, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 4, "selected": false, "text": "--COMMIT TRAN t1\n begin tran t1\nupdate \nset \nwhere \nrollback tran t1\n--commit tran t1\n" }, { "answer_id": 168536, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 0, "selected": false, "text": "WHERE UPDATE my_table WHERE condition = true;\n" }, { "answer_id": 168546, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 8, "selected": true, "text": "DELETE FROM Customers\n SELECT *\nINTO CustomerBackup200810032034\nFROM Customer\n" }, { "answer_id": 168607, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 4, "selected": false, "text": "--Update P Set\n--Select ID, Name as OldName, \n Name='Jones'\nFrom Person P\nWhere ID = 1000\n" }, { "answer_id": 168632, "author": "Peter", "author_id": 5189, "author_profile": "https://Stackoverflow.com/users/5189", "pm_score": 0, "selected": false, "text": "select *\n into MyBackupDb..PeterTableName2008_09_28BeforeABigUpdate\n" }, { "answer_id": 890697, "author": "Aaron", "author_id": 71608, "author_profile": "https://Stackoverflow.com/users/71608", "pm_score": 1, "selected": false, "text": "Begin Transaction\n Delete from foo where FooID = 100\nIF @@RowCount <> 1 Begin\n Rollback Transaction\nEnd \n" }, { "answer_id": 994608, "author": "tsilb", "author_id": 11112, "author_profile": "https://Stackoverflow.com/users/11112", "pm_score": 0, "selected": false, "text": "-- PROD -- PROD -- PROD -- PROD -- PROD -- PROD --\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10906/" ]
168,528
<p>I know I can get this to technically work but I'd like to implement the cleanest possible solution. Here's the situation:</p> <p>I have a managed library which wraps an unmanaged C-style library. The C-style library functionality I'm currently wrapping does some processing involving a list of strings. The library's client code can provide a delegate, such that during the list processing, if an "invalid" scenario is encountered, the library can callback to the client via this delegate and allow them to choose the strategy to use (throw an exception, replace the invalid characters, etc.)</p> <p>What I'd ideally like to have is all of the managed C++ isolated in one function, and then be able to call a separate function which takes only unmanaged parameters so that all of the native C++ and unmanaged code is isolated at that one point. Providing the callback mechanism to this unmanaged code is proving to be the sticking point for me.</p> <pre><code> #pragma managed public delegate string InvalidStringFilter(int lineNumber, string text); ... public IList&lt;Result&gt; DoListProcessing(IList&lt;string&gt; listToProcess, InvalidStringFilter filter) { // Managed code goes here, translate parameters etc. } #pragma unmanaged // This should be the only function that actually touches the C-library directly std::vector&lt;NativeResult&gt; ProcessList(std::vector&lt;char*&gt; list, ?? callback); </code></pre> <p>In this snippet, I want to keep all of the C-library access within ProcessList, but during the processing, it will need to do callbacks, and this callback is provided in the form of the InvalidStringFilter delegate which is passed in from some client of my managed library.</p>
[ { "answer_id": 168604, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "\n#pragma managed\npublic delegate string InvalidStringFilter(int lineNumber, string text);\n\n...\nstatic InvalidStringFilter sFilter;\n\npublic IList<Result> DoListProcessing(IList<string> listToProcess, InvalidStringFilter filter)\n{\n // Managed code goes here, translate parameters etc.\n SFilter = filter;\n}\n\n#pragma unmanaged\n\nvoid StringCallback(???)\n{\n sFilter(????);\n}\n\n// This should be the only function that actually touches the C-library directly\nstd::vector<NativeResult> ProcessList(std::vector<char*> list, StringCallback);\n" }, { "answer_id": 258472, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 0, "selected": false, "text": "typedef void (__stdcall *w_InvalidStringFilter) (int lineNumber, string message);\n\nGCHandle handle = GCHandle::Alloc(InvalidStringFilter);\nw_InvalidStringFilter callback = \n static_cast<w_InvalidStringFilter>(\n Marshal::GetFunctionPointerForDelegate(InvalidStringFilter).ToPointer()\n );\n\nstd::vector<NativeResult> res = ProcessList(list, callback);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24965/" ]
168,531
<p>I have a very large file that looks like this (see below). I have two basic choices of regex to use on it (I know there may be others but I'm really trying to compare Greedy and Negated Char Class) methods.</p> <pre><code>ftp: [^\D]{1,} ftp: (\d)+ ftp: \d+ </code></pre> <p><strong><em>Note: what if I took off the parense around the \d?</em></strong></p> <p>Now + is greedy which forces backtracking but the Negated Char Class require a char-by-char comparison. Which is more efficient? Assume the file is very-very large so minute differences in processor usage will become exaggerated due to the length of the file.</p> <p>Now that you've answered that, What if my Negated Char Class was very large, say 18 different characters? Would that change your answer?</p> <p>Thanks.</p> <blockquote> <p>ftp: 1117 bytes<br> ftp: 5696 bytes<br> ftp: 3207 bytes<br> ftp: 5696 bytes<br> ftp: 7200 bytes</p> </blockquote>
[ { "answer_id": 168563, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 2, "selected": false, "text": "\\d+?\n" }, { "answer_id": 168570, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 1, "selected": false, "text": "([^\\D]{1,}): ~18s\n(\\d+): ~17s\n(split / /)[1]: ~17s\n while (<>)\n{\n if ($foo = (split / /)[1])\n {\n print $foo . \"\\n\";\n }\n}\n" }, { "answer_id": 168571, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 1, "selected": false, "text": "(\\d)+ \\d+" }, { "answer_id": 168625, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": true, "text": "\\d*123\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
168,550
<p>How can I display a tooltip over a button using <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a>?</p>
[ { "answer_id": 168555, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": -1, "selected": false, "text": "ToolTip t = new ToolTip();\n private void control_MouseHover(object sender, EventArgs e)\n{\n t.Show(\"Text\", (Control)sender);\n}\n" }, { "answer_id": 168585, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 6, "selected": false, "text": "private void Form1_Load(object sender, System.EventArgs e)\n{\n System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();\n ToolTip1.SetToolTip(this.Button1, \"Hello\");\n}\n" }, { "answer_id": 168591, "author": "Timothy Carter", "author_id": 4660, "author_profile": "https://Stackoverflow.com/users/4660", "pm_score": 3, "selected": false, "text": "private void checkBox1_MouseHover(object sender, EventArgs e)\n{\n toolTip1.Show(\"text\", checkBox1);\n}\n" }, { "answer_id": 168599, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 8, "selected": false, "text": "MyToolTip.Show(\"Tooltip text goes here\", MyButton);\n MyToolTip.Hide(MyButton);\n" }, { "answer_id": 168622, "author": "jmatthias", "author_id": 2768, "author_profile": "https://Stackoverflow.com/users/2768", "pm_score": 7, "selected": false, "text": "this.toolTip1.SetToolTip(this.targetControl, \"My Tool Tip\");\n" }, { "answer_id": 31805340, "author": "nvivekgoyal", "author_id": 1005063, "author_profile": "https://Stackoverflow.com/users/1005063", "pm_score": 3, "selected": false, "text": "System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();\nToolTip1.SetToolTip(this.textBox1, \"Hello world\");\n" }, { "answer_id": 37788880, "author": "flodis", "author_id": 4299943, "author_profile": "https://Stackoverflow.com/users/4299943", "pm_score": 3, "selected": false, "text": "private System.Windows.Forms.ToolTip ToolTip1;\nprivate void PrepareTooltips()\n{\n ToolTip1 = new System.Windows.Forms.ToolTip();\n foreach(Control ctrl in this.Controls)\n {\n if (ctrl is Button && ctrl.Tag is string)\n {\n ctrl.MouseHover += new EventHandler(delegate(Object o, EventArgs a)\n {\n var btn = (Control)o;\n ToolTip1.SetToolTip(btn, btn.Tag.ToString());\n });\n }\n }\n}\n" }, { "answer_id": 49053929, "author": "akn", "author_id": 9429951, "author_profile": "https://Stackoverflow.com/users/9429951", "pm_score": 2, "selected": false, "text": "private void Form1_Load(object sender, System.EventArgs e)\n{\n ToolTip toolTip1 = new ToolTip();\n toolTip1.AutoPopDelay = 5000;\n toolTip1.InitialDelay = 1000;\n toolTip1.ReshowDelay = 500;\n toolTip1.ShowAlways = true;\n toolTip1.SetToolTip(this.button1, \"My button1\");\n toolTip1.SetToolTip(this.checkBox1, \"My checkBox1\");\n}\n" }, { "answer_id": 62537758, "author": "The_Black_Smurf", "author_id": 315493, "author_profile": "https://Stackoverflow.com/users/315493", "pm_score": 2, "selected": false, "text": "public static void SetToolTip(this Control control, string txt)\n{\n new ToolTip().SetToolTip(control, txt);\n}\n this.MyButton.SetToolTip(\"Hello world\");\n" }, { "answer_id": 73166890, "author": "Charan Vasant Achari", "author_id": 19648065, "author_profile": "https://Stackoverflow.com/users/19648065", "pm_score": 0, "selected": false, "text": "Ex- \nToolTip t=new ToolTip();\nt.setToolTip(textBoxName,\"write your message here what tp you want to show up\");\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html" rel="noreferrer">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html" rel="noreferrer">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
[ { "answer_id": 168584, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 7, "selected": true, "text": "os.write(tup[0], \"foo\\n\")\n f = os.fdopen(tup[0], \"w\")\nf.write(\"foo\")\n" }, { "answer_id": 168705, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 2, "selected": false, "text": "tempfile.TemporaryFile" }, { "answer_id": 1296063, "author": "Daryl Spitzer", "author_id": 4766, "author_profile": "https://Stackoverflow.com/users/4766", "pm_score": 4, "selected": false, "text": "from __future__ import with_statement\nfrom contextlib import closing\nfd, filepath = tempfile.mkstemp()\nwith closing(os.fdopen(fd, 'w')) as tf:\n tf.write('foo\\n')\n" }, { "answer_id": 2414333, "author": "hoju", "author_id": 105066, "author_profile": "https://Stackoverflow.com/users/105066", "pm_score": 2, "selected": false, "text": "temp = tempfile.NamedTemporaryFile(delete=False)\ntemp.file.write('foo\\n')\ntemp.close()\n" }, { "answer_id": 16942329, "author": "MartinD", "author_id": 1027660, "author_profile": "https://Stackoverflow.com/users/1027660", "pm_score": 0, "selected": false, "text": "f = tempfile.mkstemp(\"\", \"\", \"\", \"w\") # first three params are 'suffix, 'prefix', 'dir'...\nos.write(f[0], \"write something\")\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
168,560
<p>What is the best way to perform a couple of tasks together and if one task fails then the next tasks should not be completed? I know if it were the database operations then I should have used Transactions but I am talking about different types of operations like the following: </p> <p>All tasks must pass: </p> <p>SendEmail ArchiveReportsInDatabase CreateAFile</p> <p>In the above scenario all the tasks must pass or else the whole batch operation must be rollback. </p>
[ { "answer_id": 168605, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 1, "selected": false, "text": "try {\n task1();\n task2();\n task3();\n ...\n taskN();\n}\ncatch (TaskFailureException e) {\n dealWith(e);\n}\n" }, { "answer_id": 168609, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 0, "selected": false, "text": "SendEmail () {\n # ...\n}\nArchiveReportsInDatabase () {\n # ...\n}\nCreateAFile () {\n # ...\n}\n\nSendEmail && ArchiveReportsInDatabase && CreateAFile\n" }, { "answer_id": 168615, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 1, "selected": false, "text": "try:\n SendEmail()\n try:\n ArchiveReportsInDatabase()\n try:\n CreateAFile()\n except:\n UndoArchiveReportsInDatabase()\n raise\n except:\n UndoSendEmail()\n raise\nexcept:\n // handle failure\n" }, { "answer_id": 168630, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 0, "selected": false, "text": "return SendEmail() && ArchiveResportsInDatabase() && CreateAFile();\n" }, { "answer_id": 168641, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": true, "text": "try {\n if (!SendEmail()) {\n throw \"Could not send e-mail\";\n }\n\n if (!ArchiveReportsInDatabase()) {\n throw \"Could not archive reports in database\";\n }\n\n if (!CreateAFile()) {\n throw \"Could not create file\";\n }\n\n ...\n\n} catch (Exception) {\n LogError(Exception);\n ...\n}\n try {\n SendEmail();\n ArchiveReportsInDatabase();\n CreateAFile();\n ...\n\n} catch (Exception) {\n LogError(Exception);\n ...\n}\n" }, { "answer_id": 168856, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "class Compensator {\n Action Action { get; set; }\n Action Compensate { get; set; }\n}\n\nQueue<Compensator> actions = new Queue<Compensator>(new Compensator[] { \n new Compensator(SendEmail, UndoSendEmail),\n new Compensator(ArchiveReportsInDatabase, UndoArchiveReportsInDatabase),\n new Compensator(CreateAFile, UndoCreateAFile)\n});\n\nQueue<Compensator> doneActions = new Queue<Compensator>();\nwhile (var c = actions.Dequeue() != null) {\n try {\n c.Action();\n doneActions.Add(c);\n } catch {\n try {\n doneActions.Each(d => d.Compensate());\n } catch (EXception ex) {\n throw new OhCrapException(\"Couldn't rollback\", doneActions, ex);\n }\n throw;\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
168,589
<p>I can do this:</p> <pre><code>$ find . . ./b ./b/foo ./c ./c/foo </code></pre> <p>And this:</p> <pre><code>$ find . -type f -exec cat {} \; This is in b. This is in c. </code></pre> <p>But not this:</p> <pre><code>$ find . -type f -exec cat &gt; out.txt {} \; </code></pre> <p>Why not?</p>
[ { "answer_id": 168595, "author": "Commodore Jaeger", "author_id": 4659, "author_profile": "https://Stackoverflow.com/users/4659", "pm_score": 6, "selected": true, "text": "$ find . -type f -exec cat {} \\; > out.txt\n $ find . -type f | xargs cat > out.txt\n $ find . -type f -print0 | xargs -0 cat > out.txt\n" }, { "answer_id": 168603, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 2, "selected": false, "text": "find . -type f -exec cat {} \\; > /tmp/out.txt\n" }, { "answer_id": 168613, "author": "JoMo", "author_id": 4107, "author_profile": "https://Stackoverflow.com/users/4107", "pm_score": 2, "selected": false, "text": "$ cat `find . -type f` > out.txt\n" }, { "answer_id": 168636, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 0, "selected": false, "text": "zsh setopt extendedglob\n .zshrc cat **/*(.) > outfile \n" }, { "answer_id": 168673, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "find . -type f -exec cat {} \\; > ../out.txt\n" }, { "answer_id": 168752, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 1, "selected": false, "text": "> $ find . -type f -exec cat > out.txt {} \\;\n find \".\" \"-type\" \"f\" \"-exec\" \"cat\" \"out.txt\" \"{}\" \";\" find -exec -print0 | xargs -0 $ find . -type f -exec cat \\{} \\; > /tmp/out.txt\n cat `ls -p|sed 's/\\/$/\\/*/'` > /tmp/out.txt\n ls '/' sed '*'" }, { "answer_id": 168785, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "(find . -type f -exec cat {} \\;) > out.txt \n" }, { "answer_id": 168984, "author": "ljorquera", "author_id": 9132, "author_profile": "https://Stackoverflow.com/users/9132", "pm_score": 0, "selected": false, "text": "cat $(find . -type f) > out.txt\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22917/" ]
168,594
<p>I am creating some build scripts that interact with Perforce and I would like to mark for delete a few files. What exactly is the P4 syntax using the command line?</p>
[ { "answer_id": 168614, "author": "JR Lawhorne", "author_id": 22917, "author_profile": "https://Stackoverflow.com/users/22917", "pm_score": 4, "selected": true, "text": "p4 delete filename\n Opens a file that currently exists in the depot for deletion.\nIf the file is present on the client it is removed. If a pending\nchangelist number is given with the -c flag the opened file is\nassociated with that changelist, otherwise it is associated with\nthe 'default' pending changelist.\n\nFiles that are deleted generally do not appear on the have list.\n\nThe -n flag displays what would be opened for delete without actually\nchanging any files or metadata.\n" }, { "answer_id": 168617, "author": "Swati", "author_id": 12682, "author_profile": "https://Stackoverflow.com/users/12682", "pm_score": 2, "selected": false, "text": "p4 delete demo.txt readme.txt\n" }, { "answer_id": 168627, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "p4 help p4 help commands p4 help <command name>" }, { "answer_id": 2314692, "author": "ssc", "author_id": 217844, "author_profile": "https://Stackoverflow.com/users/217844", "pm_score": 0, "selected": false, "text": "p4" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
168,596
<p>When an Event is triggered by a user in IE, it is set to the <code>window.event</code> object. The only way to see what triggered the event is by accessing the <code>window.event</code> object (as far as I know)</p> <p>This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the <code>window.event</code> object stores the last user-triggered event.</p> <p>When the <code>onchange</code> event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.</p> <p>Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.</p> <hr> <p><strong>To explain what I'm doing specifically:</strong><br> I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.</p> <p>The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's <code>change()</code> method.</p> <p>Because the trigger for the event was a list item, IE sees the <em>list item</em> as the source of the event, not the text box, like it should.</p> <p>I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "<code>change</code>" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.</p> <p>Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?</p> <hr> <p>I've found this problem reported several other places, but they offer no solutions: </p> <ul> <li><a href="http://groups.google.com/group/jquery-en/browse_thread/thread/a8902f2774edc05a/d119026f561ca528?lnk=raot" rel="noreferrer">jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator</a></li> <li><a href="http://forums.asp.net/t/1326208.aspx" rel="noreferrer">ASP.NET forums, bug with ValidatorOnChange() function</a></li> </ul>
[ { "answer_id": 371396, "author": "quark", "author_id": 46680, "author_profile": "https://Stackoverflow.com/users/46680", "pm_score": 3, "selected": false, "text": "jQuery.fn.extend({\n fire: function(evttype){ \n el = this.get(0);\n if (document.createEvent) {\n var evt = document.createEvent('HTMLEvents'); \n evt.initEvent(evttype, false, false); \n el.dispatchEvent(evt); \n } else if (document.createEventObject) { \n el.fireEvent('on' + evttype); \n }\n return this;\n }\n});\n if ($.browser.msie) {\n datepickerOptions = $.extend(datepickerOptions, { \n onSelect: function(){\n $(this).fire(\"change\").blur();\n }\n });\n}\n" }, { "answer_id": 2905196, "author": "Ben McIntyre", "author_id": 208465, "author_profile": "https://Stackoverflow.com/users/208465", "pm_score": 2, "selected": false, "text": " for (i = 0; i < vals.length; i++) {\n ValidatorValidate(vals[i], null, event);\n }\n if (vals) {\n for (i = 0; i < vals.length; i++) {\n ValidatorValidate(vals[i], null, event);\n }\n}\n // Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix\n function ValidatorOnChange(event) {\n if (!event) {\n event = window.event;\n }\n Page_InvalidControlToBeFocused = null;\n var targetedControl;\n if ((typeof (event.srcElement) != \"undefined\") && (event.srcElement != null)) {\n targetedControl = event.srcElement;\n }\n else {\n targetedControl = event.target;\n }\n var vals;\n if (typeof (targetedControl.Validators) != \"undefined\") {\n vals = targetedControl.Validators;\n }\n else {\n if (targetedControl.tagName.toLowerCase() == \"label\") {\n targetedControl = document.getElementById(targetedControl.htmlFor);\n vals = targetedControl.Validators;\n }\n }\n var i;\n if (vals) {\n for (i = 0; i < vals.length; i++) {\n ValidatorValidate(vals[i], null, event);\n }\n }\n ValidatorUpdateIsValid();\n}\n" }, { "answer_id": 8993921, "author": "thorn0", "author_id": 76173, "author_profile": "https://Stackoverflow.com/users/76173", "pm_score": 2, "selected": false, "text": " window.ValidatorHookupEvent = function(control, eventType, body) {\n $(control).bind(eventType.slice(2), new Function(\"event\", body));\n };\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
168,610
<p>I have a PHP web application on an intranet that can extract the IP and host name of the current user on that page, but I was wondering if there is a way to get/extract their Active Directory/Windows username as well. Is this possible?</p>
[ { "answer_id": 168626, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 7, "selected": true, "text": "AUTH_USER AUTH_USER MYDOMAIN\\user.name" }, { "answer_id": 168675, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "<?php phpinfo(); ?>" }, { "answer_id": 1958096, "author": "CrayFishUK", "author_id": 214596, "author_profile": "https://Stackoverflow.com/users/214596", "pm_score": 2, "selected": false, "text": "$_SERVER['REMOTE_USER']" }, { "answer_id": 2932793, "author": "Someone", "author_id": 400440, "author_profile": "https://Stackoverflow.com/users/400440", "pm_score": 1, "selected": false, "text": "getenv('USERNAME')" }, { "answer_id": 3360104, "author": "Schwarz.Oz", "author_id": 405366, "author_profile": "https://Stackoverflow.com/users/405366", "pm_score": 4, "selected": false, "text": "$_SERVER[\"AUTH_USER\"] $user = $_SERVER['AUTH_USER'];\n $user DOMAIN\\username DOMAIN\\" }, { "answer_id": 13986660, "author": "Eddy Goh", "author_id": 1505514, "author_profile": "https://Stackoverflow.com/users/1505514", "pm_score": 2, "selected": false, "text": "echo gethostbyaddr($_SERVER['REMOTE_ADDR']);\n" }, { "answer_id": 41915371, "author": "GMR", "author_id": 7484312, "author_profile": "https://Stackoverflow.com/users/7484312", "pm_score": 2, "selected": false, "text": "preg_replace(\"/^.+\\\\\\\\/\", \"\", $_SERVER[\"AUTH_USER\"]);\n" }, { "answer_id": 42653233, "author": "UserHelpNeeding02356", "author_id": 7356159, "author_profile": "https://Stackoverflow.com/users/7356159", "pm_score": -1, "selected": false, "text": "$user= shell_exec(\"echo %username%\"); \n echo \"user : $user\";\n" }, { "answer_id": 42819817, "author": "Purple Lady", "author_id": 4076116, "author_profile": "https://Stackoverflow.com/users/4076116", "pm_score": -1, "selected": false, "text": "get_current_user();\n$username = get_current_user();\necho $username;\n" }, { "answer_id": 45372797, "author": "PodTech.io", "author_id": 1842743, "author_profile": "https://Stackoverflow.com/users/1842743", "pm_score": 0, "selected": false, "text": "<?php \n$user = $_SERVER['REMOTE_USER'];\n$domain = getenv('USERDOMAIN');\n\n?>\n LoadModule authnz_sspi_module modules/mod_authnz_sspi.so\n\n<Directory \"/path/to/folder\">\n AllowOverride All\n Options ExecCGI\n AuthName \"SSPI Authentication\"\n AuthType SSPI\n SSPIAuth On\n SSPIAuthoritative On\n SSPIOmitDomain On\n Require valid-user\n Require user \"NT AUTHORITY\\ANONYMOUS LOGON\" denied\n</Directory>\n" }, { "answer_id": 57172609, "author": "NightwingDFMX", "author_id": 11827083, "author_profile": "https://Stackoverflow.com/users/11827083", "pm_score": 2, "selected": false, "text": "shell_exec(\"wmic computersystem get username\")\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
168,621
<p>I'm having trouble with my php code not indenting correctly...</p> <p>I would like my code to look like this</p> <pre><code>if (foo) { print "i am indented"; } </code></pre> <p>but it always looks like this:</p> <pre><code>if (foo) { print "i am not indented correctly"; } </code></pre> <p>I tired googling for similar things and tried adding the following to my .emacs, but it didn't work at all.</p> <p>Any thoughts?</p> <pre><code> (add-hook 'php-mode-hook (function (lambda () ;; GNU style (setq php-indent-level 4 php-continued-statement-offset 4 php-continued-brace-offset 0 php-brace-offset 0 php-brace-imaginary-offset 0 php-label-offset -4)))) </code></pre>
[ { "answer_id": 171798, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "(defun my-build-tab-stop-list (width)\n (let ((num-tab-stops (/ 80 width))\n (counter 1)\n (ls nil))\n (while (<= counter num-tab-stops)\n (setq ls (cons (* width counter) ls))\n (setq counter (1+ counter)))\n (nreverse ls)))\n\n(add-hook 'c-mode-common-hook\n #'(lambda ()\n ;; You an remove this, if you don't want fixed tab-stop-widths\n (set (make-local-variable 'tab-stop-list)\n (my-build-tab-stop-list tab-width))\n (setq c-basic-offset tab-width)\n (c-set-offset 'defun-block-intro tab-width)\n (c-set-offset 'arglist-intro tab-width)\n (c-set-offset 'arglist-close 0)\n (c-set-offset 'defun-close 0)\n (setq abbrev-mode nil)))\n" }, { "answer_id": 485553, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 4, "selected": false, "text": "(setq c-default-style \"bsd\"\n c-basic-offset 4)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
168,639
<p>In Java, suppose I have a String variable S, and I want to search for it inside of another String T, like so:</p> <pre><code> if (T.matches(S)) ... </code></pre> <p>(note: the above line was T.contains() until a few posts pointed out that that method does not use regexes. My bad.)</p> <p>But now suppose S may have unsavory characters in it. For instance, let S = "[hi". The left square bracket is going to cause the regex to fail. Is there a function I can call to escape S so that this doesn't happen? In this particular case, I would like it to be transformed to "\[hi".</p>
[ { "answer_id": 168662, "author": "Aaron", "author_id": 19130, "author_profile": "https://Stackoverflow.com/users/19130", "pm_score": 0, "selected": false, "text": " String S = \"\\\\[hi\"\n \\[hi\n if (T.indexOf(\"[hi\") != -1) {\n" }, { "answer_id": 168884, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 4, "selected": false, "text": "if (T.matches(\"\\\\Q\" + S + \"\\\\E\"))\n Pattern sPattern = Pattern.compile(S, Pattern.LITERAL);\nif (sPattern.matcher(T).matches()) { /* do something */ }\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24973/" ]
168,659
<p>I found this via google: <a href="http://www.mvps.org/access/api/api0008.htm" rel="nofollow noreferrer">http://www.mvps.org/access/api/api0008.htm</a></p> <pre class="lang-vb prettyprint-override"><code>'******************** Code Start ************************** ' This code was originally written by Dev Ashish. ' It is not to be altered or distributed, ' except as part of an application. ' You are free to use it in any application, ' provided the copyright notice is left unchanged. ' ' Code Courtesy of ' Dev Ashish ' Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _ "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long Function fOSUserName() As String ' Returns the network login name Dim lngLen As Long, lngX As Long Dim strUserName As String strUserName = String$(254, 0) lngLen = 255 lngX = apiGetUserName(strUserName, lngLen) If ( lngX &gt; 0 ) Then fOSUserName = Left$(strUserName, lngLen - 1) Else fOSUserName = vbNullString End If End Function '******************** Code End ************************** </code></pre> <p>Is this the best way to do it?</p>
[ { "answer_id": 168682, "author": "bugBurger", "author_id": 13337, "author_profile": "https://Stackoverflow.com/users/13337", "pm_score": 1, "selected": false, "text": "For Each strComputer In arrComputers\n Set objWMIService = GetObject(\"winmgmts:\\\\\" & strComputer & \"\\root\\cimv2\")\n Set colItems = objWMIService.ExecQuery(\"Select * from Win32_ComputerSystem\",,48)\n For Each objItem in colItems\n Wscript.Echo \"UserName: \" & objItem.UserName & \" is logged in at computer \" & strComputer\nNext\n" }, { "answer_id": 168686, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 4, "selected": false, "text": "Set WshNetwork = CreateObject(\"WScript.Network\")\nPrint WshNetwork.UserName\n" }, { "answer_id": 168986, "author": "Knox", "author_id": 4873, "author_profile": "https://Stackoverflow.com/users/4873", "pm_score": 2, "selected": false, "text": "Function UserNameWindows() As String\n UserNameWindows = VBA.Environ(\"USERNAME\") & \"@\" & VBA.Environ(\"USERDOMAIN\")\nEnd Function\n" }, { "answer_id": 19719939, "author": "Harsono", "author_id": 2943641, "author_profile": "https://Stackoverflow.com/users/2943641", "pm_score": 0, "selected": false, "text": "Set objWMIService = GetObject(\"winmgmts:\" & \"{impersonationLevel=impersonate}!\\\\\" & strIP & \"\\root\\cimv2\")\nSet colProcessList = objWMIService.ExecQuery(\"Select * from Win32_Process\")\nFor Each objprocess In colProcessList\n colProperties = objprocess.GetOwner(strNameOfUser, strUserDomain)\n If objprocess.Name = \"explorer.exe\" Then\n UsrName = strNameOfUser\n DmnName = strUserDomain\n End If\nNext\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2462/" ]
168,661
<p>I have a table with one column and about ten rows. The first column has rows with text as row headers, "header 1", "header 2". The second column contains fields for the user to type data (<em>textboxes</em> and <em>checkboxes</em>). </p> <p>I want to have a button at the top labelled "<em>Add New...</em>", and have it create a third column, with the same fields as the first column. If the user clicks it again, it will create another blank column with fields (as in the second column).</p> <p>Does anyone know of an effective way to manipulate the DOM to achieve this?</p> <p>I'm experimenting with <code>div</code>'s and <code>TABLES</code> but i'm on my third day of doing this, and it feels harder than it should be.</p>
[ { "answer_id": 168670, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "function(table)\n{\n for(var i=0;i<table.rows.length;i++)\n {\n newcell = table.rows[i].cells[0].cloneNode(true);\n table.rows[i].appendChild(newcell);\n }\n}\n" }, { "answer_id": 168889, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function AddColumn(tableId)\n{\n var table = document.getElementById(tableId);\n if (table == undefined) return;\n var rowNb = table.rows.length;\n // Take care of header\n var bAddNames = (table.tHead.rows[0].cells.length % 2 == 1);\n var newcell = table.rows[0].cells[bAddNames ? 1 : 0].cloneNode(true);\n table.rows[0].appendChild(newcell);\n // Add the remainder of the column\n for(var i = 1; i < rowNb; i++)\n {\n newcell = table.rows[i].cells[0].cloneNode(bAddNames);\n table.rows[i].appendChild(newcell);\n }\n}\n <input type=\"button\" id=\"BSO\" value=\"Add\" onclick=\"javascript:AddColumn('TSO')\"/>\n<table border=\"1\" id=\"TSO\">\n<thead>\n<tr><th>Fields</th><th>Data</th></tr>\n</thead>\n<tbody>\n<tr><td>Doh</td><td>10</td></tr>\n<tr><td>Toh</td><td>20</td></tr>\n<tr><td>Foo</td><td>30</td></tr>\n<tr><td>Bar</td><td>42</td></tr>\n<tr><td>Ga</td><td>50</td></tr>\n<tr><td>Bu</td><td>666</td></tr>\n<tr><td>Zo</td><td>70</td></tr>\n<tr><td>Meu</td><td>80</td></tr>\n</tbody>\n</table>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
168,664
<p>Given a table or a temp table, I'd like to run a procedure that will output a SQL script (i.e. a bunch of INSERT statements) that would populate the table. Is this possible in MS SQL Server 2000?</p>
[ { "answer_id": 168670, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "function(table)\n{\n for(var i=0;i<table.rows.length;i++)\n {\n newcell = table.rows[i].cells[0].cloneNode(true);\n table.rows[i].appendChild(newcell);\n }\n}\n" }, { "answer_id": 168889, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function AddColumn(tableId)\n{\n var table = document.getElementById(tableId);\n if (table == undefined) return;\n var rowNb = table.rows.length;\n // Take care of header\n var bAddNames = (table.tHead.rows[0].cells.length % 2 == 1);\n var newcell = table.rows[0].cells[bAddNames ? 1 : 0].cloneNode(true);\n table.rows[0].appendChild(newcell);\n // Add the remainder of the column\n for(var i = 1; i < rowNb; i++)\n {\n newcell = table.rows[i].cells[0].cloneNode(bAddNames);\n table.rows[i].appendChild(newcell);\n }\n}\n <input type=\"button\" id=\"BSO\" value=\"Add\" onclick=\"javascript:AddColumn('TSO')\"/>\n<table border=\"1\" id=\"TSO\">\n<thead>\n<tr><th>Fields</th><th>Data</th></tr>\n</thead>\n<tbody>\n<tr><td>Doh</td><td>10</td></tr>\n<tr><td>Toh</td><td>20</td></tr>\n<tr><td>Foo</td><td>30</td></tr>\n<tr><td>Bar</td><td>42</td></tr>\n<tr><td>Ga</td><td>50</td></tr>\n<tr><td>Bu</td><td>666</td></tr>\n<tr><td>Zo</td><td>70</td></tr>\n<tr><td>Meu</td><td>80</td></tr>\n</tbody>\n</table>\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17997/" ]
168,672
<p>I have a table on SQL2000 with a numeric column and I need the select to return a 01, 02, 03...</p> <p>It currently returns 1,2,3,...10,11...</p> <p>Thanks.</p>
[ { "answer_id": 168689, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "SELECT REPLACE(STR(mycolumn, 2), ' ', '0')\n" }, { "answer_id": 168739, "author": "Patrick Szalapski", "author_id": 7453, "author_profile": "https://Stackoverflow.com/users/7453", "pm_score": 0, "selected": false, "text": "select case when mycolumn between -9 and 9 then '0' + str(mycolumn) else str(mycolumn) end \n" }, { "answer_id": 168796, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 0, "selected": false, "text": "select right('0'+ltrim(str(n)),2)\n select right(str(100+n),2)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/212/" ]
168,691
<p>If I'm deep in a nest of loops I'm wondering which of these is more efficient:</p> <pre><code>if (!isset($array[$key])) $array[$key] = $val; </code></pre> <p>or</p> <pre><code>$array[$key] = $val; </code></pre> <p>The second form is much more desirable as far as readable code goes. In reality the names are longer and the array is multidimensional. So the first form ends up looking pretty gnarly in my program.</p> <p>But I'm wondering if the second form might be slower. Since the code is in one of the most frequently-executed functions in the program, I'd like to use the faster form.</p> <p>Generally speaking this code will execute many times with the same value of "$key". So in most cases $array[$key] will already be set, and the isset() will return FALSE.</p> <p>To clarify for those who fear that I'm treating non-identical code as if it were identical: as far as this part of the program is concerned, $val is a constant. It isn't known until run-time, but it's set earlier in the program and doesn't change here. So both forms produce the same result. And this is the most convenient place to get at $val.</p>
[ { "answer_id": 168820, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "$array[$key] $array[$key] $val $array[$key] $val $array[$key]" }, { "answer_id": 168824, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 0, "selected": false, "text": "isset()" }, { "answer_id": 168841, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 3, "selected": false, "text": "array_key_exists($key, $array) isset($array[$key])" }, { "answer_id": 168857, "author": "Tony L.", "author_id": 21905, "author_profile": "https://Stackoverflow.com/users/21905", "pm_score": 0, "selected": false, "text": "$array[$key] = !isset($array[$key]) ? $val : $array[$key];\n" }, { "answer_id": 487447, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "$anArray[ 'level1' ][ 'level2' ][ 'level3' ] = ...\n $anArray[ 'level1' ][ 'level2' ]\n <?php\n\nfunction create_array_path( $path, & $inArray )\n{\n if ( ! is_array( $inArray ) )\n {\n throw new Exception( 'The second argument is not an array!' );\n }\n $traversed = array();\n $current = &$inArray;\n\n foreach( $path as $subpath )\n {\n $traversed[] = $subpath;\n if ( ! is_array( $current ) )\n {\n $current = array();\n }\n if ( ! array_key_exists( $subpath, $current ) )\n {\n $current[ $subpath ] = '';\n }\n $current = &$current[ $subpath ];\n }\n}\n\n\n$myArray = array();\n\ncreate_array_path( array( 'level1', 'level2', 'level3' ), $myArray );\n\nprint_r( $myArray );\n\n?>\n Array\n (\n [level1] => Array\n (\n [level2] => Array\n (\n [level3] => \n )\n\n )\n\n )\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8722/" ]
168,727
<p>A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow noreferrer">Python 2.6</a>), for instance, are found in the <a href="http://docs.python.org/library/collections.html" rel="nofollow noreferrer">collections</a> module. </p> <p>The <a href="http://docs.python.org/library/" rel="nofollow noreferrer">Library Documentation page</a> will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it <em>this way</em> using Python!" unless the important features in the language are pointed out by the experienced developers.</p> <p>I'm <strong>not</strong> specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.</p>
[ { "answer_id": 168768, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 4, "selected": false, "text": "multiprocessing threading Queue Lock" }, { "answer_id": 168795, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "json simplejson json.dumps(obj) json.loads(string)" }, { "answer_id": 335299, "author": "Dutch Masters", "author_id": 42037, "author_profile": "https://Stackoverflow.com/users/42037", "pm_score": 3, "selected": true, "text": "os, os.path \n sys \n unittest \n logging \n datetime \n ConfigParser \n socket, urllib \n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8669/" ]
168,732
<p>.NET has System.Uri for Uris and System.IO.FileInfo for file paths. I am looking for classes which are traditionally object oriented in that they specify both meaning and behavior for the string which is used in the object's construction. What other useful string encapsulation classes exist?</p> <p>Things such as regular expressions and StringBuilders are useful for the gross manipulation of strings but they aren't what I'm looking for.</p>
[ { "answer_id": 168782, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "using (System.Security.SecureString password = new System.Security.SecureString())\n{\n password.AppendChar('s');\n password.AppendChar('e');\n password.AppendChar('c');\n password.AppendChar('r');\n password.AppendChar('e');\n password.AppendChar('t');\n password.MakeReadOnly();\n}\n" }, { "answer_id": 185230, "author": "hangy", "author_id": 11963, "author_profile": "https://Stackoverflow.com/users/11963", "pm_score": 2, "selected": false, "text": "System.Net.Mail.MailAddress someMailAddress = new System.Net.Mail.MailAddress(\"me@example.org\", \"John Doe\");\nSystem.Console.WriteLine(someMailAddress.Address); // me@example.org\nSystem.Console.WriteLine(someMailAddress.User); // me\nSystem.Console.WriteLine(someMailAddress.Host); // example.org\nSystem.Console.WriteLine(someMailAddress.DisplayName); // John Doe\nSystem.Console.WriteLine(someMailAddress); // \"John Doe\" <me@example.org>\n" }, { "answer_id": 207372, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 2, "selected": false, "text": "Guid id = Guid.NewGuid()\nConsole.WriteLine(id);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9251/" ]
168,736
<p>How do you set a default value for a MySQL Datetime column?</p> <p>In SQL Server it's <code>getdate()</code>. What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.</p>
[ { "answer_id": 168832, "author": "sebthebert", "author_id": 24820, "author_profile": "https://Stackoverflow.com/users/24820", "pm_score": 11, "selected": true, "text": "mysql> create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP);\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> desc test;\n+-------+-------------+------+-----+-------------------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+-------------------+-------+\n| str | varchar(32) | YES | | NULL | | \n| ts | timestamp | NO | | CURRENT_TIMESTAMP | | \n+-------+-------------+------+-----+-------------------+-------+\n2 rows in set (0.00 sec)\n\nmysql> insert into test (str) values (\"demo\");\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> select * from test;\n+------+---------------------+\n| str | ts |\n+------+---------------------+\n| demo | 2008-10-03 22:59:52 | \n+------+---------------------+\n1 row in set (0.00 sec)\n\nmysql>\n" }, { "answer_id": 1483959, "author": "Stephan Unrau", "author_id": 179792, "author_profile": "https://Stackoverflow.com/users/179792", "pm_score": 7, "selected": false, "text": "SET NEW.DateCreated=NOW()" }, { "answer_id": 1552804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "ALTER TABLE `test_table`\n CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',\n CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;\n CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`\n FOR EACH ROW SET NEW.created_dt = NOW();\n" }, { "answer_id": 4979548, "author": "Donald", "author_id": 614409, "author_profile": "https://Stackoverflow.com/users/614409", "pm_score": 5, "selected": false, "text": "CREATE TABLE `MyTable` (\n`MyTable_ID` int UNSIGNED NOT NULL AUTO_INCREMENT ,\n`MyData` varchar(10) NOT NULL ,\n`CreationDate` datetime NULL ,\n`UpdateDate` datetime NULL ,\nPRIMARY KEY (`MyTable_ID`)\n)\n;\n\nCREATE TRIGGER `MyTable_INSERT` BEFORE INSERT ON `MyTable`\nFOR EACH ROW BEGIN\n -- Set the creation date\n SET new.CreationDate = now();\n\n -- Set the udpate date\n Set new.UpdateDate = now();\nEND;\n\nCREATE TRIGGER `MyTable_UPDATE` BEFORE UPDATE ON `MyTable`\nFOR EACH ROW BEGIN\n -- Set the udpate date\n Set new.UpdateDate = now();\nEND;\n" }, { "answer_id": 5430103, "author": "Drawin Kumar", "author_id": 676350, "author_profile": "https://Stackoverflow.com/users/676350", "pm_score": 3, "selected": false, "text": "DELIMITER //\nCREATE TRIGGER `MyTable_UPDATE` BEFORE UPDATE ON `MyTable`\nFOR EACH ROW BEGIN\n -- Set the udpate date\n Set new.UpdateDate = now();\nEND//\nDELIMITER ;\n" }, { "answer_id": 5731720, "author": "John Larson", "author_id": 556250, "author_profile": "https://Stackoverflow.com/users/556250", "pm_score": 7, "selected": false, "text": "CREATE TRIGGER myTable_OnInsert BEFORE INSERT ON `tblMyTable`\n FOR EACH ROW SET NEW.dateAdded = NOW();\n INSERT INTO tblMyTable(name, dateAdded) VALUES('Alice', '2010-01-03 04:30:43');\n CREATE TRIGGER myTable_OnInsert BEFORE INSERT ON `tblMyTable`\n FOR EACH ROW SET NEW.dateAdded = IFNULL(NEW.dateAdded, NOW());\n" }, { "answer_id": 6444073, "author": "Augiwan", "author_id": 770035, "author_profile": "https://Stackoverflow.com/users/770035", "pm_score": 5, "selected": false, "text": "ALTER TABLE `table_name` CHANGE `column_name` DATETIME NOT NULL DEFAULT 0\n" }, { "answer_id": 8275966, "author": "George", "author_id": 1066382, "author_profile": "https://Stackoverflow.com/users/1066382", "pm_score": 3, "selected": false, "text": "DATETIME INSERT INTO Yourtable (Field1, YourDateField) VALUES('val1', (select now()))\n" }, { "answer_id": 8860822, "author": "Samuel", "author_id": 1149021, "author_profile": "https://Stackoverflow.com/users/1149021", "pm_score": 3, "selected": false, "text": "ALTER TABLE `table_name` CHANGE `column_name` `column_name` \nTIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;\n" }, { "answer_id": 10603198, "author": "Gustav Bertram", "author_id": 1005039, "author_profile": "https://Stackoverflow.com/users/1005039", "pm_score": 9, "selected": false, "text": "CREATE TABLE foo (\n `creation_time` DATETIME DEFAULT CURRENT_TIMESTAMP,\n `modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP\n)\n" }, { "answer_id": 13840008, "author": "Fathah Rehman P", "author_id": 991065, "author_profile": "https://Stackoverflow.com/users/991065", "pm_score": 2, "selected": false, "text": "CREATE TABLE `testtable` (\n `id` INT(10) NULL DEFAULT NULL,\n `colname` DATETIME NULL DEFAULT '1999-12-12 12:12:12'\n)\n colname" }, { "answer_id": 15012579, "author": "Steven Lloyd", "author_id": 888870, "author_profile": "https://Stackoverflow.com/users/888870", "pm_score": 4, "selected": false, "text": "ALTER TABLE mytable CHANGE mydate datetime NOT NULL DEFAULT 'CURRENT_TIMESTAMP'\n" }, { "answer_id": 28607663, "author": "Lucas Moyano Angelini", "author_id": 2372187, "author_profile": "https://Stackoverflow.com/users/2372187", "pm_score": 0, "selected": false, "text": "/************ ROLE ************/\ndrop table if exists `role`;\ncreate table `role` (\n `id_role` bigint(20) unsigned not null auto_increment,\n `date_created` datetime,\n `date_deleted` datetime,\n `name` varchar(35) not null,\n `description` text,\n primary key (`id_role`)\n) comment='';\n\ndrop trigger if exists `role_date_created`;\ncreate trigger `role_date_created` before insert\n on `role`\n for each row \n set new.`date_created` = now();" }, { "answer_id": 36374254, "author": "Evhz", "author_id": 5476782, "author_profile": "https://Stackoverflow.com/users/5476782", "pm_score": 4, "selected": false, "text": "ALTER TABLE table_name CHANGE date_column datetime NOT NULL DEFAULT '0000-00-00 00:00:00'\n ALTER TABLE table_name CHANGE date_column datetime NOT NULL DEFAULT '1000-01-01 00:00:00'\n" }, { "answer_id": 39571278, "author": "Rana Aalamgeer", "author_id": 3611036, "author_profile": "https://Stackoverflow.com/users/3611036", "pm_score": 1, "selected": false, "text": "DELIMITER $$\n\n CREATE TRIGGER bu_table1_each BEFORE UPDATE ON table1 FOR EACH ROW\n BEGIN\n SET new.datefield = NOW();\n END $$\n\n DELIMITER ;\n" }, { "answer_id": 41020080, "author": "Saveendra Ekanayake", "author_id": 3103802, "author_profile": "https://Stackoverflow.com/users/3103802", "pm_score": 5, "selected": false, "text": "ALTER TABLE <TABLE_NAME> \nCHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;\n ALTER TABLE <TABLE_NAME> \nCHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT '2015-05-11 13:01:01';\n" }, { "answer_id": 51533959, "author": "Deepak N", "author_id": 8746415, "author_profile": "https://Stackoverflow.com/users/8746415", "pm_score": 2, "selected": false, "text": "CREATE TABLE defaultforTime(\n `creation_time` DATETIME DEFAULT CURRENT_TIMESTAMP,\n `modification_time` DATETIME default now()\n);\n" }, { "answer_id": 60247492, "author": "Gvs Akhil", "author_id": 7737777, "author_profile": "https://Stackoverflow.com/users/7737777", "pm_score": 3, "selected": false, "text": "CREATE TABLE `users` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,\n `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n PRIMARY KEY (`id`),\n UNIQUE KEY `mobile_UNIQUE` (`mobile`)\n ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n" }, { "answer_id": 64212095, "author": "Bhargav Variya", "author_id": 12479629, "author_profile": "https://Stackoverflow.com/users/12479629", "pm_score": 2, "selected": false, "text": "ON UPDATE CURRENT_TIMESTAMP CREATE TABLE bar(\n `create_time` TIMESTAMP CURRENT_TIMESTAMP,\n `update_time` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP\n )\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
168,738
<p>I am building the diagram component in JavaScript. It has two layers rendered separately: foreground and background.</p> <p>To determine the required size of the background:</p> <ol> <li>render the foreground </li> <li>measure the height of the result</li> <li>render the foreground and the background together</li> </ol> <p>In code it looks like this:</p> <pre><code>var foreground = renderForegroundIntoString(); parentDiv.innerHTML = foreground; var height = parentDiv.children[0].clientHeight; var background = renderBackgroundIntoString(height); parentDiv.innerHTML = foreground + background; </code></pre> <p>Using IE7, this is a piece of cake. However, Firefox2 is not really willing to render the <code>parentDiv.innerHTML</code> right away, therefore I cannot read out the foreground height.</p> <p>When does Firefox execute the rendering and how can I delay my background generation till foreground rendering is completed, or is there any alternative way to determine the height of my foreground elements?</p> <p>[Appended after testing Dan's answer (thanx Dan)]</p> <p>Within the body of the callback method (called back by <code>setTimeout(...))</code> I can see, the rendering of the <code>innerHTML</code> is still not complete. </p>
[ { "answer_id": 168767, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 2, "selected": false, "text": "setTimeout(renderBackground, 0)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24451/" ]
168,798
<p>I've exposed several web services in our product using Java and WS-Security. One of our customers wants to consume the web service using ColdFusion. Does ColdFusion support WS-Security? Can I get around it by writing a Java client and using that in ColdFusion?</p> <p>(I don't know much about ColdFusion).</p>
[ { "answer_id": 178131, "author": "Jason", "author_id": 3242, "author_profile": "https://Stackoverflow.com/users/3242", "pm_score": 4, "selected": true, "text": "<cfset local.soapHeader = xmlNew()>\n<cfset local.soapHeader.TheSoapHeader = xmlElemNew(local.soapHeader, \"http://someurl.com/\", \"TheSoapHeader\")>\n<cfset local.soapHeader.TheSoapHeader.UserName.XmlText = \"foo\">\n<cfset local.soapHeader.TheSoapHeader.UserName.XmlAttributes[\"xsi:type\"] = \"xsd:string\">\n\n<cfset local.soapHeader.TheSoapHeader = xmlElemNew(local.soapHeader, \"http://webserviceUrl.com/\", \"TheSoapHeader\")>\n<cfset local.soapHeader.TheSoapHeader.Password.XmlText = \"bar\">\n<cfset local.soapHeader.TheSoapHeader.Password.XmlAttributes[\"xsi:type\"] = \"xsd:string\">\n\n<cfset theWebService = createObject(\"webservice\",\"http://webserviceUrl.com/Webservice.asmx?WSDL\")>\n<cfset addSOAPRequestHeader(theWebService, \"ignoredNameSpace\", \"ignoredName\", local.soapHeader, false)>\n\n<cfset aResponse = theWebService.SomeMethod(arg1)>\n" }, { "answer_id": 11567405, "author": "williambq", "author_id": 1200607, "author_profile": "https://Stackoverflow.com/users/1200607", "pm_score": 2, "selected": false, "text": "Local['soapHeader'] = xmlNew();\nLocal['soapHeader']['UsernameToken'] = xmlElemNew(local.soapHeader, \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\", \"UsernameToken\");\nLocal['soapHeader']['UsernameToken']['username'] = xmlElemNew(local.soapHeader, \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\", \"username\");\nLocal['soapHeader']['UsernameToken']['username'].XmlText = Arguments.szUserName;\nLocal['soapHeader']['UsernameToken']['username'].XmlAttributes[\"xsi:type\"] = \"xsd:string\";\nLocal['soapHeader']['UsernameToken']['password'] = xmlElemNew(local.soapHeader, \"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\", \"password\");\nLocal['soapHeader']['UsernameToken']['password'].XmlText = Arguments.szPassword;\nLocal['soapHeader']['UsernameToken']['password'].XmlAttributes[\"xsi:type\"] = \"xsd:string\";\naddSOAPRequestHeader(ws, \"ignoredNameSpace\", \"ignoredName\", Local.soapHeader, false);\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
168,826
<p>In ASP.net 2.0, the PreviousPage property of a web page does not have a ViewState collection. I want to use this collection to transfer information between pages.</p>
[ { "answer_id": 168888, "author": "Keith Walton", "author_id": 22448, "author_profile": "https://Stackoverflow.com/users/22448", "pm_score": 0, "selected": false, "text": "<%@ previouspagetype virtualpath=\"~/firstpage.aspx\" %>\n If (Not MyBase.IsPostBack) Then\n\n _someValue = Me.PreviousPage.SomeValue\n\nEnd If\n" }, { "answer_id": 6609609, "author": "jekcom", "author_id": 830285, "author_profile": "https://Stackoverflow.com/users/830285", "pm_score": 1, "selected": false, "text": "public class BaseCrossPage:System.Web.UI.Page\n{\n public List<Guid> Invitees = new List<Guid>();\n\n}\n public partial class Default : BaseCrossPage\n{\n\n protected void Page_Load(object sender, EventArgs e)\n {\n\n this.Invitees = LoadInvitees();\n }\n\n\n}\n public partial class secondPage : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n\n BaseCrossPage p = (BaseCrossPage)PreviousPage;\n List<Guid> Invitees = p.InvitedTeams\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22448/" ]
168,833
<p>I wish to perform an experiment many different times. After every trial, I am left with a "large" set of output statistics -- let's say, 1000. I would like to store the outputs of my experiments in a table, but what's the best way...?</p> <h3>Option 1</h3> <p>Have a table with 1000 columns. Seems like a bad idea. What if the number of statistics one day exceeds the maximum number of columns?</p> <h3>Option 2</h3> <p>Have a table with three columns. Let's say, ID, StatisticType, and StatisticValue. That way, you can have as many statistics as you want. However, reading a single experiments statistics becomes more complicated. Moreover, what if different statistics are different data types??</p> <p>Any suggestions?</p>
[ { "answer_id": 168850, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 0, "selected": false, "text": "SELECT * FROM table WHERE Experiment = 5;" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
168,838
<p>I am trying to visualize some values on a form. They range from 0 to 200 and I would like the ones around 0 be green and turn bright red as they go to 200. </p> <p>Basically the function should return color based on the value inputted. Any ideas ?</p>
[ { "answer_id": 168846, "author": "Peter Parker", "author_id": 23264, "author_profile": "https://Stackoverflow.com/users/23264", "pm_score": 3, "selected": false, "text": "red = (float)val / 200 * 255;\n\ngreen = (float)(200 - val) / 200 * 255;\n\nblue = 0;\n\nreturn red << 16 + green << 8 + blue;\n" }, { "answer_id": 168863, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "R = R1 * (200-i)/200 + R2 * i/200\nG = G1 * (200-i)/200 + G2 * i/200\nB = B1 * (200-i)/200 + B2 * i/200\n" }, { "answer_id": 168877, "author": "eaolson", "author_id": 23669, "author_profile": "https://Stackoverflow.com/users/23669", "pm_score": 3, "selected": false, "text": "H = 0.4 * value + 120\n" }, { "answer_id": 168974, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": true, "text": "function transition(value, maximum, start_point, end_point):\n return start_point + (end_point - start_point)*value/maximum\n function transition3(value, maximum, (s1, s2, s3), (e1, e2, e3)):\n r1= transition(value, maximum, s1, e1)\n r2= transition(value, maximum, s2, e2)\n r3= transition(value, maximum, s3, e3)\n return (r1, r2, r3)\n function rgb_to_hsv(r, g, b):\n maxc= max(r, g, b)\n minc= min(r, g, b)\n v= maxc\n if minc == maxc then return (0, 0, v)\n diff= maxc - minc\n s= diff / maxc\n rc= (maxc - r) / diff\n gc= (maxc - g) / diff\n bc= (maxc - b) / diff\n if r == maxc then\n h= bc - gc\n else if g == maxc then\n h= 2.0 + rc - bc\n else\n h = 4.0 + gc - rc\n h = (h / 6.0) % 1.0 //comment: this calculates only the fractional part of h/6\n return (h, s, v)\n\nfunction hsv_to_rgb(h, s, v):\n if s == 0.0 then return (v, v, v)\n i= int(floor(h*6.0)) //comment: floor() should drop the fractional part\n f= (h*6.0) - i\n p= v*(1.0 - s)\n q= v*(1.0 - s*f)\n t= v*(1.0 - s*(1.0 - f))\n if i mod 6 == 0 then return v, t, p\n if i == 1 then return q, v, p\n if i == 2 then return p, v, t\n if i == 3 then return p, q, v\n if i == 4 then return t, p, v\n if i == 5 then return v, p, q\n //comment: 0 <= i <= 6, so we never come here\n start_triplet= rgb_to_hsv(0, 255, 0) //comment: green converted to HSV\nend_triplet= rgb_to_hsv(255, 0, 0) //comment: accordingly for red\n\nmaximum= 200\n\n… //comment: value is defined somewhere here\n\nrgb_triplet_to_display= hsv_to_rgb(transition3(value, maximum, start_triplet, end_triplet))\n" }, { "answer_id": 168980, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "Red = max(value / 100, 1) * 255\nGreen = (1 - max(value / 100, 1)) * 255\nBlue = 0\n" }, { "answer_id": 9338274, "author": "Jon Lemmon", "author_id": 307438, "author_profile": "https://Stackoverflow.com/users/307438", "pm_score": 2, "selected": false, "text": "//comment: s = start_triplet, m = mid_triplet, e = end_triplet\nfunction transition3midpoint = (value, maximum, s, m, e):\n mid = maximum / 2\n if value < mid\n return transition3(value, mid, s, m)\n else\n return transition3(value - mid, mid, m, e)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4694/" ]
168,886
<p>I'm looking for a homegrown way to scramble production data for use in development and test. I've built a couple of scripts that make random social security numbers, shift birth dates, scramble emails, etc. But I've come up against a wall trying to scramble customer names. I want to keep real names so we can still use or searches so random letter generation is out. What I have tried so far is building a temp table of all last names in the table then updating the customer table with a random selection from the temp table. Like this:</p> <pre><code>DECLARE @Names TABLE (Id int IDENTITY(1,1),[Name] varchar(100)) /* Scramble the last names (randomly pick another last name) */ INSERT @Names SELECT LastName FROM Customer ORDER BY NEWID(); WITH [Customer ORDERED BY ROWID] AS (SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) AS ROWID, LastName FROM Customer) UPDATE [Customer ORDERED BY ROWID] SET LastName=(SELECT [Name] FROM @Names WHERE ROWID=Id) </code></pre> <p>This worked well in test, but completely bogs down dealing with larger amounts of data (>20 minutes for 40K rows)</p> <p>All of that to ask, how would you scramble customer names while keeping real names and the weight of the production data?</p> <p><strong>UPDATE:</strong> Never fails, you try to put all the information in the post, and you forget something important. This data will also be used in our sales &amp; demo environments which are publicly available. Some of the answers are what I am attempting to do, to 'switch' the names, but my question is literally, how to code in T-SQL?</p>
[ { "answer_id": 807426, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "DECLARE TABLE #Names \n(Id int IDENTITY(1,1),[Name] varchar(100))\n INSERT #Names\n SELECT LastName \n FROM Customer \n ORDER BY NEWID();\nWITH [Customer ORDERED BY ROWID] AS\n(SELECT ROW_NUMBER() OVER (ORDER BY NEWID()) AS ROWID, LastName FROM Customer)\n\nUPDATE [Customer ORDERED BY ROWID] \n\nSET LastName=(SELECT [Name] FROM #Names WHERE ROWID=Id)\n\nDROP TABLE #Names\n" }, { "answer_id": 38973047, "author": "AUR", "author_id": 2322668, "author_profile": "https://Stackoverflow.com/users/2322668", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION [dbo].[GenerateDummyValues]\n(\n @dataType varchar(100),\n @currentValue varchar(4000)=NULL\n)\nRETURNS varchar(4000)\nAS\nBEGIN\nIF @dataType = 'int'\n BEGIN\n Return '0'\n END\nELSE IF @dataType = 'varchar' OR @dataType = 'nvarchar' OR @dataType = 'char' OR @dataType = 'nchar'\n BEGIN\n Return 'AAAA'\n END\nELSE IF @dataType = 'datetime'\n BEGIN\n Return Convert(varchar(2000),GetDate())\n END\n-- you can add more checks, add complicated logic etc\nReturn 'XXX'\nEND\n select 'select ''update '' + TABLE_NAME + '' set '' + COLUMN_NAME + '' = '' + '''''''' + dbo.GenerateDummyValues( Data_type,'''') + '''''' where id = '' + Convert(varchar(10),Id) from INFORMATION_SCHEMA.COLUMNS, ' + table_name + ' where RIGHT(LOWER(COLUMN_NAME),2) <> ''id'' and TABLE_NAME = '''+ table_name + '''' + ';' from INFORMATION_SCHEMA.TABLES;\n select 'update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ' + '''' + dbo.GenerateDummyValues( Data_type,'') + ''' where id = ' + Convert(varchar(10),Id) from INFORMATION_SCHEMA.COLUMNS, Customers where RIGHT(LOWER(COLUMN_NAME),2) <> 'id' and TABLE_NAME = 'Customers';\nselect 'update ' + TABLE_NAME + ' set ' + COLUMN_NAME + ' = ' + '''' + dbo.GenerateDummyValues( Data_type,'') + ''' where id = ' + Convert(varchar(10),Id) from INFORMATION_SCHEMA.COLUMNS, Products where RIGHT(LOWER(COLUMN_NAME),2) <> 'id' and TABLE_NAME = 'Products';\n" }, { "answer_id": 44853526, "author": "S3S", "author_id": 6167855, "author_profile": "https://Stackoverflow.com/users/6167855", "pm_score": 1, "selected": false, "text": "declare @table table (ID int, PLAIN_TEXT nvarchar(4000))\ninsert into @table\nvalues\n(1,N'Some Dudes name'),\n(2,N'Another Person Name'),\n(3,N'Yet Another Name')\n\n--split your string into a column, and compute the decimal value (N) \nif object_id('tempdb..#staging') is not null drop table #staging\nselect \n substring(a.b, v.number+1, 1) as Val\n ,ascii(substring(a.b, v.number+1, 1)) as N\n --,dense_rank() over (order by b) as RN\n ,a.ID\ninto #staging\nfrom (select PLAIN_TEXT b, ID FROM @table) a\n inner join\n master..spt_values v on v.number < len(a.b)\nwhere v.type = 'P' \n\n--select * from #staging\n\n\n--create a fast tally table of numbers to be used to build the ROT-47 table.\n\n;WITH\n E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),\n E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows\n E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max\n cteTally(N) AS \n (\n SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4\n )\n\n\n\n--Here we put it all together with stuff and FOR XML\nselect \n PLAIN_TEXT\n ,ENCRYPTED_TEXT =\n stuff((\n select\n --s.Val\n --,s.N\n e.ENCRYPTED_TEXT\n from #staging s\n left join(\n select \n N as DECIMAL_VALUE\n ,char(N) as ASCII_VALUE\n ,case \n when 47 + N <= 126 then char(47 + N)\n when 47 + N > 126 then char(N-47)\n end as ENCRYPTED_TEXT\n from cteTally\n where N between 33 and 126) e on e.DECIMAL_VALUE = s.N\n where s.ID = t.ID\n FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')\nfrom @table t\n\n\n--or if you want really random\nselect \n PLAIN_TEXT\n ,ENCRYPTED_TEXT =\n stuff((\n select\n --s.Val\n --,s.N\n e.ENCRYPTED_TEXT\n from #staging s\n left join(\n select \n N as DECIMAL_VALUE\n ,char(N) as ASCII_VALUE\n ,char((select ROUND(((122 - N -1) * RAND() + N), 0))) as ENCRYPTED_TEXT\n from cteTally\n where (N between 65 and 122) and N not in (91,92,93,94,95,96)) e on e.DECIMAL_VALUE = s.N\n where s.ID = t.ID\n FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 0, '')\nfrom @table t\n" }, { "answer_id": 50242368, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 1, "selected": false, "text": "conv(substr(md5(first_name), 3),16,10) MySQL" }, { "answer_id": 54876405, "author": "mnemotronic", "author_id": 1368561, "author_profile": "https://Stackoverflow.com/users/1368561", "pm_score": 2, "selected": false, "text": "Original name Morphed name\nLoren Nimag\nJuanita Kuogewso\nTennyson Saggywig\nDavid Mijsm\nJulie Kunewa\n -- from https://stackoverflow.com/a/28712621\n\n-- Convert and return param as Title Case\n\nCREATE FUNCTION [dbo].[fnConvert_TitleCase] (@InputString VARCHAR(4000) )\nRETURNS VARCHAR(4000)AS\nBEGIN\nDECLARE @Index INT\nDECLARE @Char CHAR(1)\nDECLARE @OutputString VARCHAR(255)\n\nSET @OutputString = LOWER(@InputString)\nSET @Index = 2\nSET @OutputString = STUFF(@OutputString, 1, 1,UPPER(SUBSTRING(@InputString,1,1)))\n\nWHILE @Index <= LEN(@InputString)\nBEGIN\n SET @Char = SUBSTRING(@InputString, @Index, 1)\n IF @Char IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&','''','(','{','[','@')\n IF @Index + 1 <= LEN(@InputString)\n BEGIN\n IF @Char != '''' OR UPPER(SUBSTRING(@InputString, @Index + 1, 1)) != 'S'\n SET @OutputString = STUFF(@OutputString, @Index + 1, 1,UPPER(SUBSTRING(@InputString, @Index + 1, 1)))\n END\n SET @Index = @Index + 1\n END\n\n RETURN ISNULL(@OutputString,'')\n\nEND\nGo\n\n-- 00.045 x 0.045%\n-- 00.045 z 0.045%\n--\n-- Replace(Replace(Replace(TS_NAME,'x','#'),'z','x'),'#','z')\n--\n-- 00.456 k 0.456%\n-- 00.511 j 0.511%\n-- 00.824 v 0.824%\n-- kjv\n-- Replace(Replace(Replace(Replace(TS_NAME,'k','#'),'j','k'),'v','j'),'#','v')\n--\n-- 01.642 g 1.642%\n-- 02.284 n 2.284%\n-- 02.415 l 2.415%\n-- gnl\n-- Replace(Replace(Replace(Replace(TS_NAME,'g','#'),'n','g'),'l','n'),'#','l')\n--\n-- 02.826 r 2.826%\n-- 03.174 d 3.174%\n-- 03.826 m 3.826%\n-- rdm\n-- Replace(Replace(Replace(Replace(TS_NAME,'r','#'),'d','r'),'m','d'),'#','m')\n--\n-- 04.027 f 4.027%\n-- 04.200 h 4.200%\n-- 04.319 p 4.319%\n-- 04.434 b 4.434%\n-- 05.238 c 5.238%\n-- fhpbc\n-- Replace(Replace(Replace(Replace(Replace(Replace(TS_NAME,'f','#'),'h','f'),'p','h'),'b','p'),'c','b'),'#','c')\n--\n-- 05.497 w 5.497%\n-- 06.686 s 6.686%\n-- 15.978 t 15.978%\n-- wst\n-- Replace(Replace(Replace(Replace(TS_NAME,'w','#'),'s','w'),'t','s'),'#','t')\n--\n--\n-- 02.799 e 2.799%\n-- 07.294 i 7.294%\n-- 07.631 o 7.631%\n-- 11.682 a 11.682%\n-- eioa\n-- Replace(Replace(Replace(Replace(Replace(TS_NAME,'e','#'),'i','ew'),'o','i'),'a','o'),'#','a')\n--\n-- -- dont replace\n-- 00.222 q 0.222%\n-- 00.763 y 0.763%\n-- 01.183 u 1.183%\n\n-- Obfuscate a name\nSelect\n ts_id,\n Cast(ts_name as varchar(42)) as [Original Name]\n\n Cast(dbo.fnConvert_TitleCase(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(TS_NAME,'x','#'),'z','x'),'#','z'),'k','#'),'j','k'),'v','j'),'#','v'),'g','#'),'n','g'),'l','n'),'#','l'),'r','#'),'d','r'),'m','d'),'#','m'),'f','#'),'h','f'),'p','h'),'b','p'),'c','b'),'#','c'),'w','#'),'s','w'),'t','s'),'#','t'),'e','#'),'i','ew'),'o','i'),'a','o'),'#','a')) as VarChar(42)) As [morphed name] ,\n Cast(dbo.fnConvert_TitleCase(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(Replace(TS_NAME,'e','t'),'~','e'),'t','~'),'a','o'),'~','a'),'o','~'),'i','n'),'~','i'),'n','~'),'s','h'),'~','s'),'h','r'),'r','~'),'d','l'),'~','d'),'l','~'),'m','w'),'~','m'),'w','f'),'f','~'),'g','y'),'~','g'),'y','p'),'p','~'),'b','v'),'~','b'),'v','k'),'k','~'),'x','~'),'j','x'),'~','j')) as VarChar(42)) As [morphed name2]\n\nFrom\n ts_users\n;\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24991/" ]
168,891
<p>If I have a sorted list (say quicksort to sort), if I have a lot of values to add, is it better to suspend sorting, and add them to the end, then sort, or use binary chop to place the items correctly while adding them. Does it make a difference if the items are random, or already more or less in order?</p>
[ { "answer_id": 168934, "author": "Ihar Bury", "author_id": 18001, "author_profile": "https://Stackoverflow.com/users/18001", "pm_score": 0, "selected": false, "text": "List<T>" }, { "answer_id": 169424, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "O(n) O(log n) O(log n) O(n) O(n ^ 2) O(n log n) O(n log n)" }, { "answer_id": 170508, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 4, "selected": false, "text": "// Note that itemstoadd is modified as a side effect of this function\ntemplate<typename T>\nvoid AddToSortedList(std::list<T> & sortedlist, std::vector<T> & itemstoadd)\n{\n std::sort(itemstoadd.begin(), itemstoadd.end());\n std::list<T>::iterator listposition = sortedlist.begin();\n std::vector<T>::iterator nextnewitem = itemstoadd.begin();\n while ((listposition != sortedlist.end()) || (nextnewitem != itemstoadd.end()))\n {\n if ((listposition == sortedlist.end()) || (*nextnewitem < *listposition))\n sortedlist.insert(listposition, *nextnewitem++);\n else\n ++listposition;\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ]
168,897
<p>Is it more performant to have a bidimensional array (<code>type[,]</code>) or an array of arrays (<code>type[][]</code>) in C#?</p> <p>Particularly for initial allocation and item access</p>
[ { "answer_id": 169958, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "Size 1000, Repeat 1000\n int[,] set: 3460\n int[,] get: 4036 (chk=1304808064)\n int[][] set: 2441\n int[][] get: 1283 (chk=1304808064)\n using System;\nusing System.Diagnostics;\nstatic class Program\n{\n static void Main()\n {\n Console.WriteLine(\"First is just for JIT...\");\n Test(10,10);\n Console.WriteLine(\"Real numbers...\");\n Test(1000,1000);\n\n Console.ReadLine();\n }\n\n static void Test(int size, int repeat)\n {\n Console.WriteLine(\"Size {0}, Repeat {1}\", size, repeat);\n int[,] rect = new int[size, size];\n int[][] jagged = new int[size][];\n for (int i = 0; i < size; i++)\n { // don't count this in the metrics...\n jagged[i] = new int[size];\n }\n Stopwatch watch = Stopwatch.StartNew();\n for (int cycle = 0; cycle < repeat; cycle++)\n {\n for (int i = 0; i < size; i++)\n {\n for (int j = 0; j < size; j++)\n {\n rect[i, j] = i * j;\n }\n }\n }\n watch.Stop();\n Console.WriteLine(\"\\tint[,] set: \" + watch.ElapsedMilliseconds);\n\n int sum = 0;\n watch = Stopwatch.StartNew();\n for (int cycle = 0; cycle < repeat; cycle++)\n {\n for (int i = 0; i < size; i++)\n {\n for (int j = 0; j < size; j++)\n {\n sum += rect[i, j];\n }\n }\n }\n watch.Stop();\n Console.WriteLine(\"\\tint[,] get: {0} (chk={1})\", watch.ElapsedMilliseconds, sum);\n\n watch = Stopwatch.StartNew();\n for (int cycle = 0; cycle < repeat; cycle++)\n {\n for (int i = 0; i < size; i++)\n {\n for (int j = 0; j < size; j++)\n {\n jagged[i][j] = i * j;\n }\n }\n }\n watch.Stop();\n Console.WriteLine(\"\\tint[][] set: \" + watch.ElapsedMilliseconds);\n\n sum = 0;\n watch = Stopwatch.StartNew();\n for (int cycle = 0; cycle < repeat; cycle++)\n {\n for (int i = 0; i < size; i++)\n {\n for (int j = 0; j < size; j++)\n {\n sum += jagged[i][j];\n }\n }\n }\n watch.Stop();\n Console.WriteLine(\"\\tint[][] get: {0} (chk={1})\", watch.ElapsedMilliseconds, sum);\n }\n}\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
168,901
<pre><code>private IEnumerable&lt;string&gt; Tables { get { yield return "Foo"; yield return "Bar"; } } </code></pre> <p>Let's say I want iterate on those and write something like processing #n of #m. </p> <p>Is there a way I can find out the value of m without iterating before my main iteration?</p> <p>I hope I made myself clear.</p>
[ { "answer_id": 168922, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 10, "selected": true, "text": "IEnumerable IEnumerable ICollection<T> Count" }, { "answer_id": 168954, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "ulong.MaxValue" }, { "answer_id": 169699, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 7, "selected": false, "text": "Count() Count() Count() if( enumerable.Count != 0 ) Any() if( enumerable.Any() )" }, { "answer_id": 853401, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "Tables.ToList<string>().Count;\n" }, { "answer_id": 853478, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 8, "selected": false, "text": "System.Linq.Enumerable.Count IEnumerable<T> ICollection<T> c = source as ICollection<TSource>;\nif (c != null)\n return c.Count;\n\nint result = 0;\nusing (IEnumerator<T> enumerator = source.GetEnumerator())\n{\n while (enumerator.MoveNext())\n result++;\n}\nreturn result;\n ICollection<T> Count Count() IEnumerable<T>" }, { "answer_id": 853524, "author": "Samuel Jack", "author_id": 1727, "author_profile": "https://Stackoverflow.com/users/1727", "pm_score": 3, "selected": false, "text": "BackgroundWorker worker = new BackgroundWorker();\nworker.WorkerReportsProgress = true;\nworker.DoWork += (sender, e) =>\n {\n // pretend we have a collection of \n // items to process\n var items = 1.To(1000);\n items\n .WithProgressReporting(progress => worker.ReportProgress(progress))\n .ForEach(item => Thread.Sleep(10)); // simulate some real work\n };\n" }, { "answer_id": 1267328, "author": "Roman Golubin", "author_id": 155223, "author_profile": "https://Stackoverflow.com/users/155223", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Collections;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n var test = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };\n var result = test.Split(7);\n int cnt = 0;\n\n foreach (IEnumerable<int> chunk in result)\n {\n cnt = chunk.Count();\n Console.WriteLine(cnt);\n }\n cnt = result.Count();\n Console.WriteLine(cnt);\n Console.ReadLine();\n }\n }\n\n static class LinqExt\n {\n public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkLength)\n {\n if (chunkLength <= 0)\n throw new ArgumentOutOfRangeException(\"chunkLength\", \"chunkLength must be greater than 0\");\n\n IEnumerable<T> result = null;\n using (IEnumerator<T> enumerator = source.GetEnumerator())\n {\n while (enumerator.MoveNext())\n {\n result = GetChunk(enumerator, chunkLength);\n yield return result;\n }\n }\n }\n\n static IEnumerable<T> GetChunk<T>(IEnumerator<T> source, int chunkLength)\n {\n int x = chunkLength;\n do\n yield return source.Current;\n while (--x > 0 && source.MoveNext());\n }\n }\n}\n" }, { "answer_id": 5775421, "author": "prabug", "author_id": 723253, "author_profile": "https://Stackoverflow.com/users/723253", "pm_score": 2, "selected": false, "text": ".method public hidebysig static int32 Count<TSource>(class \n\n[mscorlib]System.Collections.Generic.IEnumerable`1<!!TSource> source) cil managed\n{\n .custom instance void System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 ) \n // Code size 85 (0x55)\n .maxstack 2\n .locals init (class [mscorlib]System.Collections.Generic.ICollection`1<!!TSource> V_0,\n class [mscorlib]System.Collections.ICollection V_1,\n int32 V_2,\n class [mscorlib]System.Collections.Generic.IEnumerator`1<!!TSource> V_3)\n IL_0000: ldarg.0\n IL_0001: brtrue.s IL_000e\n IL_0003: ldstr \"source\"\n IL_0008: call class [mscorlib]System.Exception System.Linq.Error::ArgumentNull(string)\n IL_000d: throw\n IL_000e: ldarg.0\n IL_000f: isinst class [mscorlib]System.Collections.Generic.ICollection`1<!!TSource>\n IL_0014: stloc.0\n IL_0015: ldloc.0\n IL_0016: brfalse.s IL_001f\n IL_0018: ldloc.0\n IL_0019: callvirt instance int32 class [mscorlib]System.Collections.Generic.ICollection`1<!!TSource>::get_Count()\n IL_001e: ret\n IL_001f: ldarg.0\n IL_0020: isinst [mscorlib]System.Collections.ICollection\n IL_0025: stloc.1\n IL_0026: ldloc.1\n IL_0027: brfalse.s IL_0030\n IL_0029: ldloc.1\n IL_002a: callvirt instance int32 [mscorlib]System.Collections.ICollection::get_Count()\n IL_002f: ret\n IL_0030: ldc.i4.0\n IL_0031: stloc.2\n IL_0032: ldarg.0\n IL_0033: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1<!0> class [mscorlib]System.Collections.Generic.IEnumerable`1<!!TSource>::GetEnumerator()\n IL_0038: stloc.3\n .try\n {\n IL_0039: br.s IL_003f\n IL_003b: ldloc.2\n IL_003c: ldc.i4.1\n IL_003d: add.ovf\n IL_003e: stloc.2\n IL_003f: ldloc.3\n IL_0040: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()\n IL_0045: brtrue.s IL_003b\n IL_0047: leave.s IL_0053\n } // end .try\n finally\n {\n IL_0049: ldloc.3\n IL_004a: brfalse.s IL_0052\n IL_004c: ldloc.3\n IL_004d: callvirt instance void [mscorlib]System.IDisposable::Dispose()\n IL_0052: endfinally\n } // end handler\n IL_0053: ldloc.2\n IL_0054: ret\n} // end of method Enumerable::Count\n" }, { "answer_id": 8908126, "author": "Oliver Kötter", "author_id": 1155881, "author_profile": "https://Stackoverflow.com/users/1155881", "pm_score": -1, "selected": false, "text": "IEnum<string>.ToArray<string>().Length" }, { "answer_id": 9023728, "author": "prosseek", "author_id": 260127, "author_profile": "https://Stackoverflow.com/users/260127", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Test\n{\n private IEnumerable<string> Tables\n {\n get {\n yield return \"Foo\";\n yield return \"Bar\";\n }\n }\n\n static void Main()\n {\n var x = new Test();\n Console.WriteLine(x.Tables.Count());\n }\n}\n" }, { "answer_id": 13191375, "author": "Shahidul Haque", "author_id": 739240, "author_profile": "https://Stackoverflow.com/users/739240", "pm_score": 3, "selected": false, "text": "IEnumberable if( iEnum.Cast<Object>().Count() > 0) \n{\n\n}\n GetDataTable(IEnumberable iEnum)\n{ \n if (iEnum != null && iEnum.Cast<Object>().Count() > 0) //--- proceed further\n\n}\n" }, { "answer_id": 17315323, "author": "Hugo", "author_id": 1496074, "author_profile": "https://Stackoverflow.com/users/1496074", "pm_score": -1, "selected": false, "text": "public int GetEnumerableCount(IEnumerable Enumerable)\n{\n return (from object Item in Enumerable\n select Item).Count();\n}\n" }, { "answer_id": 50210008, "author": "Me Hungry", "author_id": 8216382, "author_profile": "https://Stackoverflow.com/users/8216382", "pm_score": -1, "selected": false, "text": "((IList<string>)Table).Count\n" }, { "answer_id": 59611940, "author": "Abhas Bhoi", "author_id": 6832033, "author_profile": "https://Stackoverflow.com/users/6832033", "pm_score": 2, "selected": false, "text": "IEnumerable<T> enumList = ReturnFromSomeFunction();\n\nint count = new List<T>(enumList).Count;\n" }, { "answer_id": 61283708, "author": "Sowvik Roy", "author_id": 3706956, "author_profile": "https://Stackoverflow.com/users/3706956", "pm_score": 3, "selected": false, "text": "Enumerable.Count<TSource>(IEnumerable<TSource> source)\n" }, { "answer_id": 69828022, "author": "Russell McDonnell", "author_id": 4888238, "author_profile": "https://Stackoverflow.com/users/4888238", "pm_score": 2, "selected": false, "text": "Tables.TryGetNonEnumeratedCount(out var count)\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ]
168,912
<p>I need to show only one element at a time when a link is clicked on. Right now I'm cheating by hiding everything again and then toggling the element clicked on. This works, unless i want EVERYTHING to disappear again. Short of adding a "Hide All" button/link what can i do? I would like to be able to click on the link again, and hide it's content.</p> <p>EDIT: Pseudo's code would have worked, but the html here mistakenly led you to believe that all the links were in one div. instead of tracking down where they all were, it is easier to call them by their ID.</p> <p>Here's what I have so far:</p> <pre><code>$(document).ready(function(){ //hides everything $("#infocontent *").hide(); //now we show them by which they click on $("#linkjoedhit").click(function(event){ $("#infocontent *").hide(); $("#infojoedhit").toggle(); return false; }); $("#linkgarykhit").click(function(event){ $("#infocontent *").hide(); $("#infogarykhit").toggle(); return false; }); }); </code></pre> <p>and the html looks like:</p> <pre><code>&lt;div id="theircrappycode"&gt; &lt;a id="linkjoedhit" href=""&gt;Joe D&lt;/a&gt;&lt;br/&gt; &lt;a id="linkgarykhit" href=""&gt;Gary K&lt;/a&gt; &lt;/div&gt; &lt;div id="infocontent"&gt; &lt;p id="infojoedhit"&gt;Information about Joe D Hitting.&lt;/p&gt; &lt;p id="infogarykhit"&gt;Information about Gary K Hitting.&lt;/p&gt; &lt;/div </code></pre> <p>there are about 20 links like this. Because I am not coding the actual html, I have no control over the actual layout, which is horrendous. Suffice to say, this is the only way to organize the links/info.</p>
[ { "answer_id": 169036, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 3, "selected": true, "text": "$(\"#linkgarykhit\").click(function(){\n if($(\"#infogarykhit\").css('display') != 'none'){\n $(\"#infogarykhit\").hide();\n }else{\n $(\"#infocontent *\").hide();\n $(\"#infogarykhit\").show();\n }\n return false;\n});\n function toggleInfoContent(id){\n if($('#' + id).css('display') != 'none'){\n $('#' + id).hide();\n }else{\n $(\"#infocontent *\").hide();\n $('#' + id).show();\n }\n}\n\n$(\"#linkgarykhit\").click(function(){\n toggleInfoContent('infogarykhit');\n return false;\n});\n\n$(\"#linkbobkhit\").click(function(){\n toggleInfoContent('infobobkhit');\n return false;\n});\n" }, { "answer_id": 169062, "author": "MrChrister", "author_id": 24229, "author_profile": "https://Stackoverflow.com/users/24229", "pm_score": 0, "selected": false, "text": "jQuery function DoToggleMagic(strParagraphID) {\n strDisplayed = $(strParagraphID).css(\"display\");\n $(\"#infocontent *\").hide();\n if (strDisplayed == \"none\") \n $(strParagraphID).toggle();\n}\n$(document).ready(function(){\n //hides everything\n $(\"#infocontent *\").hide();\n\n //now we show them by which they click on\n $(\"#linkjoedhit\").click(function(event){\n DoToggleMagic(\"#infojoedhit\");\n return false;\n });\n\n $(\"#linkgarykhit\").click(function(event){\n DoToggleMagic(\"#infogarykhit\");\n return false;\n }); \n});\n" }, { "answer_id": 169160, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 2, "selected": false, "text": "$(document).ready( function () {\n $(\"#infocontent *\").hide();\n\n $(\"div#theircrappycode > a\").click(function(event){\n var toggleId = \"#\" + this.id.replace(/^link/,\"info\");\n $(\"#infocontent *\").not(toggleId).hide();\n $(toggleId).toggle();\n return false;\n });\n});\n" }, { "answer_id": 169939, "author": "Philip Tinney", "author_id": 14930, "author_profile": "https://Stackoverflow.com/users/14930", "pm_score": 1, "selected": false, "text": "$(document).ready(function(){\n $(\"#infocontent *\").hide();\n $(\"#theircrappycode > a\").click(statlink.togvis);\n});\nvar statlink = {\n visId: \"\",\n togvis: function(){\n $(\"#\" + statlink.visId).toggle();\n statlink.visId = $(this).attr(\"id\").replace(/link/, \"info\");\n $(\"#\" + statlink.visId).toggle();\n }\n};\n" } ]
2008/10/03
[ "https://Stackoverflow.com/questions/168912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50/" ]