qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
247,412
|
<p>I'm trying to log users out when the user's session timeout happens. Logging users out - in my case - requires modifying the user's "online" status in a database.<br>
I was thinking that I might be able to use the observer pattern to make something that would monitor the state of the user session and trigger a callback when the session expires - which would preserve the user's name so we can update the db. I'm not exactly sure where to begin on the session side. Can I tie a callback to the session's timeout? </p>
<p>are these things built into any available pear or zend session packages? I will use whatever I have to to make this happen!</p>
<p><br /><br />
<strong>UPDATE @ 16:33:</strong><br>
What if you have a system where users can interact with each other (but they can only interact with online users)? The user needs to know which other users are online currently.</p>
<p>If we simply check to see if the session is still alive on each page refresh, then after a timeout, the user is sent to a non-logged in page, but they are still listed as online in the system.</p>
<p>That method would be fine except that when we timeout the session, we lose the information about the user which could be used to log them out.</p>
<p><br /><br />
<strong>UPDATE @16:56:</strong><br>
right. Thanks. I agree...sort of ugly. I already have some slow polling of the server happening, so it would be quite easy to implement that method. It just seems like such a useful feature for a session handling package. Zend and PEAR both have session packages. </p>
|
[
{
"answer_id": 247687,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM Users WHERE LoggedIn=1 AND LastAccess > DATEADD(Minute,-20.GETDATE())\n"
},
{
"answer_id": 7735305,
"author": "Serj Sagan",
"author_id": 550975,
"author_profile": "https://Stackoverflow.com/users/550975",
"pm_score": 0,
"selected": false,
"text": "$session_id = 'session_id';\n$save_path = ini_get('session.save_path');\n\nif (! $save_path) {\n$save_path = '.'; // if this vlaue is blank, it defaults to the current directory\n}\n\nif (file_exists($save_path . '/sess_' $session_id)) {\nunlink($session_id); // or whatever your file is called\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,413
|
<p>Here's my binding source object: </p>
<pre><code>Public Class MyListObject
Private _mylist As New ObservableCollection(Of String)
Private _selectedName As String
Public Sub New(ByVal nameList As List(Of String), ByVal defaultName As String)
For Each name In nameList
_mylist.Add(name)
Next
_selectedName = defaultName
End Sub
Public ReadOnly Property MyList() As ObservableCollection(Of String)
Get
Return _mylist
End Get
End Property
Public ReadOnly Property SelectedName() As String
Get
Return _selectedName
End Get
End Property
End Class
</code></pre>
<p>Here is my XAML:</p>
<pre><code><Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
xmlns:local="clr-namespace:WpfApplication1"
>
<Window.Resources>
<ObjectDataProvider x:Key="MyListObject" ObjectInstance="" />
</Window.Resources>
<Grid>
<ComboBox Height="23"
Margin="24,91,53,0"
Name="ComboBox1"
VerticalAlignment="Top"
SelectedValue="{Binding Path=SelectedName, Source={StaticResource MyListObject}, Mode=OneWay}"
ItemsSource="{Binding Path=MyList, Source={StaticResource MyListObject}, Mode=OneWay}"
/>
<Button Height="23"
HorizontalAlignment="Left"
Margin="47,0,0,87"
Name="btn_List1"
VerticalAlignment="Bottom"
Width="75">List 1</Button>
<Button Height="23"
Margin="0,0,75,87"
Name="btn_List2"
VerticalAlignment="Bottom"
HorizontalAlignment="Right"
Width="75">List 2</Button>
</Grid>
</Window>
</code></pre>
<p>Here's the code-behind:</p>
<pre><code>Class Window1
Private obj1 As MyListObject
Private obj2 As MyListObject
Private odp As ObjectDataProvider
Public Sub New()
InitializeComponent()
Dim namelist1 As New List(Of String)
namelist1.Add("Joe")
namelist1.Add("Steve")
obj1 = New MyListObject(namelist1, "Steve")
.
Dim namelist2 As New List(Of String)
namelist2.Add("Bob")
namelist2.Add("Tim")
obj2 = New MyListObject(namelist2, "Tim")
odp = DirectCast(Me.FindResource("MyListObject"), ObjectDataProvider)
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List1.Click
odp.ObjectInstance = obj1
End Sub
Private Sub btn_List2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btn_List2.Click
odp.ObjectInstance = obj2
End Sub
End Class
</code></pre>
<p>When the Window first loads, the bindings hook up fine. The ComboBox contains the names "Joe" and "Steve" and "Steve" is selected by default. However, when I click a button to switch the ObjectInstance to obj2, the ComboBox ItemsSource gets populated correctly in the dropdown, but the SelectedValue is set to Nothing instead of being equal to obj2.SelectedName.</p>
|
[
{
"answer_id": 247482,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 6,
"selected": true,
"text": "SelectedValue SelectedValue SelectedItem SelectedValue"
},
{
"answer_id": 1262778,
"author": "Mikeb",
"author_id": 154630,
"author_profile": "https://Stackoverflow.com/users/154630",
"pm_score": 2,
"selected": false,
"text": "SelectedValuePath=\"Content\" SelectedValue SelectedValue SelectedValue"
},
{
"answer_id": 3301328,
"author": "ASeale",
"author_id": 398200,
"author_profile": "https://Stackoverflow.com/users/398200",
"pm_score": 4,
"selected": false,
"text": "<ComboBox Text=\"{Binding Test}\">\n <ComboBoxItem Content=\"A\" />\n <ComboBoxItem Content=\"B\" />\n <ComboBoxItem Content=\"C\" />\n</ComboBox>\n public class TestCode\n{\n private string _test;\n public string Test \n { \n get { return _test; }\n set\n {\n _test = value;\n NotifyPropertyChanged(() => Test); // NotifyPropertyChanged(\"Test\"); if not using Caliburn\n }\n }\n}\n"
},
{
"answer_id": 5742784,
"author": "Dummy01",
"author_id": 461463,
"author_profile": "https://Stackoverflow.com/users/461463",
"pm_score": 3,
"selected": false,
"text": "SelectedValuePath SelectedValue SelectedValuePath Int16 SelectedValue int"
},
{
"answer_id": 5986840,
"author": "Pavel Kovalev",
"author_id": 701869,
"author_profile": "https://Stackoverflow.com/users/701869",
"pm_score": 3,
"selected": false,
"text": "//Converter\n\npublic class SelectedToIndexConverter : IValueConverter\n {\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value != null && value is YourType)\n {\n YourType YourSelectedValue = (YourType) value;\n\n YourSelectedValue = (YourType) cmbDowntimeDictionary.Tag;\n YourType a = (from dd in Helper.YourType\n where dd.YourTypePrimaryKey == YourSelectedValue.YourTypePrimaryKey\n select dd).First();\n\n int index = YourTypeCollection.IndexOf(a); //YourTypeCollection - Same as ItemsSource of ComboBox\n }\n return null;\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n if (value!=null && value is int)\n {\n return YourTypeCollection[(int) value];\n }\n\n return null;\n }\n }\n <ComboBox \n ItemsSource=\"{Binding Source={StaticResource YourDataProvider}}\"\n SelectedIndex=\"{Binding Path=YourValue, Mode=TwoWay, Converter={StaticResource SelectedToIndexConverter}, UpdateSourceTrigger=PropertyChanged}\"/>\n"
},
{
"answer_id": 10529054,
"author": "Junier",
"author_id": 1386391,
"author_profile": "https://Stackoverflow.com/users/1386391",
"pm_score": 3,
"selected": false,
"text": "UpdateSourceTrigger=PropertyChanged \n"
},
{
"answer_id": 55591489,
"author": "Rajon Tanducar",
"author_id": 6310002,
"author_profile": "https://Stackoverflow.com/users/6310002",
"pm_score": 1,
"selected": false,
"text": "private ObservableCollection<string> _SelectedPartyType;\n\npublic ObservableCollection<string> SelectedPartyType { get { return \n_SelectedPartyType; } set { \n _SelectedPartyType = value; OnPropertyChanged(\"SelectedPartyType\"); } }\n private string _SelectedPartyType;\n\n public string SelectedPartyType { get { return _SelectedPartyType; } set { \n _SelectedPartyType = value; OnPropertyChanged(\"SelectedPartyType\"); } }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
247,416
|
<p>I'm using several variants of the Validator controls (RequiredFieldValidator, CompareValidator, etc) and am using the CssClass property of the validator. I can see (via Firebug) that the class is being applied, but the validator control itself is adding a style element to it, namely color: red. But I don't want that. I want the control to use the cssclass only.</p>
<p>I know I can override the Forecolor attribute, but I'll have to do that on every validator in the project. And I'd really like to be able to just change my CSS Class in my stylesheet in case we have to change all the error message appearances in the future.</p>
<p>Anyone have any clues how to tell the Validator controls to NOT use their default styles?</p>
|
[
{
"answer_id": 247453,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 5,
"selected": true,
"text": ".validator\n{\n color: blue !important;\n}\n"
},
{
"answer_id": 14277151,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 3,
"selected": false,
"text": "<asp:RequiredFieldValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:RangeValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:CompareValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:RegularExpressionValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:CustomValidator runat=\"server\" CssClass=\"validation-error\" />\n<asp:ValidationSummary runat=\"server\" CssClass=\"validation-error\" />\n web.config <configuration>\n <system.web>\n <pages theme=\"DefaultTheme\" />\n </system.web>\n</configuration>\n .validation-error style=\"Color:red\" ForeColor !important"
},
{
"answer_id": 37847764,
"author": "Eyad Eyadian",
"author_id": 5520809,
"author_profile": "https://Stackoverflow.com/users/5520809",
"pm_score": 0,
"selected": false,
"text": "Set Forecolor=\"\"\n CssClass=\"your-css-class\"\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
247,422
|
<p>I've got a Excel VSTO 2005 application I need to debug, I've tried attaching to the process EXCEL.EXE in Visual Studio 2005 to no avail.</p>
<p>Does anyone know what to do in order to debug managed code running in a VSTO Excel Application?</p>
|
[
{
"answer_id": 247436,
"author": "Josh",
"author_id": 5233,
"author_profile": "https://Stackoverflow.com/users/5233",
"pm_score": 4,
"selected": true,
"text": "Debugger.Launch();\n"
},
{
"answer_id": 3148119,
"author": "AMissico",
"author_id": 163921,
"author_profile": "https://Stackoverflow.com/users/163921",
"pm_score": 2,
"selected": false,
"text": "StopSwitch Stop"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18818/"
] |
247,430
|
<p>Is there a better way to implement copy construcor for matlab for a handle derived class other than adding a constructor with one input and explicitly copying its properties?</p>
<pre><code>obj.property1 = from.property1;
obj.property2 = from.property2;
</code></pre>
<p>etc.</p>
<p>Thanks,
Dani</p>
|
[
{
"answer_id": 248091,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 4,
"selected": true,
"text": "classdef Foo < handle\n properties\n a = 1;\n end\n methods\n function F=Foo(rhs)\n if nargin==0\n % default constructor\n F.a = rand(1);\n else\n % copy constructor\n fns = properties(rhs);\n for i=1:length(fns)\n F.(fns{i}) = rhs.(fns{i});\n end\n end\n end\n end\nend\n f = Foo(); [f.a Foo(f).a] % should print 2 floats with the same value.\n"
},
{
"answer_id": 1760151,
"author": "Gui",
"author_id": 214217,
"author_profile": "https://Stackoverflow.com/users/214217",
"pm_score": 2,
"selected": false,
"text": "try\n F.(fns{i}) = rhs.(fns{i});\nend\n"
},
{
"answer_id": 16170645,
"author": "Navan",
"author_id": 156525,
"author_profile": "https://Stackoverflow.com/users/156525",
"pm_score": 4,
"selected": false,
"text": "classdef YourClass < matlab.mixin.Copyable\n...\n\na = YourClass;\nb = copy(a); % b is a copy of a\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28772/"
] |
247,433
|
<p>How exactly can one implement a Log off function when using ASP.NET Forms Authentication on an intranet application?</p>
<p>How will this work if I am an administrator and want to log in "as someone else" into the application?</p>
<p>Please share your ideas</p>
|
[
{
"answer_id": 247441,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": true,
"text": "FormsAuthentication.SignOut();"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
247,446
|
<p>I have created a setup project using Visual Studio 2008. After the application is finished installing, I would like to have it start up immediately. Any thoughts on how this can be done?</p>
|
[
{
"answer_id": 9024424,
"author": "bendytree",
"author_id": 193896,
"author_profile": "https://Stackoverflow.com/users/193896",
"pm_score": 3,
"selected": false,
"text": "MyApp.Application MyApp.Installer MyApp.Application Add New Item... Installer Class View Code Commit public override void Commit(IDictionary savedState)\n{\n base.Commit(savedState);\n\n Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));\n Process.Start(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + \"\\\\MyApp.exe\");\n}\n MyApp.exe MyApp.Installer View Custom Actions Commit Add custom action Application Folder OK OK"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247446",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/324/"
] |
247,455
|
<p>I'm in the process of writing a piece of code that connects to a server spawns a bunch of threads using that connection and does a bunch of "stuff".</p>
<p>There are certain instances where the connection fails and I need to stop everything and start from scratch with a new object.</p>
<p>I wanted to clean up after the object but calling thread.stop on the threads, but this method is seemingly deprecated.</p>
<p>What is the recommended alternative to doing this? Should I write my own cleanup and exit method for each of the threads? Set the thread to null? or something else? </p>
|
[
{
"answer_id": 247507,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "interrupt stop"
},
{
"answer_id": 12133570,
"author": "Arun Edwin",
"author_id": 1626305,
"author_profile": "https://Stackoverflow.com/users/1626305",
"pm_score": 1,
"selected": false,
"text": "private Thread m_CleanupThread = null; \n\npublic void threadCleanUp(){\n m_CleanupThread = new Thread(this);\n m_CleanupThread.Start();\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
247,471
|
<p>I'm trying to build a shared library (DLL) on Windows, using MSVC 6 (retro!) and I have a peculiar link issue I need to resolve. My shared library must access some global state, controlled by the loading application.</p>
<p>Broadly, what I have is this:</p>
<p>application.c:</p>
<pre><code>static int g_private_value;
int use_private_value() {
/* do something with g_private_value */
}
int main (...) {
return shared_library_method ();
}
</code></pre>
<p>shared_library.c:</p>
<pre><code>__declspec(dllexport) int __stdcall shared_library_method() {
use_private_value();
}
</code></pre>
<p>(<strong>Updated</strong> - I forgot the <code>__declspec(dllexport) int __stdcall</code> portion, but it's there in the real code)</p>
<p>How do I set up shared_library.dll so that it exports <code>shared_library_method</code> and imports <code>use_private_value</code>?</p>
<p>Please remember that A) I'm a unix programmer, generally, and B) that I'm doing this without Visual Studio; our automated build infrastructure drives MSVC with makefiles. If I'm omitting something that will make it easier to answer the question, please comment and I'll update it ASAP.</p>
|
[
{
"answer_id": 247588,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 1,
"selected": false,
"text": "__declspec(dllexport) int __stdcall shared_library_method(void)\n{\n\n\n}\n"
},
{
"answer_id": 247669,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 2,
"selected": false,
"text": "typedef int (*func_ptr)();\nvoid init_library(func_ptr func);\n"
},
{
"answer_id": 247694,
"author": "Peter Olsson",
"author_id": 2703,
"author_profile": "https://Stackoverflow.com/users/2703",
"pm_score": 1,
"selected": false,
"text": "/export:use_private_value@0\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23309/"
] |
247,474
|
<p>A path in Perforce contains files a.txt and b.txt. I'll refer to the main path as mainline.</p>
<p>I've create a branch (called initialbranch) from there which contains just a.txt. I make lots of changes to a.txt, and am very happy with it. However, it's not yet ready for submitting back to mainline. I can easily integrate any changes to a.txt that occur in mainline.</p>
<p>Another project comes along, which needs the changes from initialbranch. Now, say I want to make changes to b.txt, and want to be able to integrate changes that happen both in initialbranch and in mainline. At present, I'm branching from initialbranch (call this new branch secondbranch). Previously I've been adding b.txt to initialbranch, and then integrating my changes across to secondbranch. Is there a nicer way to do this?</p>
<p>Sorry if this question seems somewhat convoluted, I've expressed it as best I can!</p>
<p>Thanks,</p>
<p>Dom</p>
|
[
{
"answer_id": 247566,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "initialbranch/a.txt secondbranch/a.txt\nmainline/b.txt secondbranch/b.txt\n"
},
{
"answer_id": 247665,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": " a,b------------------------------------------------------> mainline\n \\ branched / integrated back in\n \\-a----------------------------------/------------> initialbranch\n copied from mainline /\n -b-------------------/--------------> secondbranch\n a,b--------------------------------------------------> mainline\n \\ branched \\ / integrated back in\n \\-a-----------\\---------------------------/----> initialbranch\n \\ branched from mainline /\n -b-----------------------------> secondbranch\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20972/"
] |
247,479
|
<p>Does anyone know of a script that can select all text references to URLs and automatically replace them with anchor tags pointing to those locations?</p>
<pre><code>For example:
http://www.google.com
would automatically turn into
<a href="http://www.google.com">http://www.google.com</a>
</code></pre>
<p>Note: I am wanting this because I don't want to go through all my content and wrap them with anchor tags. </p>
|
[
{
"answer_id": 247558,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 2,
"selected": false,
"text": "while line = gets\n puts line.gsub( /(^|[^\"'])(http\\S+)/, \"\\\\1<a href='\\\\2'>\\\\2</a>\" )\nend\n"
},
{
"answer_id": 248901,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 6,
"selected": false,
"text": "// Define: Linkify plugin\n(function($){\n\n var url1 = /(^|<|\\s)(www\\..+?\\..+?)(\\s|>|$)/g,\n url2 = /(^|<|\\s)(((https?|ftp):\\/\\/|mailto:).+?)(\\s|>|$)/g,\n\n linkifyThis = function () {\n var childNodes = this.childNodes,\n i = childNodes.length;\n while(i--)\n {\n var n = childNodes[i];\n if (n.nodeType == 3) {\n var html = $.trim(n.nodeValue);\n if (html)\n {\n html = html.replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(url1, '$1<a href=\"http://$2\">$2</a>$3')\n .replace(url2, '$1<a href=\"$2\">$2</a>$5');\n $(n).after(html).remove();\n }\n }\n else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {\n linkifyThis.call(n);\n }\n }\n };\n\n $.fn.linkify = function () {\n return this.each(linkifyThis);\n };\n\n})(jQuery);\n\n// Usage example:\njQuery('div.textbody').linkify();\n www.example.com/path http://www.example.com/path mailto:me@example.com ftp://www.server.com/path < >"
},
{
"answer_id": 11359292,
"author": "Kimtho6",
"author_id": 451571,
"author_profile": "https://Stackoverflow.com/users/451571",
"pm_score": 3,
"selected": false,
"text": "textToLinks: function(text) {\n\n var re = /(https?:\\/\\/(([-\\w\\.]+)+(:\\d+)?(\\/([\\w/_\\.]*(\\?\\S+)?)?)?))/g;\n return text.replace(re, \"<a href=\\\"$1\\\" title=\\\"\\\">$1</a>\");\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
247,483
|
<p>I need to do an <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods" rel="noreferrer">HTTP GET</a> request in JavaScript. What's the best way to do that?</p>
<p>I need to do this in a Mac OS X dashcode widget.</p>
|
[
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "var sURL = '/your/url.html?' + (new Date()).getTime();\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "AllowNetworkAccess"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n $(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "$http.get $http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "window.fetch XMLHttpRequest fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n //create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "const http = new XMLHttpRequest()\n\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\nhttp.send()\n\nhttp.onload = () => console.log(http.responseText)"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<script> <script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": " <property> value <property> \n Property1: value\n Property2: value\n etc.\n var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n yournavigator.exe '' --allow-file-access-from-files\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "fetch('https://www.randomtext.me/api/lorem')\n let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)(); Open Chrome console network tab to see request"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "let data;\nconst URLAPI = \"https://gorest.co.in/public/v1/users\";\nfunction setData(dt) {\n data = dt;\n}\n // MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 1 --> \", data);\n data = null;\n });\n}\n // ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 2 --> \", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 3 --> \", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log(\"Data received 4 --> \", data);\n\n })\n}\n // ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log(\"Data received 5 -->\", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n (async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n // Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match \"Content-Type\" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n $ npm install axios\n const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": " httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26948/"
] |
247,486
|
<p>I'm loading data into a DataSet from an XML file using the ReadXml method. This results in two tables with the same name. One of the tables has a namespace and the other doesn't. I'm trying to reference the table with the namespace. Can anyone tell me how to do this?</p>
<pre><code> Dim reader As XmlTextReader = New XmlTextReader(strURL)
Dim city as string = ""
Dim ds As DataSet = New DataSet()
ds.Namespace = "HomeAddress"
ds.ReadXml(reader)
city = ds.Tables("Address").Rows(0).Item(2).ToString()
</code></pre>
|
[
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "var sURL = '/your/url.html?' + (new Date()).getTime();\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "AllowNetworkAccess"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n $(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "$http.get $http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "window.fetch XMLHttpRequest fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n //create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "const http = new XMLHttpRequest()\n\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\nhttp.send()\n\nhttp.onload = () => console.log(http.responseText)"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<script> <script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": " <property> value <property> \n Property1: value\n Property2: value\n etc.\n var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n yournavigator.exe '' --allow-file-access-from-files\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "fetch('https://www.randomtext.me/api/lorem')\n let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)(); Open Chrome console network tab to see request"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "let data;\nconst URLAPI = \"https://gorest.co.in/public/v1/users\";\nfunction setData(dt) {\n data = dt;\n}\n // MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 1 --> \", data);\n data = null;\n });\n}\n // ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 2 --> \", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 3 --> \", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log(\"Data received 4 --> \", data);\n\n })\n}\n // ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log(\"Data received 5 -->\", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n (async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n // Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match \"Content-Type\" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n $ npm install axios\n const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": " httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28327/"
] |
247,530
|
<p>I've an image that is wrapped in an anchor tag that, through jQuery, triggers an action somewhere else on the page. When I click on the image, two tiny 1px by 1px boxes show up in the upper and lower left corners of the image.</p>
<p>My CSS styles explicitly state no borders for images: <code>a,img { border: 0; }</code></p>
<p>It also seems to only happen in Firefox 3. Anyone else had this issue?</p>
<hr>
<p>Here's a screenshot of the left part of the image (the graphic has a white background):</p>
<p><a href="http://neezer.net/img/ss.png" rel="nofollow noreferrer">alt text http://neezer.net/img/ss.png</a></p>
<p>It's not the background, or the border of any other element. I checked.</p>
|
[
{
"answer_id": 247498,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 6,
"selected": false,
"text": "var xmlHttp = null;\n\nfunction GetCustomerInfo()\n{\n var CustomerNumber = document.getElementById( \"TextBoxCustomerNumber\" ).value;\n var Url = \"GetCustomerInfoAsJson.aspx?number=\" + CustomerNumber;\n\n xmlHttp = new XMLHttpRequest(); \n xmlHttp.onreadystatechange = ProcessRequest;\n xmlHttp.open( \"GET\", Url, true );\n xmlHttp.send( null );\n}\n\nfunction ProcessRequest() \n{\n if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) \n {\n if ( xmlHttp.responseText == \"Not found\" ) \n {\n document.getElementById( \"TextBoxCustomerName\" ).value = \"Not found\";\n document.getElementById( \"TextBoxCustomerAddress\" ).value = \"\";\n }\n else\n {\n var info = eval ( \"(\" + xmlHttp.responseText + \")\" );\n\n // No parsing necessary with JSON! \n document.getElementById( \"TextBoxCustomerName\" ).value = info.jsonData[ 0 ].cmname;\n document.getElementById( \"TextBoxCustomerAddress\" ).value = info.jsonData[ 0 ].cmaddr1;\n } \n }\n}\n"
},
{
"answer_id": 247499,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": false,
"text": "new Ajax.Request( '/myurl', {\n method: 'get',\n parameters: { 'param1': 'value1'},\n onSuccess: function(response){\n alert(response.responseText);\n },\n onFailure: function(){\n alert('ERROR');\n }\n});\n"
},
{
"answer_id": 247511,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 8,
"selected": false,
"text": "$.get(\n \"somepage.php\",\n {paramOne : 1, paramX : 'abc'},\n function(data) {\n alert('page content: ' + data);\n }\n);\n"
},
{
"answer_id": 247516,
"author": "Tom",
"author_id": 20,
"author_profile": "https://Stackoverflow.com/users/20",
"pm_score": 5,
"selected": false,
"text": "var sURL = '/your/url.html?' + (new Date()).getTime();\n"
},
{
"answer_id": 248140,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 3,
"selected": false,
"text": "AllowNetworkAccess"
},
{
"answer_id": 249239,
"author": "Daniel Beardsley",
"author_id": 13216,
"author_profile": "https://Stackoverflow.com/users/13216",
"pm_score": 3,
"selected": false,
"text": "var page_content;\n$.get( \"somepage.php\", function(data){\n page_content = data;\n});\n"
},
{
"answer_id": 4033310,
"author": "Joan",
"author_id": 488828,
"author_profile": "https://Stackoverflow.com/users/488828",
"pm_score": 11,
"selected": true,
"text": "function httpGet(theUrl)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.open( \"GET\", theUrl, false ); // false for synchronous request\n xmlHttp.send( null );\n return xmlHttp.responseText;\n}\n function httpGetAsync(theUrl, callback)\n{\n var xmlHttp = new XMLHttpRequest();\n xmlHttp.onreadystatechange = function() { \n if (xmlHttp.readyState == 4 && xmlHttp.status == 200)\n callback(xmlHttp.responseText);\n }\n xmlHttp.open(\"GET\", theUrl, true); // true for asynchronous \n xmlHttp.send(null);\n}\n"
},
{
"answer_id": 4122716,
"author": "aNieto2k",
"author_id": 500520,
"author_profile": "https://Stackoverflow.com/users/500520",
"pm_score": 7,
"selected": false,
"text": "var i = document.createElement(\"img\");\ni.src = \"/your/GET/url?params=here\";\n"
},
{
"answer_id": 22076667,
"author": "tggagne",
"author_id": 214046,
"author_profile": "https://Stackoverflow.com/users/214046",
"pm_score": 7,
"selected": false,
"text": "var HttpClient = function() {\n this.get = function(aUrl, aCallback) {\n var anHttpRequest = new XMLHttpRequest();\n anHttpRequest.onreadystatechange = function() { \n if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)\n aCallback(anHttpRequest.responseText);\n }\n\n anHttpRequest.open( \"GET\", aUrl, true ); \n anHttpRequest.send( null );\n }\n}\n var client = new HttpClient();\nclient.get('http://some/thing?with=arguments', function(response) {\n // do something with response\n});\n"
},
{
"answer_id": 25358151,
"author": "Daniel De León",
"author_id": 980442,
"author_profile": "https://Stackoverflow.com/users/980442",
"pm_score": 6,
"selected": false,
"text": "//Option with catch\nfetch( textURL )\n .then(async r=> console.log(await r.text()))\n .catch(e=>console.error('Boo...' + e));\n\n//No fear...\n(async () =>\n console.log(\n (await (await fetch( jsonURL )).json())\n )\n)();\n let request = new XMLHttpRequest();\nrequest.onreadystatechange = function () {\n if (this.readyState === 4) {\n if (this.status === 200) {\n document.body.className = 'ok';\n console.log(this.responseText);\n } else if (this.response == null && this.status === 0) {\n document.body.className = 'error offline';\n console.log(\"The computer appears to be offline.\");\n } else {\n document.body.className = 'error';\n }\n }\n};\nrequest.open(\"GET\", url, true);\nrequest.send(null);\n"
},
{
"answer_id": 26060638,
"author": "parag.rane",
"author_id": 3045721,
"author_profile": "https://Stackoverflow.com/users/3045721",
"pm_score": 3,
"selected": false,
"text": "xmlhttp.open(\"GET\",\"URL\",true);\nxmlhttp.send();\n $(\"btn\").click(function() {\n $.ajax({url: \"demo_test.txt\", success: function_name(result) {\n $(\"#innerdiv\").html(result);\n }});\n}); \n"
},
{
"answer_id": 30087038,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 3,
"selected": false,
"text": "$http.get $http.get('/someUrl').\n success(function(data, status, headers, config) {\n // this callback will be called asynchronously\n // when the response is available\n }).\n error(function(data, status, headers, config) {\n // called asynchronously if an error occurs\n // or server returns response with an error status.\n });\n"
},
{
"answer_id": 38168619,
"author": "Gaurav Gupta",
"author_id": 4452469,
"author_profile": "https://Stackoverflow.com/users/4452469",
"pm_score": 2,
"selected": false,
"text": "function get(path) {\n var form = document.createElement(\"form\");\n form.setAttribute(\"method\", \"get\");\n form.setAttribute(\"action\", path);\n document.body.appendChild(form);\n form.submit();\n}\n\n\nget('/my/url/')\n"
},
{
"answer_id": 38297729,
"author": "Peter Gibson",
"author_id": 66349,
"author_profile": "https://Stackoverflow.com/users/66349",
"pm_score": 8,
"selected": false,
"text": "window.fetch XMLHttpRequest fetch(url).then(function(response) {\n return response.json();\n}).then(function(data) {\n console.log(data);\n}).catch(function() {\n console.log(\"Booo\");\n});\n async function fetchAsync (url) {\n let response = await fetch(url);\n let data = await response.json();\n return data;\n}\n"
},
{
"answer_id": 38479928,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "function httpRequest() {\n var ajax = null,\n response = null,\n self = this;\n\n this.method = null;\n this.url = null;\n this.async = true;\n this.data = null;\n\n this.send = function() {\n ajax.open(this.method, this.url, this.asnyc);\n ajax.send(this.data);\n };\n\n if(window.XMLHttpRequest) {\n ajax = new XMLHttpRequest();\n }\n else if(window.ActiveXObject) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.6.0\");\n }\n catch(e) {\n try {\n ajax = new ActiveXObject(\"Msxml2.XMLHTTP.3.0\");\n }\n catch(error) {\n self.fail(\"not supported\");\n }\n }\n }\n\n if(ajax == null) {\n return false;\n }\n\n ajax.onreadystatechange = function() {\n if(this.readyState == 4) {\n if(this.status == 200) {\n self.success(this.responseText);\n }\n else {\n self.fail(this.status + \" - \" + this.statusText);\n }\n }\n };\n}\n //create request with its porperties\nvar request = new httpRequest();\nrequest.method = \"GET\";\nrequest.url = \"https://example.com/api?parameter=value\";\n\n//create callback for success containing the response\nrequest.success = function(response) {\n console.log(response);\n};\n\n//and a fail callback containing the error\nrequest.fail = function(error) {\n console.log(error);\n};\n\n//and finally send it away\nrequest.send();\n"
},
{
"answer_id": 39981705,
"author": "jpereira",
"author_id": 2290540,
"author_profile": "https://Stackoverflow.com/users/2290540",
"pm_score": 0,
"selected": false,
"text": "// Create the XHR object.\nfunction createCORSRequest(method, url) {\n var xhr = new XMLHttpRequest();\nif (\"withCredentials\" in xhr) {\n// XHR for Chrome/Firefox/Opera/Safari.\nxhr.open(method, url, true);\n} else if (typeof XDomainRequest != \"undefined\") {\n// XDomainRequest for IE.\nxhr = new XDomainRequest();\nxhr.open(method, url);\n} else {\n// CORS not supported.\nxhr = null;\n}\nreturn xhr;\n}\n\n// Make the actual CORS request.\nfunction makeCorsRequest() {\n // This is a sample server that supports CORS.\n var url = 'http://html5rocks-cors.s3-website-us-east-1.amazonaws.com/index.html';\n\nvar xhr = createCORSRequest('GET', url);\nif (!xhr) {\nalert('CORS not supported');\nreturn;\n}\n\n// Response handlers.\nxhr.onload = function() {\nvar text = xhr.responseText;\nalert('Response from CORS request to ' + url + ': ' + text);\n};\n\nxhr.onerror = function() {\nalert('Woops, there was an error making the request.');\n};\n\nxhr.send();\n}\n"
},
{
"answer_id": 46993214,
"author": "Damjan Pavlica",
"author_id": 3576214,
"author_profile": "https://Stackoverflow.com/users/3576214",
"pm_score": 6,
"selected": false,
"text": "const http = new XMLHttpRequest()\n\nhttp.open(\"GET\", \"https://api.lyrics.ovh/v1/toto/africa\")\nhttp.send()\n\nhttp.onload = () => console.log(http.responseText)"
},
{
"answer_id": 51064810,
"author": "negstek",
"author_id": 995071,
"author_profile": "https://Stackoverflow.com/users/995071",
"pm_score": 2,
"selected": false,
"text": "let httpRequestAsync = (method, url) => {\n return new Promise(function (resolve, reject) {\n var xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = function () {\n if (xhr.status == 200) {\n resolve(xhr.responseText);\n }\n else {\n reject(new Error(xhr.responseText));\n }\n };\n xhr.send();\n });\n}\n"
},
{
"answer_id": 51294660,
"author": "aabiro",
"author_id": 7848529,
"author_profile": "https://Stackoverflow.com/users/7848529",
"pm_score": 4,
"selected": false,
"text": "<script> <script type=“text/javascript”> \n // Create request object \n var request = new Request('https://example.com/api/...', \n { method: 'POST', \n body: {'name': 'Klaus'}, \n headers: new Headers({ 'Content-Type': 'application/json' }) \n });\n // Now use it! \n\n fetch(request) \n .then(resp => { \n // handle response \n }) \n .catch(err => { \n // handle errors \n });\n</script>\n"
},
{
"answer_id": 53363310,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "function get(url, callback) {\n var getRequest = new XMLHttpRequest();\n\n getRequest.open(\"get\", url, true);\n\n getRequest.addEventListener(\"readystatechange\", function() {\n if (getRequest.readyState === 4 && getRequest.status === 200) {\n callback(getRequest.responseText);\n }\n });\n\n getRequest.send();\n}\n"
},
{
"answer_id": 55180638,
"author": "Cherif",
"author_id": 11027579,
"author_profile": "https://Stackoverflow.com/users/11027579",
"pm_score": 0,
"selected": false,
"text": " <property> value <property> \n Property1: value\n Property2: value\n etc.\n var objectfile = {};\n\nfunction getfilecontent(url){\n var cli = new XMLHttpRequest();\n\n cli.onload = function(){\n if((this.status == 200 || this.status == 0) && this.responseText != null) {\n var r = this.responseText;\n var b=(r.indexOf('\\n')?'\\n':r.indexOf('\\r')?'\\r':'');\n if(b.length){\n if(b=='\\n'){var j=r.toString().replace(/\\r/gi,'');}else{var j=r.toString().replace(/\\n/gi,'');}\n r=j.split(b);\n r=r.filter(function(val){if( val == '' || val == NaN || val == undefined || val == null ){return false;}return true;});\n r = r.map(f => f.trim());\n }\n if(r.length > 0){\n for(var i=0; i<r.length; i++){\n var m = r[i].split(':');\n if(m.length>1){\n var mname = m[0];\n var n = m.shift();\n var ivalue = m.join(':');\n objectfile[mname]=ivalue;\n }\n }\n }\n }\n }\ncli.open(\"GET\", url);\ncli.send();\n}\n getfilecontent('mesite.com/mefile.txt');\n\nwindow.onload = function(){\n\nif(objectfile !== null){\nalert (objectfile.property1.value);\n}\n}\n yournavigator.exe '' --allow-file-access-from-files\n"
},
{
"answer_id": 57799229,
"author": "Pradeep Maurya",
"author_id": 8682291,
"author_profile": "https://Stackoverflow.com/users/8682291",
"pm_score": 2,
"selected": false,
"text": "// Create a request variable and assign a new XMLHttpRequest object to it.\nvar request = new XMLHttpRequest()\n\n// Open a new connection, using the GET request on the URL endpoint\nrequest.open('GET', 'restUrl', true)\n\nrequest.onload = function () {\n // Begin accessing JSON data here\n}\n\n// Send request\nrequest.send()\n"
},
{
"answer_id": 57816554,
"author": "Rama",
"author_id": 10512029,
"author_profile": "https://Stackoverflow.com/users/10512029",
"pm_score": 0,
"selected": false,
"text": "<button type=\"button\" onclick=\"loadXMLDoc()\"> GET CONTENT</button>\n\n <script>\n function loadXMLDoc() {\n var xmlhttp = new XMLHttpRequest();\n var url = \"<Enter URL>\";``\n xmlhttp.onload = function () {\n if (xmlhttp.readyState == 4 && xmlhttp.status == \"200\") {\n document.getElementById(\"demo\").innerHTML = this.responseText;\n }\n }\n xmlhttp.open(\"GET\", url, true);\n xmlhttp.send();\n }\n </script>\n"
},
{
"answer_id": 61750410,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "fetch('https://www.randomtext.me/api/lorem')\n let url = 'https://www.randomtext.me/api/lorem';\n\n// to only send GET request without waiting for response just call \nfetch(url);\n\n// to wait for results use 'then'\nfetch(url).then(r=> r.json().then(j=> console.log('\\nREQUEST 2',j)));\n\n// or async/await\n(async()=> \n console.log('\\nREQUEST 3', await(await fetch(url)).json()) \n)(); Open Chrome console network tab to see request"
},
{
"answer_id": 67454712,
"author": "Azer8",
"author_id": 15487184,
"author_profile": "https://Stackoverflow.com/users/15487184",
"pm_score": 3,
"selected": false,
"text": "async function funcName(url){\n const response = await fetch(url);\n var data = await response.json();\n }"
},
{
"answer_id": 68655799,
"author": "Federico Baù",
"author_id": 13903942,
"author_profile": "https://Stackoverflow.com/users/13903942",
"pm_score": 3,
"selected": false,
"text": "let data;\nconst URLAPI = \"https://gorest.co.in/public/v1/users\";\nfunction setData(dt) {\n data = dt;\n}\n // MOST SIMPLE ONE \nfunction makeRequest1() { \n fetch(URLAPI)\n .then(response => response.json()).then( json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 1 --> \", data);\n data = null;\n });\n}\n // ASYNC FUNCTIONS \nfunction makeRequest2() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(async json => await setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 2 --> \", data);\n data = null; \n });\n}\n\nfunction makeRequest3() { \n fetch(URLAPI)\n .then(async response => await response.json()).then(json => setData(json))\n .catch(error => console.error(error))\n .finally(() => {\n console.log(\"Data received 3 --> \", data);\n data = null;\n });\n}\n\n// Better Promise usages\nfunction makeRequest4() {\n const response = Promise.resolve(fetch(URLAPI).then(response => response.json())).then(json => setData(json) ).finally(()=> {\n console.log(\"Data received 4 --> \", data);\n\n })\n}\n // ONE LINER STRIKE ASYNC WRAPPER FUNCTION \nasync function makeRequest5() {\n console.log(\"Data received 5 -->\", await Promise.resolve(fetch(URLAPI).then(response => response.json().then(json => json ))) );\n}\n (async () =>\n console.log(\n (await (await fetch( URLAPI )).json())\n )\n)();\n // Example POST method implementation:\nasync function postData(url = '', data = {}) {\n // Default options are marked with *\n const response = await fetch(url, {\n method: 'POST', // *GET, POST, PUT, DELETE, etc.\n mode: 'cors', // no-cors, *cors, same-origin\n cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached\n credentials: 'same-origin', // include, *same-origin, omit\n headers: {\n 'Content-Type': 'application/json'\n // 'Content-Type': 'application/x-www-form-urlencoded',\n },\n redirect: 'follow', // manual, *follow, error\n referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url\n body: JSON.stringify(data) // body data type must match \"Content-Type\" header\n });\n return response.json(); // parses JSON response into native JavaScript objects\n}\n\npostData('https://example.com/answer', { answer: 42 })\n .then(data => {\n console.log(data); // JSON data parsed by `data.json()` call\n });\n $ npm install axios\n const axios = require('axios');\nconst request = async (url) => await (await axios.get( url ));\nlet response = request(URL).then(resp => console.log(resp.data));\n"
},
{
"answer_id": 68897028,
"author": "tbo47",
"author_id": 1554999,
"author_profile": "https://Stackoverflow.com/users/1554999",
"pm_score": 2,
"selected": false,
"text": " httpRequest = (url, method = 'GET') => {\n return new Promise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n xhr.open(method, url);\n xhr.onload = () => {\n if (xhr.status === 200) { resolve(xhr.responseText); }\n else { reject(new Error(xhr.responseText)); }\n };\n xhr.send();\n });\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32154/"
] |
247,538
|
<p>I was looking through the plans for C++0x and came upon <code>std::initializer_list</code> for implementing initializer lists in user classes. This class could not be implemented in C++
without using itself, or else using some "compiler magic". If it could, it wouldn't be needed since whatever technique you used to implement <code>initializer_list</code> could be used to implement initializer lists in your own class.</p>
<p>What other classes require some form of "compiler magic" to work? Which classes are in the Standard Library that could not be implemented by a third-party library?</p>
<p>Edit: Maybe instead of implemented, I should say instantiated. It's more the fact that this class is so directly linked with a language feature (you can't use initializer lists without <code>initializer_list</code>). </p>
<p>A comparison with C# might clear up what I'm wondering about: IEnumerable and IDisposable are actually hard-coded into language features. I had always assumed C++ was free of this, since Stroustrup tried to make everything implementable in libraries. So, are there any other classes / types that are inextricably bound to a language feature.</p>
|
[
{
"answer_id": 247614,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 0,
"selected": false,
"text": "Object"
},
{
"answer_id": 248891,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 4,
"selected": true,
"text": "std::type_info typeinfo std::initializer_list std::initializer_list<typename T> std::initializer_list<typename T> T[] namespace std {\n template<typename T> class initializer_list {\n T internal_array[];\n public:\n initializer_list(T other_array[]) : internal_array(other_array) { };\n\n // ... other methods needed to actually access internal_array\n }\n}\n std::initializer_list std::initializer_list struct my_class {\n ...\n my_class(std::initializer_list<int>) ...\n}\n my_class m = {1, 2, 3};\n my_class my_class std::initializer_list<int> int[] int[] std::initializer_list<int> my_class initializer_list int arry[] = {1, 2, 3};\nmy_class = arry;\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8701/"
] |
247,541
|
<p>I've editing this original question as I think I've narrowed down the problem...</p>
<p>I have one view in my site that will not let me put $document.ready within a masterpage contentplaceholder. I've stripped this page to the bare bones and the only thing that is special about it is it has a custom route in global.asax</p>
<pre><code> routes.MapRoute("Books",
"{controller}/{action}/{keywords}/{pageNumber}",
new { controller = "Books", action = "SearchResults" }
);
</code></pre>
<p>Any idea why this custom route would stop $document.ready working correctly when put in a masterpages contentplaceholder zone?</p>
|
[
{
"answer_id": 247554,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function() { alert('loaded'); });\n $().ready(function() { alert('loaded'); });\n$(function() { alert('loaded'); });\n"
},
{
"answer_id": 247645,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<script ...> <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContentPlaceHolder\" runat=\"server\">\n <div class=\"contentItem\">\n <%!-- yadda --%>\n </div>\n\n <script type=\"text/javascript\">\n $(document).ready(function() {\n // do your worst\n });\n </script>\n</asp:Content>\n"
},
{
"answer_id": 251188,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 4,
"selected": true,
"text": "<script src=\"<%= Url.Content(\"~/Content/jquery-1.2.6.min.js\") %>\" type=\"text/javascript\"></script>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5463/"
] |
247,546
|
<p>I'm sending an email using the dotnet framework. Here is the template that I'm using to create the message:</p>
<pre><code>Date of Hire: %HireDate%
Annual Salary: %AnnualIncome%
Reason for Request: %ReasonForRequest%
Name of Voluntary Employee: %FirstName% %LastName%
Total Coverage Applied For: %EECoverageAmount%
Guaranteed Coverage Portion: %GICoveragePortion%
Amount Subject to Medical Evident: %GIOverage%
</code></pre>
<p>When the messages is received in outlook, outlook tells me "Extra line breaks in this message were removed". And the message displays like this:</p>
<pre><code>Date of Hire: 9/28/2001
Annual Salary: $100,000
Reason for Request: New Hire
Name of Voluntary Employee: Ronald Weasley Total Coverage Applied For: $500,000 Guaranteed Coverage Portion: $300,000.00 Amount Subject to Medical Evident: $200,000
</code></pre>
<p>Note how Outlook incorrectly removes needed line breaks after the name, EECoverageAmount, etc...</p>
<p>It's important for the email recepients to get a correctly formatted email, and I have to assume that some of them use outlook 2003. I also can't assume they will know enough to shutoff the autoclean feature to get the message to format properly. </p>
<p>I have viewed these messages in other mail clients and they display correctly</p>
<p>some more information:</p>
<ul>
<li>I am using UTF-8 BodyEncoding (msg.BodyEncoding = System.Text.Encoding.UTF8)</li>
<li>The msg.Body is being read from a UTF-8 encoded text file, and each line is terminated with a crlf.</li>
</ul>
<p>Question:
How do I change the format of the message to avoid this problem?</p>
|
[
{
"answer_id": 247939,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 8,
"selected": true,
"text": "Date of Hire: %HireDate%\nAnnual Salary: %AnnualIncome%\nReason for Request: %ReasonForRequest%\n\nName of Voluntary Employee: %FirstName% %LastName%\nTotal Coverage Applied For: %EECoverageAmount%\nGuaranteed Coverage Portion: %GICoveragePortion%\nAmount Subject to Medical Evident: %GIOverage%\n Date of Hire: %HireDate%\n Annual Salary: %AnnualIncome%\n Reason for Request: %ReasonForRequest%\n\n Name of Voluntary Employee: %FirstName% %LastName%\n Total Coverage Applied For: %EECoverageAmount%\n Guaranteed Coverage Portion: %GICoveragePortion%\n Amount Subject to Medical Evident: %GIOverage%\n^^ <--- Two extra spaces at the start of every line\n"
},
{
"answer_id": 18986207,
"author": "Christian Casutt",
"author_id": 270085,
"author_profile": "https://Stackoverflow.com/users/270085",
"pm_score": 0,
"selected": false,
"text": "<pre> pre {\n font-family: Verdana, Geneva, sans-serif;\n}\n <td width=\"70%\"><pre>Entry Date/Time: 2013-09-19 17:06:25\nEntered By: Chris\n\nworklog mania\n\n____________________________________________________________________________________________________\n\nEntry Date/Time: 2013-09-19 17:05:42\nEntered By: Chris\n\nthis is a new Worklog Entry</pre></td>\n"
},
{
"answer_id": 26904734,
"author": "Keyur Patel",
"author_id": 1817557,
"author_profile": "https://Stackoverflow.com/users/1817557",
"pm_score": -1,
"selected": false,
"text": "string[] tokens = Regex.Split(objTickt.Description, \"\\r\\n\");\n if (tokens.Length > 0)\n {\n foreach (string line in tokens)\n {\n //htmlTW.WriteEncodedText(objTickt.Description.Replace(\"\\r\\n\", \"\\n\\n\"));\n htmlTW.RenderBeginTag(HtmlTextWriterTag.P);\n htmlTW.WriteEncodedText(line);\n htmlTW.RenderEndTag();\n }\n }\n"
},
{
"answer_id": 45742136,
"author": "Ho Ho Ho",
"author_id": 2386528,
"author_profile": "https://Stackoverflow.com/users/2386528",
"pm_score": 1,
"selected": false,
"text": "body = string.Format(\"<font face='calibri,arial,sans-serif'>{0}<font/>\", body.Replace(\"\\r\\n\", \"<br>\"));\n\nusing (var smtpClient = new SmtpClient() { Host = smtpHost })\nusing (var msg = new MailMessage(from, emailDistribution, subject, body) { IsBodyHtml = true })\n smtpClient.Send(msg);\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21155/"
] |
247,550
|
<p>I have a blank test app created in VS 2005 as ASP.NET application. <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow noreferrer">MSDN says</a> that </p>
<blockquote>
<p>By default, ASP.NET does not use impersonation, and your code runs using the ASP.NET application's process identity.</p>
</blockquote>
<p>And I have the following web.config</p>
<pre><code><configuration>
<appSettings/>
<connectionStrings/>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" defaultLanguage="c#" />
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows"/>
<identity impersonate="false"/>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
</system.web>
</configuration>
</code></pre>
<p>So it seem impersonation is disabled just like <a href="http://msdn.microsoft.com/en-us/library/ms998351.aspx" rel="nofollow noreferrer">the article</a> is suggesting.</p>
<p>My aspx is blank default and the codebehind is</p>
<pre><code>namespace TestWebapp
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine(String.Format("Before1: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
int a = 0;
System.Diagnostics.Debug.WriteLine(String.Format("After: Current Princupal = {0}", Thread.CurrentPrincipal.Identity.Name));
} finally
{
ctx.Undo();
}
}
}
}
</code></pre>
<p>When I reload the page I get the following debug output:</p>
<blockquote>
<p>[5288] Before1: Current Princupal =
DOMAIN\User
[5288] After: Current Princupal =
DOMAIN\User</p>
</blockquote>
<p>Output is the same with</p>
<pre><code><identity impersonate="false"/>
</code></pre>
<p>The web site uses Default Application Pool and the pool is set up to use NETWORK SERVICE account for its worker processes.
I'm sure the application uses the web.config it should use and the w3p.exe worker process is running under NETWORK SERVICE.</p>
<p>What can be wrong in this case?</p>
<p>Thanks!</p>
<p>@Edit: Rob, thanks for the tip!
The $user shortcut shows me that everything is happening as I expect: with impersonation on I have the process running user NT AUTHORITY\NETWORK SERVICE and the thread has DOMAIN\User before WindowsIdentity.Impersonate(IntPtr.Zero) and "No Token. Thread not impersonating." after.
But Thread.CurrentPrincipal.Identity.Name and HttpContext.Current.User.Identity.Name still give me DOMAIN\User in both places.</p>
<p>@Edit: I've found out that to get Thread.CurrentPrincipal and HttpContext.Current.User changed I have to manually do it:</p>
<pre><code>Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
HttpContext.Current.User = Thread.CurrentPrincipal;
</code></pre>
<p>I'm not sure what's the point here, but anyway. I now have a problem with sharepoint shared services manage user profile permission but that's another question.</p>
|
[
{
"answer_id": 247582,
"author": "Rob Stevenson-Leggett",
"author_id": 4950,
"author_profile": "https://Stackoverflow.com/users/4950",
"pm_score": 1,
"selected": false,
"text": "// Declare the logon types as constants\nconst long LOGON32_LOGON_INTERACTIVE = 2;\nconst long LOGON32_LOGON_NETWORK = 3;\n\n// Declare the logon providers as constants\nconst long LOGON32_PROVIDER_DEFAULT = 0;\nconst long LOGON32_PROVIDER_WINNT50 = 3;\nconst long LOGON32_PROVIDER_WINNT40 = 2;\nconst long LOGON32_PROVIDER_WINNT35 = 1;\n\n[DllImport(\"advapi32.dll\", EntryPoint = \"LogonUser\")]\nprivate static extern bool LogonUser(\n string lpszUsername,\n string lpszDomain,\n string lpszPassword,\n int dwLogonType,\n int dwLogonProvider,\n ref IntPtr phToken);\n\npublic static WindowsImpersonationContext ImpersonateCurrentUserBegin(System.Net.NetworkCredential credential)\n{\n WindowsImpersonationContext impersonationContext = null;\n if (credential == null || credential.UserName.Length == 0 || credential.Password.Length == 0 || credential.Domain.Length == 0)\n {\n throw new Exception(\"Incomplete user credentials specified\");\n }\n impersonationContext = Security.Impersonate(credential);\n if (impersonationContext == null)\n {\n return null;\n }\n else\n {\n return impersonationContext;\n }\n}\n\npublic static void ImpersonateCurrentUserEnd(WindowsImpersonationContext impersonationContext)\n{\n if (impersonationContext != null)\n {\n impersonationContext.Undo();\n }\n}\n"
},
{
"answer_id": 247583,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 1,
"selected": false,
"text": "HttpContext.User.Identity.Name"
},
{
"answer_id": 56868986,
"author": "Kushan Gowda",
"author_id": 9819727,
"author_profile": "https://Stackoverflow.com/users/9819727",
"pm_score": 2,
"selected": false,
"text": "System.Security.Principal.WindowsIdentity.GetCurrent().Name System.Threading.Thread.CurrentPrincipal.Identity.Name System.Threading.Thread.CurrentPrincipal.Identity HttpContext.Current.User.Identity System.Threading.Thread.CurrentPrincipal.Identity HttpContext.Current.User.Identity"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
247,571
|
<p>I'm trying filter the child collection of an aggregate root when loading it with Nhibernate. Load a Customer with all their Orders that have been shipped. Is this possible?</p>
|
[
{
"answer_id": 248184,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 2,
"selected": false,
"text": "<bag name=\"shippedOrders\" ... where=\"Status == 'Shipped'\" >\n <key column=\"CustomerId\" />\n <one-to-many class=\"Order\" />\n</bag>\n orderRepository.GetOrders(int customerId, OrderStatus[] statuses)\n"
},
{
"answer_id": 250135,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "session.CreateCriteria( typeOf(Order) )\n .Add( Restrictions.Eq(\"Shipped\", shippedStatus ) )\n .Add( Restrictions.Eq(\"Customer\", requiredCustomer) )\n .List<Order>();\n"
},
{
"answer_id": 868955,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 1,
"selected": false,
"text": "ICriteria crit = session.CreateCriteria (typeof(Customer));\n\ncrit.CreateAlias (\"Orders\", \"o\");\ncrit.Add (Expression.Eq (\"o.Status\", shippedStatus));\ncrit.Add (Expression.Eq (\"Id\", customerId));\n\nreturn crit.UniqueResult <Customer>();\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,573
|
<p>When a web form is submitted and takes the user to another page, it is quite often the case that the user will click the Back button in order to submit the form again (the form is an advanced search in my case.)</p>
<p>How can I reliably preserve the form options selected by the user when they click Back (so they don't have to start from scratch with filling the form in again if they are only changing one of many form elements?)</p>
<p>Do I have to go down the route of storing the form options in session data (cookies or server-side) or is there a way to get the browser to handle this for me?</p>
<p>(Environment is PHP/JavaScript - and the site must work on IE6+ and Firefox2+)</p>
|
[
{
"answer_id": 247630,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 0,
"selected": false,
"text": "$( document ).ready( function() {\n $.getJSON(\n \"/getformdata.php\",\n function( data ) {\n $.each( data.items, function(i,item) {\n $( '#' + item.eid ).val( item.val );\n } );\n });\n} );\n {\n 'items': [\n {\n 'eid': 'formfield1',\n 'val': 'John',\n },\n {\n 'eid': 'formfield2',\n 'val': 'Doe',\n }\n ]\n}\n"
},
{
"answer_id": 275343,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 0,
"selected": false,
"text": "$('#formSubmitButton').click( function() {\n var value = $('#searchbox').val();\n var days = 1;\n var date = new Date();\n date.setTime(date.getTime()+(days*24*60*60*1000));\n var expires = \"; expires=\"+date.toGMTString();\n document.cookie = \"searchbox=\"+value+expires+\"; path=/\";\n});\n\n$(document).ready( function() {\n var nameEQ = \"searchbox=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) var valueC = c.substring(nameEQ.length,c.length);\n }\n $('#searchbox').val(valueC);\n});\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24106/"
] |
247,596
|
<p>svg is an xml based graphics and you can add JavaScripts to it. I have tried to access to the script functions defined in a svg. The script in my svg is something like this:</p>
<pre><code><svg ... onload="RunScript(evt);"...>
<script type="text/javascript">
...
function RunScript(loadEvent) {
// Get object in my html by id
var objElement = top.document.getElementById('objid1');
if (objElement)
{
// Extend object tag object's methods
objElement.SVGsetDimension = setDimension;
...
}
function setDimention(w, h) {...}
</code></pre>
<p>In my main html file, the svg is embedded in an object tag like this:</p>
<pre><code><object id="objid1" data="mygrahic.svg" ... >
<a href="#" onclick="document.getElementById('objid1').SVGsetDimention(10, 10);
return false;"
...>Set new dimention</a>...
</code></pre>
<p>This one works fine. However if the svg xml file is referenced by a full URL (on another site) like this:</p>
<pre><code><object id="objid1" data="http://www.artlibrary.net/myaccount/mygrahic.svg" ... >
</code></pre>
<p>the codes do not work any more. It looks like that I cannot attach the method defined in my svg script to a method in my main html object tag element, or the top or document is not available in this case, or getElementById(..) just cannot find my object element in my svg script. Is there any way I can do in the svg xml script to find my html element?</p>
<p>Not sure if this problem is caused by the different DOMs, and there is no way for my svg script codes to figure out another DOM's object or element. It would be nice if there is any solution.</p>
|
[
{
"answer_id": 247811,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 3,
"selected": true,
"text": "iframe"
},
{
"answer_id": 3510064,
"author": "Ms2ger",
"author_id": 33466,
"author_profile": "https://Stackoverflow.com/users/33466",
"pm_score": 2,
"selected": false,
"text": "<script>\nfunction stealPassword() {\n var passwordInput = document.querySelector('input[type=\"password\"]');\n var value = passwordInput.value; // My password!\n sendPasswordToServerToStealMyMoney(value);\n}\n</script>\n<iframe src=mybank.com onload=stealPassword()></iframe>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
247,607
|
<p>I'm trying to use xcodebuild and OCUnit with my Continuous Integration server (<a href="http://www.jetbrains.com/teamcity/" rel="noreferrer">TeamCity</a>). </p>
<p>JetBrains offers test observer implementations for boost::test and CppUnit that format test output in a way that TeamCity can interpret. I need to do something similar for OCUnit if I want to use it.</p>
<p>There appears to be a SenTestObserver class in OCUnit but I'm ignorant of how exactly it should be used, and the <a href="http://www.sente.ch/software/ocunit/" rel="noreferrer">OCUnit homepage</a> doesn't seem to provide any documentation on the matter.</p>
|
[
{
"answer_id": 6149887,
"author": "Johannes Rudolph",
"author_id": 125407,
"author_profile": "https://Stackoverflow.com/users/125407",
"pm_score": 2,
"selected": false,
"text": "+(void)initialize\n{\n [[NSUserDefaults standardUserDefaults] setValue:@\"TeamCityAdapter\" forKey:@\"SenTestObserverClass\"];\n // we need to force SenTestObserver to register us as a handler\n // SenTestObserver is properly guarding against this invocation so nothing bad will hapen\n // but this is required (bad design on SenTestObserver's side)...\n [super initialize];\n}\n + (void) initialize\n{\n if ([self class] == [SenTestObserver class]) {\n NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];\n NSDictionary *registeredDefaults = [NSDictionary dictionaryWithObjectsAndKeys:\n @\"SenTestLog\" , @\"SenTestObserverClass\",\n nil];\n [defaults registerDefaults:registeredDefaults];\n [NSClassFromString ([defaults objectForKey:@\"SenTestObserverClass\"]) class]; // make sure default observer is loaded\n }\n\n if ([[[NSUserDefaults standardUserDefaults] objectForKey:@\"SenTestObserverClass\"] isEqualToString:NSStringFromClass(self)]) {\n [self setCurrentObserver:self];\n }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20480/"
] |
247,621
|
<p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about <strong><em>C# 3.5</em></strong>?</p>
<p>This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. <strong><em>C# 3.5</em></strong>. The hope is that anyone failing to find an answer with the wrong version number will find <em>this</em> question and then search again with the right version number.</p>
|
[
{
"answer_id": 247623,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 13,
"selected": true,
"text": "Dispose IEnumerator IDisposable var dynamic await catch finally Add out unmanaged ref stackalloc fixed fixed == != new ?? ? ref partial int GetEnumerator using CallerArgumentExpression #line Span<char> IntPtr ref scoped ref Environment.Version"
},
{
"answer_id": 16661422,
"author": "Gennady Vanin Геннадий Ванин",
"author_id": 200449,
"author_profile": "https://Stackoverflow.com/users/200449",
"pm_score": 5,
"selected": false,
"text": "0"
},
{
"answer_id": 63316829,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Version .NET Framework Visual Studio Important Features\n"
},
{
"answer_id": 71309649,
"author": "Darth-CodeX",
"author_id": 17939455,
"author_profile": "https://Stackoverflow.com/users/17939455",
"pm_score": 0,
"selected": false,
"text": "READ MORE"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22656/"
] |
247,626
|
<p>How can I set cron to run certain commands every one and a half hours?</p>
|
[
{
"answer_id": 247640,
"author": "vfilby",
"author_id": 24279,
"author_profile": "https://Stackoverflow.com/users/24279",
"pm_score": 4,
"selected": false,
"text": "0 0,3,6,9,12,15,18,21 * * * <commands>\n30 1,4,7,10,13,16,19,22 * * * <commands>\n"
},
{
"answer_id": 247643,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": false,
"text": "cron 0 0,3,6,9,12,15,18,21 * * * [cmd]\n30 1,4,7,10,13,16,19,22 * * * [cmd]\n 0 */3 * * * [cmd]\n30 1-23/3 * * * [cmd]\n"
},
{
"answer_id": 247644,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 3,
"selected": false,
"text": "0 0,3,6,9,12,15,18,21 * * * /usr/bin/foo\n30 1,4,7,10,13,16,19,22 * * * /usr/bin/foo\n"
},
{
"answer_id": 247749,
"author": "Christian Lescuyer",
"author_id": 341,
"author_profile": "https://Stackoverflow.com/users/341",
"pm_score": 1,
"selected": false,
"text": "@ 01h30 my_cmd\n"
},
{
"answer_id": 21820687,
"author": "user3174711",
"author_id": 3174711,
"author_profile": "https://Stackoverflow.com/users/3174711",
"pm_score": 1,
"selected": false,
"text": "#! /bin/sh\n\n# Minute Cron\n# Usage: cron-min start\n# Copyright 2014 by Marc Perkel\n# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron\"\n# Free to use with attribution\n\n# Run this script under Cron once a minute\n\nbasedir=/etc/cron-min\n\nif [ $# -gt 0 ]\nthen\n echo\n echo \"cron-min by Marc Perkel\"\n echo\n echo \"This program is used to run all programs in a directory in parallel every X minutes.\"\n echo\n echo \"Usage: cron-min\"\n echo\n echo \"The scheduling is done by creating directories with the number of minutes as part of the\"\n echo \"directory name. The minutes do not have to evenly divide into 60 or be less than 60.\"\n echo\n echo \"Examples:\"\n echo \" /etc/cron-min/1 # Executes everything in that directory every 1 minute\"\n echo \" /etc/cron-min/5 # Executes everything in that directory every 5 minutes\"\n echo \" /etc/cron-min/13 # Executes everything in that directory every 13 minutes\"\n echo \" /etc/cron-min/90 # Executes everything in that directory every 90 minutes\"\n echo\n exit\nfi\n\nfor dir in $basedir/* ; do\n minutes=${dir##*/}\n if [ $(( ($(date +%s) / 60) % $minutes )) -eq 0 ]\n then\n for program in $basedir/$minutes/* ; do\n if [ -x $program ]\n then\n $program &> /dev/null &\n fi\n done\n fi\ndone\n"
},
{
"answer_id": 24449393,
"author": "user3782709",
"author_id": 3782709,
"author_profile": "https://Stackoverflow.com/users/3782709",
"pm_score": -1,
"selected": false,
"text": "15 */1 * * * root /usr/bin/some_script.sh >> /tmp/something.log\n"
},
{
"answer_id": 25537959,
"author": "Alex",
"author_id": 3984676,
"author_profile": "https://Stackoverflow.com/users/3984676",
"pm_score": 2,
"selected": false,
"text": "*/10 * * * * root perl -e 'exit(time()%(90*60)>60)' && command * * * * * root perl -e 'exit(time()%(71*60)>60)' && command"
},
{
"answer_id": 31759088,
"author": "stefanmaric",
"author_id": 2457929,
"author_profile": "https://Stackoverflow.com/users/2457929",
"pm_score": 2,
"selected": false,
"text": "#!/bin/bash\n\nminutesSinceEpoch=$(($(date +'%s / 60')))\n\n# every 90 minutes (one and a half hours)\nif [[ $(($minutesSinceEpoch % 90)) -ne 0 ]]; then\n exit 0\nfi\n date(1) %s # .---------------------- bash command substitution\n# |.--------------------- bash arithmetic expansion\n# || .------------------- bash command substitution\n# || | .---------------- date command\n# || | | .------------ FORMAT argument\n# || | | | .----- formula to calculate minutes/hours/days/etc is included into the format string passed to date command\n# || | | | |\n# ** * * * * \n $(($(date +'%s / 60')))\n# * * ---------------\n# | | | \n# | | ·----------- date should result in something like \"1438390397 / 60\"\n# | ·-------------------- it gets evaluated as an expression. (the maths)\n# ·---------------------- and we can store it\n #!/bin/bash\n# We can get the\n\nminutes=$(($(date +'%s / 60')))\nhours=$(($(date +'%s / 60 / 60')))\ndays=$(($(date +'%s / 60 / 60 / 24')))\nweeks=$(($(date +'%s / 60 / 60 / 24 / 7')))\n\n# or even\n\nmoons=$(($(date +'%s / 60 / 60 / 24 / 656')))\n\n# passed since Epoch and define a frequency\n# let's say, every 7 hours\n\nif [[ $(($hours % 7)) -ne 0 ]]; then\n exit 0\nfi\n\n# and your actual script starts here\n"
},
{
"answer_id": 70652799,
"author": "Marzycielx",
"author_id": 15670345,
"author_profile": "https://Stackoverflow.com/users/15670345",
"pm_score": 1,
"selected": false,
"text": "0 */3 * * * echo \"Command\" | at now +90 minutes && Command"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
247,636
|
<p>SSIS 2005/2008 does fuzzy lookups and groupings. Is there a feature that does the same in T-SQL?</p>
|
[
{
"answer_id": 247653,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 3,
"selected": false,
"text": "SELECT * \nFROM Customers\nWHERE SOUNDEX(Lastname) = SOUNDEX('Stonehouse')\nAND SOUNDEX(Firstname) = SOUNDEX('Scott')\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2342/"
] |
247,639
|
<p>I have seen a codebase recently that I fear is violating alignment constraints. I've scrubbed it to produce a minimal example, given below. Briefly, the players are:</p>
<ul>
<li><p><em>Pool</em>. This is a class which allocates memory efficiently, for some definition of 'efficient'. <em>Pool</em> is guaranteed to return a chunk of memory that is aligned for the requested size.</p></li>
<li><p><em>Obj_list</em>. This class stores homogeneous collections of objects. Once the number of objects exceeds a certain threshold, it changes its internal representation from a list to a tree. The size of <em>Obj_list</em> is one pointer (8 bytes on a 64-bit platform). Its populated store will of course exceed that.</p></li>
<li><p><em>Aggregate</em>. This class represents a very common object in the system. Its history goes back to the early 32-bit workstation era, and it was 'optimized' (in that same 32-bit era) to use as little space as possible as a result. <em>Aggregate</em>s can be empty, or manage an arbitrary number of objects.</p></li>
</ul>
<p>In this example, <em>Aggregate</em> items are always allocated from <em>Pool</em>s, so they are always aligned. The only occurrences of <em>Obj_list</em> in this example are the 'hidden' members in <em>Aggregate</em> objects, and therefore they are always allocated using <em>placement new</em>. Here are the support classes:</p>
<pre><code>class Pool
{
public:
Pool();
virtual ~Pool();
void *allocate(size_t size);
static Pool *default_pool(); // returns a global pool
};
class Obj_list
{
public:
inline void *operator new(size_t s, void * p) { return p; }
Obj_list(const Args *args);
// when constructed, Obj_list will allocate representation_p, which
// can take up much more space.
~Obj_list();
private:
Obj_list_store *representation_p;
};
</code></pre>
<p>And here is Aggregate. Note that member declaration <em>member_list_store_d</em>:</p>
<pre><code>// Aggregate is derived from Lesser, which is twelve bytes in size
class Aggregate : public Lesser
{
public:
inline void *operator new(size_t s) {
return Pool::default_pool->allocate(s);
}
inline void *operator new(size_t s, Pool *h) {
return h->allocate(s);
}
public:
Aggregate(const Args *args = NULL);
virtual ~Aggregate() {};
inline const Obj_list *member_list_store_p() const;
protected:
char member_list_store_d[sizeof(Obj_list)];
};
</code></pre>
<p>It is that data member that I'm most concerned about. Here is the pseudocode for initialization and access:</p>
<pre><code>Aggregate::Aggregate(const Args *args)
{
if (args) {
new (static_cast<void *>(member_list_store_d)) Obj_list(args);
}
else {
zero_out(member_list_store_d);
}
}
inline const Obj_list *Aggregate::member_list_store_p() const
{
return initialized(member_list_store_d) ? (Obj_list *) &member_list_store_d : 0;
}
</code></pre>
<p>You may be tempted to suggest that we replace the char array with a pointer to the <em>Obj_list</em> type, initialized to NULL or an instance of the class. This gives the proper semantics, but just shifts the memory cost around. If memory were still at a premium (and it might be, this is an EDA database representation), replacing the char array with a pointer to an <em>Obj_list</em> would cost one more pointer in the case when <em>Aggregate</em> objects <em>do</em> have members.</p>
<p>Besides that, I don't really want to get distracted from the main question here, which is alignment. I <em>think</em> the above construct is problematic, but can't really find more in the standard than some vague discussion of the alignment behavior of the 'system/library' <em>new</em>.</p>
<p>So, does the above construct do anything more than cause an occasional pipe stall?</p>
<p><strong>Edit</strong>: I realize that there are ways to <em>replace</em> the approach using the embedded char array. So did the original architects. They discarded them because memory was at a premium. Now, if I have a reason to touch that code, I'll probably change it.</p>
<p>However, my question, about the alignment issues inherent in this approach, is what I hope people will address. Thanks!</p>
|
[
{
"answer_id": 248826,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 0,
"selected": false,
"text": "member_list_store_d"
},
{
"answer_id": 248860,
"author": "PiNoYBoY82",
"author_id": 13646,
"author_profile": "https://Stackoverflow.com/users/13646",
"pm_score": 1,
"selected": false,
"text": "// MSVC\n#pragma pack(push,1)\n\n// structure definitions\n\n#pragma pack(pop)\n\n// *nix\nstruct YourStruct\n{\n ....\n} __attribute__((packed));\n"
},
{
"answer_id": 250159,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": true,
"text": "Obj_list list;\n list.~Obj_list();\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3778/"
] |
247,656
|
<p>What are the current best practices in the Rails world for displaying a calendar month view with event items bound to the days in the month (like in Backpack or Google Calendar, for example)?</p>
<p>I don't need anything like fancy stuff like drag and drop support. I'm just looking for code to let me get a list of events in my controller and somehow expose them as entries in a monthly calendar display view (maybe with class names on the HTML elements to allow me to display different types of events differently, or maybe to display events from multiple calendars).</p>
<p>There's the <a href="http://oldwiki.rubyonrails.org/rails/pages/DynamicCalendarHelper" rel="nofollow noreferrer">Dynamic Calendar Helper</a> that was created a few years ago, which very well might still work just fine for me, but I'm just wondering if I should be looking at other plugins, too.</p>
<p>Other possibilities I've found so far:</p>
<ul>
<li><a href="http://github.com/search?q=rails+calendar" rel="nofollow noreferrer">A few possible contenders</a>
(judging from their descriptions) on
GitHub</li>
<li><a href="http://joyent.com/connector/" rel="nofollow noreferrer">Joyent Connector</a>, which is now
open source, has calendar
capabilities</li>
</ul>
<p>So, can you point me in the right direction as to what folks are using to output monthly calendars with data these days?</p>
|
[
{
"answer_id": 496101,
"author": "user60683",
"author_id": 60683,
"author_profile": "https://Stackoverflow.com/users/60683",
"pm_score": 3,
"selected": false,
"text": " <% calendar_for(@tasks, :year => @year, :month => @month) do |t| %>\n <%= t.head('mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun') %>\n <% t.day(:day_method => YOUR_DATE_METHOD) do |day, tasks| %>\n <%= day.day %><br />\n <% tasks.each do |task| %>\n <%= h(task.name) %><br />\n <% end %>\n <% end %>\n <% end %>\n <% end %>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30632/"
] |
247,666
|
<p>I need to use C# programatically to append several preexisting <code>docx</code> files into a single, long <code>docx</code> file - including special markups like bullets and images. Header and footer information will be stripped out, so those won't be around to cause any problems.</p>
<p>I can find plenty of information about manipulating an individual <code>docx</code> file with .NET Framework 3, but nothing easy or obvious about how you would merge files. There is also a third-party program (Acronis.Words) that will do it, but it is prohibitively expensive.</p>
<h2>Update:</h2>
<p>Automating through Word has been suggested, but my code is going to be running on ASP.NET on an IIS web server, so going out to Word is not an option for me. Sorry for not mentioning that in the first place.</p>
|
[
{
"answer_id": 248249,
"author": "Terence Lewis",
"author_id": 32539,
"author_profile": "https://Stackoverflow.com/users/32539",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nusing Microsoft.Office.Interop.Word;\nusing Microsoft.Office.Core;\nusing System.Runtime.InteropServices;\nusing System.IO;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n new Program().Start();\n }\n\n private void Start()\n {\n object fileName = Path.Combine(Environment.CurrentDirectory, @\"NewDocument.doc\");\n File.Delete(fileName.ToString());\n\n try\n {\n WordApplication = new ApplicationClass();\n var doc = WordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);\n try\n {\n doc.Activate();\n\n AddDocument(@\"D:\\Projects\\WordTests\\ConsoleApplication1\\Documents\\Doc1.doc\", doc, false);\n AddDocument(@\"D:\\Projects\\WordTests\\ConsoleApplication1\\Documents\\Doc2.doc\", doc, true);\n\n doc.SaveAs(ref fileName,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing);\n }\n finally\n {\n doc.Close(ref missing, ref missing, ref missing);\n }\n }\n finally\n {\n WordApplication.Quit(ref missing, ref missing, ref missing);\n }\n }\n\n private void AddDocument(string path, Document doc, bool lastDocument)\n {\n object subDocPath = path;\n var subDoc = WordApplication.Documents.Open(ref subDocPath, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing);\n try\n {\n\n object docStart = doc.Content.End - 1;\n object docEnd = doc.Content.End;\n\n object start = subDoc.Content.Start;\n object end = subDoc.Content.End;\n\n Range rng = doc.Range(ref docStart, ref docEnd);\n rng.FormattedText = subDoc.Range(ref start, ref end);\n\n if (!lastDocument)\n {\n InsertPageBreak(doc);\n }\n }\n finally\n {\n subDoc.Close(ref missing, ref missing, ref missing);\n }\n }\n\n private static void InsertPageBreak(Document doc)\n {\n object docStart = doc.Content.End - 1;\n object docEnd = doc.Content.End;\n Range rng = doc.Range(ref docStart, ref docEnd);\n\n object pageBreak = WdBreakType.wdPageBreak;\n rng.InsertBreak(ref pageBreak);\n }\n\n private ApplicationClass WordApplication { get; set; }\n\n private object missing = Type.Missing;\n }\n}\n"
},
{
"answer_id": 465257,
"author": "Pete Skelly",
"author_id": 57516,
"author_profile": "https://Stackoverflow.com/users/57516",
"pm_score": 2,
"selected": false,
"text": "public void AddAltChunkPart(Stream parentStream, Stream altStream, string altChunkId)\n{\n //make sure we are at the start of the stream \n parentStream.Position = 0;\n altStream.Position = 0;\n //push the parentStream into a WordProcessing Document\n using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(parentStream, true))\n {\n //get the main document part\n MainDocumentPart mainPart = wordDoc.MainDocumentPart;\n //create an altChunk part by adding a part to the main document part\n AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(altChunkPartType, altChunkId);\n //feed the altChunk stream into the chunk part\n chunk.FeedData(altStream);\n //create and XElement to represent the new chunk in the document\n XElement newChunk = new XElement(altChunk, new XAttribute(relId, altChunkId));\n //Add the chunk to the end of the document (search to last paragraph in body and add at the end)\n wordDoc.MainDocumentPart.GetXDocument().Root.Element(body).Elements(paragraph).Last().AddAfterSelf(newChunk);\n //Finally, save the document\n wordDoc.MainDocumentPart.PutXDocument();\n }\n //reset position of parent stream\n parentStream.Position = 0;\n}\n"
},
{
"answer_id": 470631,
"author": "Sumit Ghosh",
"author_id": 56150,
"author_profile": "https://Stackoverflow.com/users/56150",
"pm_score": 0,
"selected": false,
"text": " Word._Application wordApp;\n Word._Document wordDoc;\n object outputFile = outputFileName;\n object missing = System.Type.Missing;\n object vk_false = false;\n object defaultTemplate = defaultWordDocumentTemplate;\n object pageBreak = Word.WdBreakType.wdPageBreak;\n string[] filesToMerge = new string[pageCounter];\n filestoDelete = new string[pageCounter];\n\n for (int i = 0; i < pageCounter; i++)\n {\n filesToMerge[i] = @\"C:\\temp\\temp\" + i.ToString() + \".rtf\";\n filestoDelete[i] = @\"C:\\temp\\temp\" + i.ToString() + \".rtf\"; \n }\n try\n {\n wordDoc = wordApp.Documents.Add(ref missing, ref missing, ref missing, ref missing);\n }\n catch(Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n Word.Selection selection= wordApp.Selection;\n\n foreach (string file in filesToMerge)\n {\n selection.InsertFile(file,\n ref missing,\n ref missing,\n ref missing,\n ref missing);\n\n selection.InsertBreak(ref pageBreak); \n }\n wordDoc.SaveAs(ref outputFile, ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,\n ref missing, ref missing);\n"
},
{
"answer_id": 2463729,
"author": "GRGodoi",
"author_id": 71666,
"author_profile": "https://Stackoverflow.com/users/71666",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.IO;\nusing System.Xml.Linq;\nusing DocumentFormat.OpenXml.Packaging;\nusing DocumentFormat.OpenXml.Wordprocessing;\n\nnamespace OfficeMergeControl\n{\n public class CombineDocs\n {\n public byte[] OpenAndCombine( IList<byte[]> documents )\n {\n MemoryStream mainStream = new MemoryStream();\n\n mainStream.Write(documents[0], 0, documents[0].Length);\n mainStream.Position = 0;\n\n int pointer = 1;\n byte[] ret;\n try\n {\n using (WordprocessingDocument mainDocument = WordprocessingDocument.Open(mainStream, true))\n {\n\n XElement newBody = XElement.Parse(mainDocument.MainDocumentPart.Document.Body.OuterXml);\n\n for (pointer = 1; pointer < documents.Count; pointer++)\n {\n WordprocessingDocument tempDocument = WordprocessingDocument.Open(new MemoryStream(documents[pointer]), true);\n XElement tempBody = XElement.Parse(tempDocument.MainDocumentPart.Document.Body.OuterXml);\n\n newBody.Add(tempBody);\n mainDocument.MainDocumentPart.Document.Body = new Body(newBody.ToString());\n mainDocument.MainDocumentPart.Document.Save();\n mainDocument.Package.Flush();\n }\n }\n }\n catch (OpenXmlPackageException oxmle)\n {\n throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, \"Error while merging files. Document index {0}\", pointer), oxmle);\n }\n catch (Exception e)\n {\n throw new OfficeMergeControlException(string.Format(CultureInfo.CurrentCulture, \"Error while merging files. Document index {0}\", pointer), e);\n }\n finally\n {\n ret = mainStream.ToArray();\n mainStream.Close();\n mainStream.Dispose();\n }\n return (ret);\n }\n }\n}\n"
},
{
"answer_id": 12089639,
"author": "Mike B",
"author_id": 560237,
"author_profile": "https://Stackoverflow.com/users/560237",
"pm_score": 3,
"selected": false,
"text": "public byte[] CreateDocument(IList<byte[]> documentsToMerge)\n{\n List<Source> documentBuilderSources = new List<Source>();\n foreach (byte[] documentByteArray in documentsToMerge)\n {\n documentBuilderSources.Add(new Source(new WmlDocument(string.Empty, documentByteArray), false));\n }\n\n WmlDocument mergedDocument = DocumentBuilder.BuildDocument(documentBuilderSources);\n return mergedDocument.DocumentByteArray;\n}\n public byte[] CreateDocument(IList<DocumentSection> documentTemplates)\n{\n List<Source> documentBuilderSources = new List<Source>();\n foreach (DocumentSection documentTemplate in documentTemplates.OrderBy(dt => dt.Rank))\n {\n // Take the template replace the items and then push it into the chunk\n using (MemoryStream templateStream = new MemoryStream())\n {\n templateStream.Write(documentTemplate.Template, 0, documentTemplate.Template.Length);\n\n this.ProcessOpenXMLDocument(templateStream, documentTemplate.Fields);\n\n documentBuilderSources.Add(new Source(new WmlDocument(string.Empty, templateStream.ToArray()), false));\n }\n }\n\n WmlDocument mergedDocument = DocumentBuilder.BuildDocument(documentBuilderSources);\n return mergedDocument.DocumentByteArray;\n}\n"
},
{
"answer_id": 60540185,
"author": "Jinjinov",
"author_id": 4675770,
"author_profile": "https://Stackoverflow.com/users/4675770",
"pm_score": 0,
"selected": false,
"text": "void AppendToExistingFile(string existingFile, IList<string> filenames)\n{\n using (WordprocessingDocument document = WordprocessingDocument.Open(existingFile, true))\n {\n MainDocumentPart mainPart = document.MainDocumentPart;\n\n for (int i = filenames.Count - 1; i >= 0; --i)\n {\n string altChunkId = \"AltChunkId\" + i;\n AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.WordprocessingML, altChunkId);\n\n using (FileStream fileStream = File.Open(filenames[i], FileMode.Open))\n {\n chunk.FeedData(fileStream);\n }\n\n AltChunk altChunk = new AltChunk { Id = altChunkId };\n mainPart.Document.Body.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());\n }\n\n mainPart.Document.Save();\n }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32471/"
] |
247,668
|
<p>I'm trying to access the command line and execute a command, and then return the output to my aspx page. A good example would be running dir on page load of an aspx page and returning the output via Response.Write(). I have tried using the code below. When I try debugging this it runs but never finishes loading and no output is rendered.
I am using C# and .NET Framework 3.5sp1. Any help much appreciated.</p>
<p>Thanks,
Bryan</p>
<pre><code>public partial class CommandLine : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
System.Diagnostics.Process si = new System.Diagnostics.Process();
si.StartInfo.WorkingDirectory = @"c:\";
si.StartInfo.UseShellExecute = false;
si.StartInfo.FileName = "cmd.exe";
si.StartInfo.Arguments = "dir";
si.StartInfo.CreateNoWindow = true;
si.StartInfo.RedirectStandardInput = true;
si.StartInfo.RedirectStandardOutput = true;
si.StartInfo.RedirectStandardError = true;
si.Start();
string output = si.StandardOutput.ReadToEnd();
si.Close();
Response.Write(output);
}
}
</code></pre>
|
[
{
"answer_id": 247699,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": true,
"text": " si.StartInfo.Arguments = \"dir\";\n si.StartInfo.Arguments = \"/c dir\";\n"
},
{
"answer_id": 247735,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": " ///////////////////////////////////////////////////////////////////////\n public static string run_svn(string args_without_password, string svn_username, string svn_password)\n {\n // run \"svn.exe\" and capture its output\n\n System.Diagnostics.Process p = new System.Diagnostics.Process();\n string svn_path = Util.get_setting(\"SubversionPathToSvn\", \"svn\");\n p.StartInfo.FileName = svn_path;\n p.StartInfo.UseShellExecute = false;\n p.StartInfo.RedirectStandardOutput = true;\n p.StartInfo.RedirectStandardError = true;\n\n args_without_password += \" --non-interactive\";\n Util.write_to_log (\"Subversion command:\" + svn_path + \" \" + args_without_password);\n\n string args_with_password = args_without_password;\n\n if (svn_username != \"\")\n {\n args_with_password += \" --username \";\n args_with_password += svn_username;\n args_with_password += \" --password \";\n args_with_password += svn_password;\n }\n\n p.StartInfo.Arguments = args_with_password;\n p.Start();\n string stdout = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n stdout += p.StandardOutput.ReadToEnd();\n\n string error = p.StandardError.ReadToEnd();\n\n if (error != \"\")\n {\n Util.write_to_log(error);\n Util.write_to_log(stdout);\n }\n\n if (error != \"\")\n {\n string msg = \"ERROR:\";\n msg += \"<div style='color:red; font-weight: bold; font-size: 10pt;'>\";\n msg += \"<br>Error executing svn.exe command from web server.\";\n msg += \"<br>\" + error;\n msg += \"<br>Arguments passed to svn.exe (except user/password):\" + args_without_password;\n if (error.Contains(\"File not found\"))\n {\n msg += \"<br><br>***** Has this file been deleted or renamed? See the following links:\";\n msg += \"<br><a href=http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html>http://svn.collab.net/repos/svn/trunk/doc/user/svn-best-practices.html</a>\";\n msg += \"<br><a href=http://subversion.open.collab.net/articles/best-practices.html>http://subversion.open.collab.net/articles/best-practices.html</a>\";\n msg += \"</div>\";\n }\n return msg;\n }\n else\n {\n return stdout;\n }\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32474/"
] |
247,678
|
<p>I have a Perl application that parses MediaWiki SQL tables and displays data from multiple wiki pages. I need to be able to re-create the absolute image path to display the images, eg: <code>.../f/fc/Herbs.jpg/300px-Herbs.jpg</code> </p>
<p>From MediaWiki Manual:</p>
<blockquote>
<p>Image_Authorisation: "the [image] path can be calculated easily from the file name and..." </p>
</blockquote>
<p>How is the path calculated? </p>
|
[
{
"answer_id": 248086,
"author": "JDrago",
"author_id": 29060,
"author_profile": "https://Stackoverflow.com/users/29060",
"pm_score": 3,
"selected": true,
"text": "use Digest::MD5 'md5_hex';\nmy $sig = md5_hex( $file->id );\n my $path = '/usr/local/media';\nmap { mkdir($path, 0666); $path .= \"/$_\" } $sig =~ m/^(..)(..)(..)/;\nopen my $ofh, '>', \"$path/$sig\"\n or die \"Cannot open '$path/$sig' for writing: $!\";\nprint $ofh \"File contents\";\nclose($ofh);\n /\n usr/\n local/\n media/\n 1f/\n f8/\n a7/\n 1ff8a7b5dc7a7d1f0ed65aaa29c04b1e\n"
},
{
"answer_id": 255013,
"author": "gradbot",
"author_id": 17919,
"author_profile": "https://Stackoverflow.com/users/17919",
"pm_score": 2,
"selected": false,
"text": "$url = wfFindFile(Title::makeTitle(NS_IMAGE, $fileName))->getURL();\n"
},
{
"answer_id": 35853041,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\ncd /opt/mediawiki/mediawiki-cur/images\n\nfor i in `find -maxdepth 1 -type f ! -name .htaccess ! -name README ! -name reorder.sh -printf '%f\\n'`; do\n path1=$(echo -n $i | md5sum | head -c1) &&\n path2=$(echo -n $i | md5sum | head -c2) &&\n mkdir -p $path1/$path2/ &&\n mv $i $path1/$path2/;\ndone\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247678",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32477/"
] |
247,691
|
<p>Seems like rel-license only applies to pages not to specific elements... anyone spotted usage for page elements in the wild?</p>
|
[
{
"answer_id": 285720,
"author": "Anirvan",
"author_id": 31100,
"author_profile": "https://Stackoverflow.com/users/31100",
"pm_score": 1,
"selected": false,
"text": "rel-license rel-license"
},
{
"answer_id": 582905,
"author": "Scott",
"author_id": 6126,
"author_profile": "https://Stackoverflow.com/users/6126",
"pm_score": 0,
"selected": false,
"text": "<p id=\"someparagraph\">Lorum ipsum dolor sit amet.</p>\n<div about=\"#someparagraph\">\n<a href=\"http://creativecommons.org/licenses/by/2.0/\" rel=\"license\">cc by 2.0</a>\n</div>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23652/"
] |
247,703
|
<p>Is there a (standardized) way to get the name of the current method using c++? </p>
<p>Using GNU GCC you can do this by using the macro <code>__FUNCTION__</code> and <code>__PRETTY_FUNCTION__</code> (surrounded by 2 underscores), however, this is of course non portable. Is there a way to do this in standard c++ or a way to make it portable?</p>
|
[
{
"answer_id": 247721,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 6,
"selected": true,
"text": "__func__ __func__ static const char __func__[] = \"function-name\";\n function-name"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23163/"
] |
247,706
|
<p>In Bash I'm executing a command and putting the result in a variable like this:</p>
<pre>export var=`svn ls`</pre>
<p>But if SVN fails for some reason--say it returns a non-zero error code--export still returns status code 0. How do I detect if the executed command fails?</p>
|
[
{
"answer_id": 247751,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "var=`svn ls`\nif [[ $? == 0 ]]\nthen\n export var\nelse\n unset var\nfi\n $? svn ls var=`svn ls` && export var || unset var\n export unset $var"
},
{
"answer_id": 247774,
"author": "jmohr",
"author_id": 16548,
"author_profile": "https://Stackoverflow.com/users/16548",
"pm_score": 2,
"selected": false,
"text": "var=`svn ls` && export var\n"
},
{
"answer_id": 248223,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": -1,
"selected": false,
"text": "export FOO=$(your-command) || echo \"your-command failed\"\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/79/"
] |
247,708
|
<p>While the built-in analytics of MOSS2007 are nice to have - they are inadequate at the same time. Any ideas where I can look for a more comprehensive package? Am I missing something?</p>
<p>Thanks,
Carl</p>
|
[
{
"answer_id": 247751,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": true,
"text": "var=`svn ls`\nif [[ $? == 0 ]]\nthen\n export var\nelse\n unset var\nfi\n $? svn ls var=`svn ls` && export var || unset var\n export unset $var"
},
{
"answer_id": 247774,
"author": "jmohr",
"author_id": 16548,
"author_profile": "https://Stackoverflow.com/users/16548",
"pm_score": 2,
"selected": false,
"text": "var=`svn ls` && export var\n"
},
{
"answer_id": 248223,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": -1,
"selected": false,
"text": "export FOO=$(your-command) || echo \"your-command failed\"\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32480/"
] |
247,718
|
<p>I am calling a SQL proc that has 3 OUTPUT params. After the call to the proc one of the params does not return a value when the other two do. Profiler shows that all 3 values are being returned.</p>
<p>The params are declared as follows in the proc...</p>
<pre><code>@UsrVariableID INT OUTPUT,
@OrganisationName NVARCHAR(256) OUTPUT,
@Visible bit OUTPUT
</code></pre>
<p>and the code that calls the proc is like this...</p>
<pre><code>cm.Parameters.AddWithValue("@OrganisationName", name);
cm.Parameters["@OrganisationName"].Direction = ParameterDirection.Output;
cm.Parameters.AddWithValue("@Visible", visible);
cm.Parameters["@Visible"].Direction = ParameterDirection.Output;
cm.ExecuteNonQuery();
name = cm.Parameters["@OrganisationName"].Value.ToString();
visible = bool.Parse(cm.Parameters["@Visible"].Value.ToString());
id = int.Parse(cm.Parameters["@UsrVariableID"].Value.ToString());
</code></pre>
<p>The param that fails is @OrganisationName.</p>
<p>I'm wondering if its because the param is of type string in the code but NVARCHAR in the proc.</p>
<p>Anyone got any ideas?</p>
|
[
{
"answer_id": 247755,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 2,
"selected": false,
"text": "cm.Parameters.Add[\"@OrganisationName\", SqlDbType.NVarChar, 256].Direction = ParameterDirection.Output\ncm.Parameters[\"@OrganisationName\"].Value = name\n visible = bool.Parse(cm.Parameters[\"@Visible\"].Value.ToString()); visible = (bool)cm.Parameters[\"@Visible\"].Value;"
},
{
"answer_id": 247771,
"author": "chilltemp",
"author_id": 28736,
"author_profile": "https://Stackoverflow.com/users/28736",
"pm_score": 1,
"selected": false,
"text": "cm.Parameters[\"@OrganisationName\"].Size = 256;\n"
},
{
"answer_id": 247822,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 4,
"selected": true,
"text": "SqlParameter theOrganizationNameParam = new SqlParameter( \"@OrganisationName\", SqlDbType.NVarChar, 256 );\ntheOrganizationNameParam.Direction = ParameterDirection.Output;\ncm.Parameters.Add( theOrganizationNameParam );\ncm.ExecuteNonQuery();\nname = theOrganizationNameParam.Value;\n"
},
{
"answer_id": 829429,
"author": "User",
"author_id": 62830,
"author_profile": "https://Stackoverflow.com/users/62830",
"pm_score": 0,
"selected": false,
"text": "cm.Parameters[\"@OrganisationName\"].Size = 50;\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] |
247,724
|
<p>I am creating a Python script where it does a bunch of tasks and one of those tasks is to launch and open an instance of Excel. What is the ideal way of accomplishing that in my script?</p>
|
[
{
"answer_id": 247740,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 3,
"selected": false,
"text": "os.system(\"start excel.exe <path/to/file>\")\n start <filename>"
},
{
"answer_id": 247761,
"author": "crftr",
"author_id": 18213,
"author_profile": "https://Stackoverflow.com/users/18213",
"pm_score": 3,
"selected": false,
"text": "popen2 excelProcess = popen2.Popen4(\"start excel %s\" % (excelFile))\nstatus = excelProcess.wait()\n wait()"
},
{
"answer_id": 248080,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 5,
"selected": true,
"text": "Popen win32api from win32com.client import Dispatch\nxl = Dispatch('Excel.Application')\nwb = xl.Workbooks.Open('C:\\\\Documents and Settings\\\\GradeBook.xls')\nxl.Visible = True # optional: if you want to see the spreadsheet\n"
},
{
"answer_id": 249571,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 3,
"selected": false,
"text": "import subprocess\n\nprocess_one = subprocess.Popen(['gqview', '/home/toto/my_images'])\n\nprint process_one.pid\n"
},
{
"answer_id": 6351029,
"author": "codedude",
"author_id": 709115,
"author_profile": "https://Stackoverflow.com/users/709115",
"pm_score": 2,
"selected": false,
"text": "import os\nos.system(\"open /Applications/Safari.app\")\n"
},
{
"answer_id": 54100051,
"author": "microbenny",
"author_id": 2886382,
"author_profile": "https://Stackoverflow.com/users/2886382",
"pm_score": 0,
"selected": false,
"text": "os.startfile(\"path to file\") os.system(\"start excel filename\")"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
247,738
|
<p>If you have an STL vector which has been resized, is it safe to take the address of element 0 and assume the rest of the vector will follow in memory?</p>
<p>e.g.</p>
<pre><code>vector<char> vc(100);
// do some stuff with vc
vc.resize(200);
char* p = &vc[0];
// do stuff with *p
</code></pre>
|
[
{
"answer_id": 247762,
"author": "Frederik Slijkerman",
"author_id": 12416,
"author_profile": "https://Stackoverflow.com/users/12416",
"pm_score": 2,
"selected": false,
"text": "std::vector &myVector.front();\n"
},
{
"answer_id": 247902,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 5,
"selected": false,
"text": "vector v vector<T, Allocator> T bool &v[n] == &v[0] +\n n 0 <= n < v.size()"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
247,743
|
<p>I already know: "Don't use css expressions!" My question is not about whether I should be using an expression or if there is an alternative; my question is simply: <strong>Can I get a css expression to only be evaluated in versions of IE prior to version 7 without using conditional comments?</strong></p>
<p>I occasionally use an underscore hack to hide a rule from IE7 but IE7 seems to evaluate expressions anyway. For example, <code>_width:700px;</code> is ignored by IE7 but <code>_width:expression('700px');</code> is still evaluated.</p>
<p>I know that someone will try to tell me to just use a conditional comment to include the rule, but I am looking for a way to do this without placing a single style rule into a separate file.</p>
<p>A note for those of you who still don't want to let it go: I've chosen to use a css expression, but I didn't do so lightly. I understand the implications and I am using an expression that only evaluates once. Stop worrying about my bad decisions and just answer the question already... ;-)</p>
|
[
{
"answer_id": 247763,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": ".ie6 .myClass {}\n.ie7 .myClass {}\n.ie .myClass{}\n"
},
{
"answer_id": 247855,
"author": "Dave Anderson",
"author_id": 371,
"author_profile": "https://Stackoverflow.com/users/371",
"pm_score": 1,
"selected": false,
"text": "#myDiv {\n height: 3.0em !important; /* non-ie */\n height: 2.6em !ie-only; /* ie7 */\n height: 2.4em; /* ie < 7 */\n}\n"
},
{
"answer_id": 248021,
"author": "adgoudz",
"author_id": 30527,
"author_profile": "https://Stackoverflow.com/users/30527",
"pm_score": 3,
"selected": true,
"text": "/* IE6 only */ \n* html .myClass {\n width: 500px;\n}\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html>\n<head>\n <style type=\"text/css\">\n\n .ie6 {\n display: none;\n }\n\n * html .ie6 {\n display: expression(\"block\");\n }\n\n * html .ie7 {\n display: expression(\"none\");\n }\n\n </style>\n</head>\n<body>\n<div class=\"ie6\">\n This is IE6\n</div>\n<div class=\"ie7\">\n This is Firefox or IE7+\n</div>\n</body>\n</html>\n"
},
{
"answer_id": 7358842,
"author": "chris5marsh",
"author_id": 869117,
"author_profile": "https://Stackoverflow.com/users/869117",
"pm_score": 2,
"selected": false,
"text": "body <!--[if lte IE 7]>\n<body class=\"ie7\">\n<![endif]-->\n<!--[if gt IE 7]>-->\n<body>\n<!--<![endif]-->\n #content {\n width:720px;\n}\n\n.ie7 #content {\n width:700px;\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5628/"
] |
247,745
|
<p>I know that <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>B</kbd> launches a solution build, but I would like a shortcut that just builds the current project. Is a custom shortcut my only option?</p>
<p><strong>Edit:</strong> Looks like a custom shortcut is my only option as <kbd>Shift</kbd> + <kbd>F6</kbd> does not work for me.</p>
|
[
{
"answer_id": 22646603,
"author": "Darien Pardinas",
"author_id": 1416294,
"author_profile": "https://Stackoverflow.com/users/1416294",
"pm_score": 6,
"selected": false,
"text": "Alt + B, B -> Build Solution\nAlt + B, R -> Rebuild Solution\nAlt + B, U -> Build current project\nAlt + B, E -> Rebuild current project\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
247,768
|
<p>I am using JSF frontend for a page where an image is uploaded or deleted. Clicking on the upload or delete button causes a postback and the page to reload with the updated status. This however, resets the scroll position of the page. How should I go about retaining the scrollback of this page on the postback actions.</p>
|
[
{
"answer_id": 3717736,
"author": "Fede",
"author_id": 318583,
"author_profile": "https://Stackoverflow.com/users/318583",
"pm_score": 1,
"selected": false,
"text": "<f:view> \n <h:form>\n <h:commandLink actionListener=\"#{bean.method}\">\n <h:outputText value=\"Submit\" />\n <f:param name=\"anchor\" value=\"image\" />\n </h:commandLink>\n </h:form>\n <div id='result'>\n <h1><a name='image'>Image</a></h1> \n </div>\n</f:view>\n public class Bean {\n\n public void method(ActionEvent actionEvent) {\n\n // Get parameter\n String ancla = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(\"anchor\");\n\n try {\n FacesContext.getCurrentInstance().getExternalContext().redirect(\"page.jsf#\" + anchor);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n"
},
{
"answer_id": 23684416,
"author": "mehmet cinar",
"author_id": 1891090,
"author_profile": "https://Stackoverflow.com/users/1891090",
"pm_score": 0,
"selected": false,
"text": " $(function(){\n\n //set window scroll position if cookie is set\n window.scroll(0,getCookie('myCookie'));\n //unset cookie after setting scroll position\n deleteCookie('myCookie'); \n\n //make this class objects keep page scroll position\n jQuery(window).unload(function() {\n setCookie('myCookie', getPageScroll());\n });\n //-------------------\n\n\n\n });\n function setCookie(name,value) {\n\n var date = new Date();\n date.setTime(date.getTime()+(10*1000));\n var expires = \"; expires=\"+date.toGMTString();\n document.cookie = name+\"=\"+value+expires+\"; path=/\";\n}\n\nfunction getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n}\n\nfunction deleteCookie(name) {\n setCookie(name,\"\",-1);\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,770
|
<p>I want to detect whether module has changed. Now, using inotify is simple, you just need to know the directory you want to get notifications from.</p>
<p>How do I retrieve a module's path in python?</p>
|
[
{
"answer_id": 248066,
"author": "Cheery",
"author_id": 21711,
"author_profile": "https://Stackoverflow.com/users/21711",
"pm_score": 5,
"selected": false,
"text": "__file__ os.path.dirname(__file__)\n"
},
{
"answer_id": 248862,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 11,
"selected": true,
"text": "import a_module\nprint(a_module.__file__)\n import os\npath = os.path.abspath(a_module.__file__)\n path = os.path.dirname(a_module.__file__)\n"
},
{
"answer_id": 4431672,
"author": "vinoth",
"author_id": 540842,
"author_profile": "https://Stackoverflow.com/users/540842",
"pm_score": 4,
"selected": false,
"text": "import os\npath = os.path.abspath(__file__)\ndir_path = os.path.dirname(path)\n"
},
{
"answer_id": 6416114,
"author": "mcstrother",
"author_id": 222515,
"author_profile": "https://Stackoverflow.com/users/222515",
"pm_score": 6,
"selected": false,
"text": "__file__ __file__ __main__ #/path1/foo.py\nimport bar\nprint(bar.__file__)\n #/path2/bar.py\nimport os\nprint(os.getcwd())\nprint(__file__)\n /path1 # \"import bar\" causes the line \"print(os.getcwd())\" to run\n/path2/bar.py # then \"print(__file__)\" runs\n/path2/bar.py # then the import statement finishes and \"print(bar.__file__)\" runs\n /path2 # \"print(os.getcwd())\" still works fine\nTraceback (most recent call last): # but __file__ doesn't exist if bar.py is running as main\n File \"/path2/bar.py\", line 3, in <module>\n print(__file__)\nNameError: name '__file__' is not defined \n"
},
{
"answer_id": 9759993,
"author": "uri",
"author_id": 1277124,
"author_profile": "https://Stackoverflow.com/users/1277124",
"pm_score": 3,
"selected": false,
"text": "import os,sys\nif hasattr(sys,'frozen'): # only when running in py2exe this exists\n base = sys.prefix\nelse: # otherwise this is a regular python script\n base = os.path.dirname(os.path.realpath(__file__))\n"
},
{
"answer_id": 12154601,
"author": "Tomas Tomecek",
"author_id": 909579,
"author_profile": "https://Stackoverflow.com/users/909579",
"pm_score": 8,
"selected": false,
"text": "inspect >>> import os\n>>> import inspect\n>>> inspect.getfile(os)\n'/usr/lib64/python2.7/os.pyc'\n>>> inspect.getfile(inspect)\n'/usr/lib64/python2.7/inspect.pyc'\n>>> os.path.dirname(inspect.getfile(inspect))\n'/usr/lib64/python2.7'\n"
},
{
"answer_id": 16826913,
"author": "jpgeek",
"author_id": 454246,
"author_profile": "https://Stackoverflow.com/users/454246",
"pm_score": 6,
"selected": false,
"text": "__file__ import something\nsomething.__file__ \n #foo.py\nprint '__file__', __file__\n #!/usr/bin/python \n#foo.py\nprint '__file__', __file__\n python bar/foo.py\n bar/foo.py\n os.path.dirname(__file__) # foo.py\nimport os\nprint '__file__ is:', __file__\nprint 'os.path.dirname(__file__) is:', os.path.dirname(__file__)\n __file__ is: foo.py\nos.path.dirname(__file__) is: \n # foo.py\nimport os\nprint 'os.path.abspath(__file__) is:', os.path.abspath(__file__)\nprint 'os.path.dirname(os.path.abspath(__file__)) is:', os.path.dirname(os.path.abspath(__file__))\n os.path.abspath(__file__) is: /home/user/bar/foo.py\nos.path.dirname(os.path.abspath(__file__)) is: /home/user/bar\n import os\nprint 'abspath(__file__)',os.path.abspath(__file__)\nprint 'realpath(__file__)',os.path.realpath(__file__)\n abspath(__file__) /home/user/file_test_link\nrealpath(__file__) /home/user/file_test.py\n import os\nimport inspect\nprint 'inspect.getfile(os) is:', inspect.getfile(os)\n inspect.getfile(inspect.currentframe())\n inspect.getabsfile(inspect.currentframe()) \n"
},
{
"answer_id": 25319974,
"author": "MestreLion",
"author_id": 624066,
"author_profile": "https://Stackoverflow.com/users/624066",
"pm_score": 2,
"selected": false,
"text": "__file__ import os.path\nmydir = os.path.dirname(__file__) or '.'\nfull = os.path.abspath(mydir)\nprint __file__, mydir, full\n $ python teste.py \nteste.py . /home/user/work/teste\n or '.' dirname() . abspath() abspath()"
},
{
"answer_id": 25344804,
"author": "Lukas Greblikas",
"author_id": 1353644,
"author_profile": "https://Stackoverflow.com/users/1353644",
"pm_score": 4,
"selected": false,
"text": "import module\nprint module.__path__\n __path__ __init__.py"
},
{
"answer_id": 27934408,
"author": "Robin Randall",
"author_id": 2426712,
"author_profile": "https://Stackoverflow.com/users/2426712",
"pm_score": 1,
"selected": false,
"text": "global modpath\nmodname = 'os' #This can be any module name on the fly\n#Create a file called \"modname.py\"\nf=open(\"modname.py\",\"w\")\nf.write(\"import \"+modname+\"\\n\")\nf.write(\"modpath = \"+modname+\"\\n\")\nf.close()\n#Call the file with execfile()\nexecfile('modname.py')\nprint modpath\n<module 'os' from 'C:\\Python27\\lib\\os.pyc'>\n"
},
{
"answer_id": 28976381,
"author": "PlasmaBinturong",
"author_id": 4614641,
"author_profile": "https://Stackoverflow.com/users/4614641",
"pm_score": 6,
"selected": false,
"text": "import imp\nimp.find_module(\"os\")\n (<open file '/usr/lib/python2.7/os.py', mode 'U' at 0x7f44528d7540>,\n'/usr/lib/python2.7/os.py',\n('.py', 'U', 1))\n importlib importlib.util.find_spec"
},
{
"answer_id": 30192316,
"author": "Al Conrad",
"author_id": 3457624,
"author_profile": "https://Stackoverflow.com/users/3457624",
"pm_score": 1,
"selected": false,
"text": "some_dir/\n maincli.py\n top_package/\n __init__.py\n level_one_a/\n __init__.py\n my_lib_a.py\n level_two/\n __init__.py\n hello_world.py\n level_one_b/\n __init__.py\n my_lib_b.py\n import sys\nimport os\nimport imp\n\n\nclass ConfigurationException(Exception):\n pass\n\n\n# inside of my_lib_a.py\ndef get_maincli_path():\n maincli_path = os.path.abspath(imp.find_module('maincli')[1])\n # top_package = __package__.split('.')[0]\n # mod = sys.modules.get(top_package)\n # modfile = mod.__file__\n # pkg_in_dir = os.path.dirname(os.path.dirname(os.path.abspath(modfile)))\n # maincli_path = os.path.join(pkg_in_dir, 'maincli.py')\n\n if not os.path.exists(maincli_path):\n err_msg = 'This script expects that \"maincli.py\" be installed to the '\\\n 'same directory: \"{0}\"'.format(maincli_path)\n raise ConfigurationException(err_msg)\n\n return maincli_path\n"
},
{
"answer_id": 32026782,
"author": "Jossef Harush Kadouri",
"author_id": 3191896,
"author_profile": "https://Stackoverflow.com/users/3191896",
"pm_score": 4,
"selected": false,
"text": "python-which <package name>\n /usr/local/bin/python-which #!/usr/bin/env python\n\nimport importlib\nimport os\nimport sys\n\nargs = sys.argv[1:]\nif len(args) > 0:\n module = importlib.import_module(args[0])\n print os.path.dirname(module.__file__)\n sudo chmod +x /usr/local/bin/python-which\n"
},
{
"answer_id": 49968449,
"author": "Jeyekomon",
"author_id": 1232660,
"author_profile": "https://Stackoverflow.com/users/1232660",
"pm_score": 2,
"selected": false,
"text": "example.txt with open('example.txt', 'w'):\n pass\n os.getcwd() os.path.realpath('example.txt') sys.argv[0] __file__ example.txt filedir = os.path.dirname(os.path.realpath(__file__))\nfilepath = os.path.join(filedir, 'example.txt')\n\nwith open(filepath, 'w'):\n pass\n"
},
{
"answer_id": 52081355,
"author": "Hassan Ashraf",
"author_id": 10047846,
"author_profile": "https://Stackoverflow.com/users/10047846",
"pm_score": 3,
"selected": false,
"text": ">>> import os\n>>> os\n<module 'os' from 'C:\\\\Users\\\\Hassan Ashraf\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python36-32\\\\lib\\\\os.py'>\n>>>\n"
},
{
"answer_id": 52679374,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 3,
"selected": false,
"text": "from pathlib import Path\n\nprint(Path().absolute())\nprint(Path().resolve('.'))\nprint(Path().cwd())\n"
},
{
"answer_id": 55446232,
"author": "fr_andres",
"author_id": 4511978,
"author_profile": "https://Stackoverflow.com/users/4511978",
"pm_score": 3,
"selected": false,
"text": "from . import __path__ as ROOT_PATH\nprint(ROOT_PATH)\n __init__.py __file__"
},
{
"answer_id": 60005316,
"author": "Javi",
"author_id": 9033534,
"author_profile": "https://Stackoverflow.com/users/9033534",
"pm_score": 2,
"selected": false,
"text": "Name: detectron2\nVersion: 0.1\nSummary: Detectron2 is FAIR next-generation research platform for object detection and segmentation.\nHome-page: https://github.com/facebookresearch/detectron2\nAuthor: FAIR\nAuthor-email: None\nLicense: UNKNOWN\nLocation: /home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages\nRequires: yacs, tabulate, tqdm, pydot, tensorboard, Pillow, termcolor, future, cloudpickle, matplotlib, fvcore\n"
},
{
"answer_id": 60155768,
"author": "shrewmouse",
"author_id": 2464381,
"author_profile": "https://Stackoverflow.com/users/2464381",
"pm_score": 0,
"selected": false,
"text": "pushd #!/bin/bash\nmodule=${1:?\"I need a module name\"}\n\npython << EOI\nimport $module\nimport os\nprint os.path.dirname($module.__file__)\nEOI\n [root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)\n[root@sri-4625-0004 ~]# echo $LXML\n/usr/lib64/python2.7/site-packages/lxml\n[root@sri-4625-0004 ~]#\n"
},
{
"answer_id": 64800657,
"author": "tupui",
"author_id": 6522112,
"author_profile": "https://Stackoverflow.com/users/6522112",
"pm_score": 3,
"selected": false,
"text": "dir(a_module) a_module.__path__ >>> import a_module\n>>> print(dir(a_module))\n['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']\n>>> print(a_module.__path__)\n['/.../.../a_module']\n>>> print(a_module)\n<module 'a_module' from '/.../.../a_module/__init__.py'>\n"
},
{
"answer_id": 68976819,
"author": "wisbucky",
"author_id": 1081043,
"author_profile": "https://Stackoverflow.com/users/1081043",
"pm_score": -1,
"selected": false,
"text": "pip pip show python $ python -m pip show numpy\n$ python2.7 -m pip show numpy\n$ python3 -m pip show numpy\n\nLocation: /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python\n $ pip show numpy pip python"
},
{
"answer_id": 70630024,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 3,
"selected": false,
"text": "import importlib.util\n\nprint(importlib.util.find_spec(\"requests\").origin)\n /usr/lib64/python3.9/site-packages/requests/__init__.py\n"
},
{
"answer_id": 73374657,
"author": "zwithouta",
"author_id": 10680954,
"author_profile": "https://Stackoverflow.com/users/10680954",
"pm_score": 0,
"selected": false,
"text": "pandas pathlib from importlib import resources # part of core Python\nimport pandas as pd\n\npackage_dir = resources.path(package=pd, resource=\"\").__enter__()\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] |
247,772
|
<pre><code>a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}
</code></pre>
<p>Am I right to say that this is an array of size 3 where the key value pairs are <code>0->4</code>, <code>1->3</code>, and <code>2->2</code>?</p>
<p>If so, I find this representation awfully confusing. At first, I thought it was a listing of values (or the array contained <code>{0, 4, 1, 3, 2, 2}</code>), but I figured that the <code>a:3</code>: was the size of the array. And if <code>3</code> was the size, then both the keys and values appeared in the brackets with no way of clearly identifying a key/value pair without counting off.</p>
<p>To clarify where I'm coming from:</p>
<p>Why did the PHP developers choose to serialize in this manner? What advantage does this have over, let's say the way var_dump and/or var_export displays its data?</p>
|
[
{
"answer_id": 247788,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": false,
"text": "array(4, 3, 2) a i"
},
{
"answer_id": 247804,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 3,
"selected": true,
"text": "$string=\"a:3:{i:0;i:4;i:1;i:3;i:2;i:2;}\";\n$array=unserialize($string);\nprint_r($array);\n Array\n(\n [0] => 4\n [1] => 3\n [2] => 2\n)\n a:<<size>>:{<<keytype>>:<<key>>;<<valuetype>>:<<value>>;...}"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
247,779
|
<p>I have essentially a survey that is shown, and people answer questions a lot like a test,
and there are different paths, it is pretty easy so far, but i wanted to make it more dynamic, so that i can have a generic rule that is for the test with all the paths, to make the evaluator easier to work with currently i just allow AND's, and each OR essentially becomes another Rule in the set, </p>
<p>QuestionID, then i form a bunch of AND rules like so
<code><pre>
<rule id="1">
<true>
<question ID=123>
<question ID=124>
</true>
<false>
<question ID=127>
<question ID=128>
</false>
</rule>
<rule id="2"><true>
<question ID=123>
<question ID=125>
</true>
<false>
<question ID=127>
</false>
</rule>
</pre></code></p>
<p>this rule 1 says if question 123, and 124 are answered true, and 127, 128 are false, they pass. OR (rule 2) is if 123 and 125 are true and 127 is false, they pass as well.
This gets tedious if there are many combinations, so i want to implement OR in the logic, I am just not sure what best approach is for this problem.</p>
<p>I think rules engine is too complicated, there must be an easier way, perhaps constructing a graph like in LINQ and then evaluating to see if they pass, </p>
<p>thanks!</p>
<p>--not an compsci major.</p>
|
[
{
"answer_id": 248058,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 0,
"selected": false,
"text": "true false question choice choice <rule id=\"1\">\n <question id=\"123\" answer=\"true\" />\n <question id=\"124\" answer=\"false\" />\n <choice id=\"1\">\n <question id=\"125\" answer='true' />\n <choice id=\"2\">\n <question id=\"126\" answer='false' />\n <question id=\"127\" answer='false' />\n </choice>\n </choice>\n</rule>\n bool GetProvidedAnswer(int questionID) bool IsQuestionCorrect(XmlElement question) bool IsChoiceCorrect(XmlElement choice) bool IsRuleSatisfied(XmlElement rule) bool IsRuleSatisfied(XmlElement rule)\n {\n bool satisfied = true;\n foreach (XmlElement child in rule.SelectNodes(\"*\"))\n {\n if (child.Name == \"question\")\n {\n satisfied = satisfied && IsQuestionCorrect(child);\n }\n if (child.Name == \"choice\")\n {\n satisfed = satisfied && IsChoiceCorrect(child);\n }\n if (!satisfied)\n {\n return false;\n }\n }\n return true;\n}\n List<XmlElement> IsFooCorrect"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5111/"
] |
247,800
|
<p>I don't think this is possible, but if is then I need it :)</p>
<p>I have a auto-generated proxy file from the wsdl.exe command line tool by Visual Studio 2008.</p>
<p>The proxy output is partial classes. I want to override the default constructor that is generated. I would rather not modify the code since it is auto-generated.</p>
<p>I tried making another partial class and redefining the default constructor, but that doesn't work. I then tried using the override and new keywords, but that doesn't work.</p>
<p>I know I could inherit from the partial class, but that would mean I'd have to change all of our source code to point to the new parent class. I would rather not have to do this.</p>
<p>Any ideas, work arounds, or hacks? </p>
<pre><code>//Auto-generated class
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public MyWebService() {
string myString = "auto-generated constructor";
//other code...
}
}
}
//Manually created class in order to override the default constructor
namespace MyNamespace {
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {
public override MyWebService() { //this doesn't work
string myString = "overridden constructor";
//other code...
}
}
}
</code></pre>
|
[
{
"answer_id": 247808,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": -1,
"selected": false,
"text": "public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol \n{\n public override MyWebService(int dummy) \n { \n string myString = \"overridden constructor\";\n //other code...\n }\n}\n\n\nMyWebService mws = new MyWebService(0);\n"
},
{
"answer_id": 247814,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "public partial class MyClass{ \n\n public MyClass(){ \n ... normal construction goes here ...\n AfterCreated(); \n }\n\n public partial void OnCreated();\n}\n"
},
{
"answer_id": 2031936,
"author": "Tom Chantler",
"author_id": 234415,
"author_profile": "https://Stackoverflow.com/users/234415",
"pm_score": 6,
"selected": false,
"text": "partial void OnCreated()\n{\n // Do the extra stuff here;\n}\n"
},
{
"answer_id": 2569167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "//* AutogenCls.cs file\n//* Let say the file is auto-generated ==> it will be overridden each time when\n//* auto-generation will be triggered.\n//*\n//* Auto-generated class, let say via xsd.exe\n//*\npartial class AutogenCls\n{\n public AutogenCls(...)\n {\n }\n}\n\n\n\n//* AutogenCls_Cunstomization.cs file\n//* The file keeps customization code completely separated from \n//* auto-generated AutogenCls.cs file.\n//*\npartial class AutogenCls\n{\n //* The following line ensures execution at the construction time\n MyCustomization m_MyCustomizationInstance = new MyCustomization ();\n\n //* The following inner&private implementation class implements customization.\n class MyCustomization\n {\n MyCustomization ()\n {\n //* IMPLEMENT HERE WHATEVER YOU WANT TO EXECUTE DURING CONSTRUCTION TIME\n }\n }\n}\n"
},
{
"answer_id": 4562379,
"author": "nreyntje",
"author_id": 365989,
"author_profile": "https://Stackoverflow.com/users/365989",
"pm_score": 1,
"selected": false,
"text": "public partial class MyClass{ \n\n public MyClass(){ \n ... normal construction goes here ...\n OnCreated1(); \n OnCreated2(); \n ...\n }\n\n public partial void OnCreated1();\n public partial void OnCreated2();\n}\n // In MyClassMyAspect1.cs\npublic partial class MyClass{ \n\n public void MyClass_MyAspect2(){ \n ... normal construction goes here ...\n\n }\n\n}\n\n// In MyClassMyAspect2.cs\npublic partial class MyClass{ \n\n public void MyClass_MyAspect1(){ \n ... normal construction goes here ...\n }\n}\n\n// In MyClassConstructor.cs\npublic partial class MyClass : IDisposable { \n\n public MyClass(){ \n GetType().GetMethods().Where(x => x.Name.StartsWith(\"MyClass\"))\n .ForEach(x => x.Invoke(null));\n }\n\n public void Dispose() {\n GetType().GetMethods().Where(x => x.Name.StartsWith(\"DisposeMyClass\"))\n .ForEach(x => x.Invoke(null));\n }\n\n}\n"
},
{
"answer_id": 5076590,
"author": "Edward",
"author_id": 158675,
"author_profile": "https://Stackoverflow.com/users/158675",
"pm_score": 0,
"selected": false,
"text": "using System.Runtime.Serialization;\n\npartial class MyWebService\n{\n [OnDeserialized]\n public void OnDeserialized(StreamingContext context)\n {\n // your code here\n }\n}\n"
},
{
"answer_id": 7572035,
"author": "rrreee",
"author_id": 967448,
"author_profile": "https://Stackoverflow.com/users/967448",
"pm_score": 2,
"selected": false,
"text": "namespace MyNamespace {\n public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol {\n public MyWebService() {\n string myString = \"auto-generated constructor\";\n OtherCode();\n }\n }\n}\n\npartial void OtherCode();\n partial void OtherCode()\n{\n //do whatever extra stuff you wanted.\n}\n"
},
{
"answer_id": 9274766,
"author": "Shadi",
"author_id": 628592,
"author_profile": "https://Stackoverflow.com/users/628592",
"pm_score": 2,
"selected": false,
"text": "public SomeClass(int x) : this()\n{\n //Your extra initialization here\n}\n SomeClass objSomeClass = new SomeClass(0);\n"
},
{
"answer_id": 17152019,
"author": "Doctor Jones",
"author_id": 39277,
"author_profile": "https://Stackoverflow.com/users/39277",
"pm_score": 2,
"selected": false,
"text": "protected override WebRequest GetWebRequest(Uri uri)\n{\n //only perform the initialization once\n if (!hasBeenInitialized)\n {\n Initialize();\n }\n\n return base.GetWebRequest(uri);\n}\n\nbool hasBeenInitialized = false;\n\nprivate void Initialize()\n{\n //do your initialization here...\n\n hasBeenInitialized = true;\n}\n"
},
{
"answer_id": 57999465,
"author": "msulis",
"author_id": 9317,
"author_profile": "https://Stackoverflow.com/users/9317",
"pm_score": 0,
"selected": false,
"text": " [System.CodeDom.Compiler.GeneratedCode(\"EF.Reverse.POCO.Generator\", \"2.37.3.0\")]\n public partial class Library {\n public string City { get; set; }\n public Library() {\n InitializePartial();\n }\n partial void InitializePartial();\n }\n public partial class Library {\n List<Book> Books { get; set; }\n partial void InitializePartial() {\n Books = new List<Book>();\n }\n }\n\n public class Book {\n public string Title { get; set; }\n }\n"
},
{
"answer_id": 74291487,
"author": "l33t",
"author_id": 419761,
"author_profile": "https://Stackoverflow.com/users/419761",
"pm_score": 0,
"selected": false,
"text": "protected public var s1 = new MyWebService();\n\nvar s2 = (MyWebService?)Activator.CreateInstance(\n typeof(MyWebService),\n BindingFlags.CreateInstance | BindingFlags.Public);\n IoC DryIoc var service = container.Resolve<MyWebService>();\n // <auto-generated />\npublic partial class MyWebService\n{\n public MyWebService(object? dummyArgument = default)\n : this()\n {\n // Auto-generated constructor\n }\n}\n\n// Manually created\npublic partial class MyWebService\n{\n protected MyWebService()\n {\n }\n}\n enum"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4481/"
] |
247,807
|
<p>I have this doubt, I've searched the web and the answers seem to be diversified. Is it better to use mysql_pconnect over mysql_connect when connecting to a database via PHP? I read that pconnect scales much better, but on the other hand, being a persistent connection... having 10 000 connections at the same time, all persistent, doesn't seem scalable to me.</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 247944,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": true,
"text": "LAST_INSERT_ID()"
},
{
"answer_id": 21674339,
"author": "Phoenix",
"author_id": 3269543,
"author_profile": "https://Stackoverflow.com/users/3269543",
"pm_score": 2,
"selected": false,
"text": "mysql_connect() mysql_pconnect() mysql_pconnect() p mysql_connect() mysql_pconnect() mysql_close() mysql_pconnect() mysql_pconncet()"
},
{
"answer_id": 35620280,
"author": "Pritty M",
"author_id": 5938437,
"author_profile": "https://Stackoverflow.com/users/5938437",
"pm_score": 0,
"selected": false,
"text": "<?php $conn = mysql_connect(‘host’, ‘mysql_user’, ‘mysql_password’); if(!$conn){ die(‘Could not connect: ‘ . mysql_error()); } echo ‘Connected successfully’; mysql_close($conn); ?>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28388/"
] |
247,818
|
<p>Multimap essentially has groups of data sorted by the key. I want a method by which I could access these individual groups and get their aggregate values.
For example, in a <code>std::multimap< string, int ></code> I store </p>
<pre><code>{"Group1", 1},
{"Group1", 2},
{"Group1", 3},
{"Group2", 10},
{"Group2", 11},
{"Group2", 12}
</code></pre>
<p>Having stored these values, I should be able to iterate this multimap and get the aggregate values of each "group". Problem is there aren't any functions defined in STL to access MultiMaps in such a way. I could use <code>lower_bound</code>, <code>upper_bound</code> to manually iterate the multimap and total the group's contents, but I am hoping there could be better ways already defined in STL ? Can anyone propose a solution as to how I could get the aggregate values for a group in the above example.</p>
|
[
{
"answer_id": 247852,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 4,
"selected": false,
"text": "multimap::equal_range begin()"
},
{
"answer_id": 247859,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 6,
"selected": true,
"text": "pair<Iter, Iter> range = my_multimap.equal_range(\"Group1\");\nint total = accumulate(range.first, range.second, 0);\n template <typename Pair>\nstruct Less : public std::binary_function<Pair, Pair, bool>\n{\n bool operator()(const Pair &x, const Pair &y) const\n {\n return x.first < y.first;\n }\n};\n\nIter first = mmap.begin();\nIter last = adjacent_find(first, mmap.end(), Less<MultimapType::value_type>());\n"
},
{
"answer_id": 248009,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": -1,
"selected": false,
"text": "#include <iostream>\n#include <vector>\n#include <map>\n#include <string>\n#include <boost/assign/list_of.hpp>\n#include <boost/foreach.hpp>\nusing namespace std;\nusing namespace boost;\nusing namespace boost::assign;\n\nint main() {\n typedef map<string, vector<int> > collection;\n collection m;\n m[\"Group 1\"] = list_of(1)(2)(3);\n m[\"Group 2\"] = list_of(10)(11)(12);\n collection::iterator g2 = m.find(\"Group 2\");\n if (g2 != m.end()) {\n BOOST_FOREACH(int& i, g2->second) {\n cout << i << \"\\n\";\n }\n }\n}\n"
},
{
"answer_id": 249401,
"author": "Dean Michael",
"author_id": 11274,
"author_profile": "https://Stackoverflow.com/users/11274",
"pm_score": 1,
"selected": false,
"text": "template <class KeyType, class ValueType>\nstruct group_add {\n typedef map<KeyType, ValueType> map_type;\n map_type & aggregates;\n explicit group_add(map_type & aggregates_)\n : aggregates(aggregates_) { };\n void operator() (map_type::value_type const & element) {\n aggregates[element.first] += element.second;\n };\n};\n\ntemplate <class KeyType, class ValueType>\ngroup_add<KeyType, ValueType>\nmake_group_adder(map<KeyType, ValueType> & map_) {\n return group_add<KeyType, ValueType>(map_);\n};\n\n// ...\nmultimap<string, int> members;\n// populate members\nmap<string, int> group_aggregates;\nfor_each(members.begin(), members.end(),\n make_group_adder(group_aggregates));\n// group_aggregates now has the sums per group\n multimap<string, int> members;\nmap<string, int> group_aggregates;\nfor_each(members.begin(), members.end(),\n [&group_aggregates](multimap<string, int>::value_type const & element) {\n group_aggregates[element.first] += element.second;\n }\n );\n"
},
{
"answer_id": 1196243,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "// samekey.cpp -- Process groups with identical keys in a multimap\n\n#include <iostream>\n#include <string>\n#include <map>\nusing namespace std;\n\ntypedef multimap<string, int> StringToIntMap;\ntypedef StringToIntMap::iterator mapIter;\n\nint main ()\n{\n StringToIntMap mymap;\n\n mymap.insert(make_pair(\"Group2\", 11));\n mymap.insert(make_pair(\"Group1\", 3));\n mymap.insert(make_pair(\"Group2\", 10));\n mymap.insert(make_pair(\"Group1\", 1));\n mymap.insert(make_pair(\"Group2\", 12));\n mymap.insert(make_pair(\"Group1\", 2));\n\n cout << \"mymap contains:\" << endl;\n\n mapIter m_it, s_it;\n\n for (m_it = mymap.begin(); m_it != mymap.end(); m_it = s_it)\n {\n string theKey = (*m_it).first;\n\n cout << endl;\n cout << \" key = '\" << theKey << \"'\" << endl;\n\n pair<mapIter, mapIter> keyRange = mymap.equal_range(theKey);\n\n // Iterate over all map elements with key == theKey\n\n for (s_it = keyRange.first; s_it != keyRange.second; ++s_it)\n {\n cout << \" value = \" << (*s_it).second << endl;\n }\n }\n\n return 0;\n\n} // end main\n\n// end samekey.cpp\n"
},
{
"answer_id": 33490177,
"author": "Hayek.Yu",
"author_id": 2259906,
"author_profile": "https://Stackoverflow.com/users/2259906",
"pm_score": 0,
"selected": false,
"text": "equal_range\n #include <map>\npair<iterator, iterator> equal_range( const key_type& key );\n equal_range()"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32492/"
] |
247,819
|
<p>I have an application built in Flex Builder 3. It has a fair amount of mxml and as3 code which uses some other custom compenents. I have looked at the documentation on building components which shows how to make a simple mxml or action script component that extends something like a combobox, but I'm lost as to how to take a whole existing and independently functioning Application and turn it into a reusable component. </p>
<p>Basically, I'd just like to create multiple instances of this app inside of another flex project.</p>
<p>Anyone able to provide a little guidance?</p>
|
[
{
"answer_id": 248376,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 3,
"selected": true,
"text": "\n//Foo.mxml\n<mx:Appliction xmlns:mx=\"http://www.adobe.com/2006/mxml\">\n <mx:Label text = \"foo\" />\n</mx:Appliction>\n \n//Foo.mxml\n<mx:VBox>\n <mx:Label text = \"foo\" />\n</mx:VBox>\n \n//App.mxml\n<mx:Appliction \n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:local=\"your.package.scheme.*\"\n>\n <local:Foo />\n\n</mx:Appliction>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,833
|
<p>I have a Visual Basic .NET program which needs to open and close an Excel spreadsheet. Opening and reading the spreadsheet work fine, but trying to close the Excel 2007 application causes it to hang. It seems to close, but if you look in the task manager the application is still running. The code that I'm using to close it is</p>
<pre><code>wbkData.Close(saveChanges:=False)
appExcel.Quit()
wbkData = Nothing
appExcel = Nothing
</code></pre>
<p>How can I get Excel to close properly?</p>
|
[
{
"answer_id": 247841,
"author": "Eric Ness",
"author_id": 18891,
"author_profile": "https://Stackoverflow.com/users/18891",
"pm_score": 0,
"selected": false,
"text": "GC.Collect()\nGC.WaitForPendingFinalizers()\n\nwbkData.Close(SaveChanges:=False)\nSystem.Runtime.InteropServices.Marshal.FinalReleaseComObject(wbkData) : wbkData = Nothing\nappExcel.Quit()\nSystem.Runtime.InteropServices.Marshal.FinalReleaseComObject(appExcel) : appExcel = Nothing\n"
},
{
"answer_id": 248040,
"author": "hearn",
"author_id": 30096,
"author_profile": "https://Stackoverflow.com/users/30096",
"pm_score": 3,
"selected": false,
"text": "//FAIL\n\nWorkbook wkBook = xlApp.Workbooks.Open(@\"C:\\mybook.xls\");\n //WIN\n\nWorksheets sheets = xlApp.Worksheets;\nWorksheet sheet = sheets.Open(@\"C:\\mybook.xls\");\n...\nMarshal.ReleaseComObject(sheets);\nMarshal.ReleaseComObject(sheet);\n //force kill any excel processes over one minute old.\ntry\n{\n Process[] procs = Process.GetProcessesByName(\"EXCEL\");\n foreach (Process p in procs)\n {\n if (p.StartTime.AddMinutes(1) < DateTime.Now)\n {\n p.Kill(); \n } \n } \n}\ncatch (Exception)\n{} \n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18891/"
] |
247,834
|
<p>The scriptaculous wiki has a demo (<a href="http://github.com/madrobby/scriptaculous/wikis/effect-slidedown" rel="nofollow noreferrer">http://github.com/madrobby/scriptaculous/wikis/effect-slidedown</a>) that shows the SlideDown effect in use. However I need to have the same link to slide down if a certain DIV is hidden and SlideUp if that DIV is showing.</p>
<p>How do I achieve this?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 247845,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "function slideMe(myDiv) {\n\n if(Element.visible(myDiv)) {\n //slide up\n\n }\n\n else {\n\n //slide down\n\n }\n}\n"
},
{
"answer_id": 248012,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 4,
"selected": true,
"text": "Effect.toggle('element_id', 'slide');\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32495/"
] |
247,837
|
<p>I found a while ago (and I want to confirm again) that if you declare a class level variable, you should not call its constructor until the class constructor or load has been called. The reason was performance - but are there other reasons to do or not do this? Are there exceptions to this rule?</p>
<p><strong>ie: this is what I do based on what I think the best practice is:</strong></p>
<pre><code>public class SomeClass
{
private PersonObject _person;
public SomeClass()
{
_person = new PersonObject("Smitface");
}
}
</code></pre>
<p><strong>opposed to:</strong></p>
<pre><code>public class SomeClass
{
private PersonObject _person = new PersonObject("Smitface");
public SomeClass()
{
}
}
</code></pre>
|
[
{
"answer_id": 248803,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 2,
"selected": false,
"text": " public SomeClass(PersonObject person) \n\n { \n per = person; \n } \n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26685/"
] |
247,856
|
<pre><code>List<String> nameList = new List<String>();
DropDownList ddl = new DropDownList();
</code></pre>
<p>List is populated here, then sorted:</p>
<pre><code>nameList.Sort();
</code></pre>
<p>Now I need to drop it into the dropdownlist, which is where I'm having issues (using foreach):</p>
<pre><code>foreach (string name in nameList){
ddl.Items.Add(new ListItem(nameList[name].ToString()));
}
</code></pre>
<p>No workie - any suggestions? It's giving me compile errors:</p>
<pre><code>Error - The best overloaded method match for 'System.Collections.Generic.List<string>.this[int]' has some invalid arguments
Error - Argument '1': cannot convert from 'string' to 'int'
</code></pre>
|
[
{
"answer_id": 247865,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 5,
"selected": false,
"text": "DropDownList ddl = new DropDownList();\nddl.DataSource = nameList;\nddl.DataBind();\n"
},
{
"answer_id": 247868,
"author": "Mike Burton",
"author_id": 22225,
"author_profile": "https://Stackoverflow.com/users/22225",
"pm_score": 6,
"selected": true,
"text": " ddl.Items.Add(new ListItem(nameList[name].ToString()));\n ddl.Items.Add(new ListItem(name));\n"
},
{
"answer_id": 247870,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 0,
"selected": false,
"text": " foreach (string name in nameList){\n ddl.Items.Add(new ListItem(nameList[name].ToString()));\n }\n foreach (string name in nameList){\n ddl.Items.Add(new ListItem(name.ToString()));\n}\n"
},
{
"answer_id": 247871,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 1,
"selected": false,
"text": "foreach (string name in nameList)\n{\n ddl.Items.Add(new ListItem(name));\n}\n"
},
{
"answer_id": 247881,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 0,
"selected": false,
"text": "nameList List foreach (string name in nameList){\n ddl.Items.Add(name);\n}\n ddl.DataSource = nameList;\nddl.DataBind();\n"
},
{
"answer_id": 8542070,
"author": "Tom",
"author_id": 814886,
"author_profile": "https://Stackoverflow.com/users/814886",
"pm_score": 2,
"selected": false,
"text": "ddl.DataSource = nameList; \nddl.DataBind(); \n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
247,857
|
<p>I'm trying to think of a naming convention that accurately conveys what's going on within a class I'm designing. On a secondary note, I'm trying to decide between two almost-equivalent user APIs.</p>
<p>Here's the situation:</p>
<p>I'm building a scientific application, where one of the central data structures has three phases: 1) accumulation, 2) analysis, and 3) query execution.</p>
<p>In my case, it's a spatial modeling structure, internally using a KDTree to partition a collection of points in 3-dimensional space. Each point describes one or more attributes of the surrounding environment, with a certain level of confidence about the measurement itself.</p>
<p>After adding (a potentially large number of) measurements to the collection, the owner of the object will query it to obtain an interpolated measurement at a new data point somewhere within the applicable field.</p>
<p>The API will look something like this (the code is in Java, but that's not really important; the code is divided into three sections, for clarity):</p>
<pre><code>// SECTION 1:
// Create the aggregation object, and get the zillion objects to insert...
ContinuousScalarField field = new ContinuousScalarField();
Collection<Measurement> measurements = getMeasurementsFromSomewhere();
// SECTION 2:
// Add all of the zillion objects to the aggregation object...
// Each measurement contains its xyz location, the quantity being measured,
// and a numeric value for the measurement. For example, something like
// "68 degrees F, plus or minus 0.5, at point 1.23, 2.34, 3.45"
foreach (Measurement m : measurements) {
field.add(m);
}
// SECTION 3:
// Now the user wants to ask the model questions about the interpolated
// state of the model. For example, "what's the interpolated temperature
// at point (3, 4, 5)
Point3d p = new Point3d(3, 4, 5);
Measurement result = field.interpolateAt(p);
</code></pre>
<p>For my particular problem domain, it will be possible to perform a small amount of incremental work (partitioning the points into a balanced KDTree) during SECTION 2.</p>
<p>And there will be a small amount of work (performing some linear interpolations) that can occur during SECTION 3.</p>
<p>But there's a huge amount of work (constructing a kernel density estimator and performing a Fast Gauss Transform, using Taylor series and Hermite functions, but that's totally beside the point) that must be performed <strong>between</strong> sections 2 and 3.</p>
<p>Sometimes in the past, I've just used lazy-evaluation to construct the data structures (in this case, it'd be on the first invocation of the "interpolateAt" method), but then if the user calls the "field.add()" method again, I have to completely discard those data structures and start over from scratch.</p>
<p>In other projects, I've required the user to explicitly call an "object.flip()" method, to switch from "append mode" into "query mode". The nice this about a design like this is that the user has better control over the exact moment when the hard-core computation starts. But it can be a nuisance for the API consumer to keep track of the object's current mode. And besides, in the standard use case, the caller never adds another value to the collection after starting to issue queries; data-aggregation almost always fully precedes query preparation.</p>
<p>How have you guys handled designing a data structure like this?</p>
<p>Do you prefer to let an object lazily perform its heavy-duty analysis, throwing away the intermediate data structures when new data comes into the collection? Or do you require the programmer to explicitly flip the data structure from from append-mode into query-mode?</p>
<p>And do you know of any naming convention for objects like this? Is there a pattern I'm not thinking of?</p>
<hr>
<p>ON EDIT:</p>
<p>There seems to be some confusion and curiosity about the class I used in my example, named "ContinuousScalarField".</p>
<p>You can get a pretty good idea for what I'm talking about by reading these wikipedia pages:</p>
<ul>
<li><p><a href="http://en.wikipedia.org/wiki/Scalar_field" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Scalar_field</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Vector_field" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Vector_field</a></p></li>
</ul>
<p>Let's say you wanted to create a topographical map (this is not my exact problem, but it's conceptually very similar). So you take a thousand altitude measurements over an area of one square mile, but your survey equipment has a margin of error of plus-or-minus 10 meters in elevation.</p>
<p>Once you've gathered all the data points, you feed them into a model which not only interpolates the values, but also takes into account the error of each measurement.</p>
<p>To draw your topo map, you query the model for the elevation of each point where you want to draw a pixel.</p>
<p>As for the question of whether a single class should be responsible for both appending and handling queries, I'm not 100% sure, but I think so.</p>
<p>Here's a similar example: HashMap and TreeMap classes allow objects to be both added and queried. There aren't separate interfaces for adding and querying.</p>
<p>Both classes are also similar to my example, because the internal data structures have to be maintained on an ongoing basis in order to support the query mechanism. The HashMap class has to periodically allocate new memory, re-hash all objects, and move objects from the old memory to the new memory. A TreeMap has to continually maintain tree balance, using the red-black-tree data structure.</p>
<p>The only difference is that my class will perform optimally if it can perform all of its calculations once it knows the data set is closed.</p>
|
[
{
"answer_id": 247891,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "IInterpolator interpolator = field.GetInterpolator();\nMeasurement measurement = Interpolator.InterpolateAt(...);\n"
},
{
"answer_id": 247973,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "flip public void interpolateAt( Point3d p );\npublic Measurement interpolatedMasurement();\n"
},
{
"answer_id": 247985,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": true,
"text": "void flip() Interpolator interpolator() interpolateAt Measurement Point Key[] data = new Key[...];\ndata[idx++] = new Key(...); /* Fast! */\n...\nArrays.sort(data); /* Slow! */\n...\nboolean contains = Arrays.binarySearch(data, datum) >= 0; /* Fast! */\n Set"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22979/"
] |
247,858
|
<p>In T-SQL, you can do this:</p>
<pre><code>SELECT ProductId, COALESCE(Price, 0)
FROM Products
</code></pre>
<p>How do you do the same thing in Access SQL? I see examples for doing it with Nz in VBA, but I'm looking for the SQL equivalent.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 247869,
"author": "pipTheGeek",
"author_id": 28552,
"author_profile": "https://Stackoverflow.com/users/28552",
"pm_score": 6,
"selected": true,
"text": "Nz Nz ISNULL COALESCE"
},
{
"answer_id": 247872,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "\"Price = IIf([Price] Is Null,0,[Price])\"\n"
},
{
"answer_id": 247880,
"author": "Nathan DeWitt",
"author_id": 1753,
"author_profile": "https://Stackoverflow.com/users/1753",
"pm_score": 3,
"selected": false,
"text": "SELECT ProductId, Nz(Price, 0)\nFROM Products\n"
},
{
"answer_id": 23369347,
"author": "Art Mendenhall",
"author_id": 3585999,
"author_profile": "https://Stackoverflow.com/users/3585999",
"pm_score": 1,
"selected": false,
"text": "IsNull() Nz() CCur() Nz([Price], CCur(0)) CCur()"
},
{
"answer_id": 40508353,
"author": "iDevlop",
"author_id": 78522,
"author_profile": "https://Stackoverflow.com/users/78522",
"pm_score": 3,
"selected": false,
"text": "Iif(Price is null, 0, Price) Coalesce() Iif() Nz() Function Coalesce(ParamArray varValues()) As Variant\n'returns the first non null value, similar to SQL Server Coalesce() function\n'Patrick Honorez --- www.idevlop.com\n Dim i As Long\n Coalesce = Null\n For i = LBound(varValues) To UBound(varValues)\n If Not IsNull(varValues(i)) Then\n Coalesce = varValues(i)\n Exit Function\n End If\n Next\nEnd Function\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1753/"
] |
247,873
|
<p>Am I correct to say the difference between a signed and unsigned integer is:</p>
<ol>
<li>Unsigned can hold a larger positive value and no negative value.</li>
<li>Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative.</li>
<li>Signed integers can hold both positive and negative numbers.</li>
</ol>
<p>Any other differences?</p>
|
[
{
"answer_id": 301285,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 7,
"selected": false,
"text": "ADD SUB JAE"
},
{
"answer_id": 4903173,
"author": "Matthew",
"author_id": 19343,
"author_profile": "https://Stackoverflow.com/users/19343",
"pm_score": 2,
"selected": false,
"text": "unsigned int ui = -1;\nsigned int si = -1;\n\nif (ui < 0) {\n printf(\"unsigned < 0\\n\");\n}\nif (si < 0) {\n printf(\"signed < 0\\n\");\n}\nif (ui == si) {\n printf(\"%d == %d\\n\", ui, si);\n printf(\"%ud == %ud\\n\", ui, si);\n}\n signed < 0\n-1 == -1\n4294967295d == 4294967295d\n"
},
{
"answer_id": 5828922,
"author": "Mike Gleen",
"author_id": 243223,
"author_profile": "https://Stackoverflow.com/users/243223",
"pm_score": 3,
"selected": false,
"text": "i = ((int) b[j]) << 8 | b[j+1]\n i = (((int) b[i]) & 0xFF) << 8 | ((int) b[i+1]) & 0xFF\n"
},
{
"answer_id": 23304179,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "a b a+=b a a int v uint32_t 4,294,967,294 v*=v; v=4 int v*=v;"
},
{
"answer_id": 35025939,
"author": "Ying Xiong",
"author_id": 5534846,
"author_profile": "https://Stackoverflow.com/users/5534846",
"pm_score": 4,
"selected": false,
"text": "0 255 -128 127"
},
{
"answer_id": 71537706,
"author": "hl037_",
"author_id": 1745291,
"author_profile": "https://Stackoverflow.com/users/1745291",
"pm_score": 0,
"selected": false,
"text": "a-b a+(-b) add(a, add(swap(b), 1))) < ((signed) -1) < 5 ((unsigned) -1) > 5"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,875
|
<p>When is memory allocated in the .NET compact framework? If there is a difference between value and reference types, please detail. Documentation or steps to confirm are appreciated.</p>
<p>In particular, consider this scenario...</p>
<pre><code>private MyClass item; // here?
public void MyMethod()
{
item = new MyClass(); // or here?
}
</code></pre>
|
[
{
"answer_id": 247898,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 4,
"selected": true,
"text": "private MyClass item; // here?\n public void MyMethod()\n{\n item = new MyClass(); // or here?\n}\n"
},
{
"answer_id": 247926,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 1,
"selected": false,
"text": "null"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3619/"
] |
247,888
|
<p>We've got VisualSVN Server set up as our Subversion server on Windows, and we use Ankhsvn + TortoiseSVN as clients on our workstations.</p>
<p>How can you configure the server to require commit messages to be non-empty?</p>
|
[
{
"answer_id": 247916,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 6,
"selected": true,
"text": "VisualSVNServerHooks.exe check-logmessage VisualSVNServerHooks.exe start-commit pre-commit post-commit pre-revprop-change post-revprop-change pre-commit"
},
{
"answer_id": 249619,
"author": "Ansgar",
"author_id": 20319,
"author_profile": "https://Stackoverflow.com/users/20319",
"pm_score": 2,
"selected": false,
"text": "SVNLOOK.exe log -t \"%2\" \"%1\" | grep.exe \"[a-zA-Z0-9]\" > nul || GOTO ERROR\nGOTO OK\n:ERROR\nECHO \"Please enter comment and then retry commit!\"\nexit 1\n:OK\nexit 0 \n"
},
{
"answer_id": 381079,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 2,
"selected": false,
"text": "tsvn:logminsize"
},
{
"answer_id": 570764,
"author": "gbjbaanb",
"author_id": 13744,
"author_profile": "https://Stackoverflow.com/users/13744",
"pm_score": 2,
"selected": false,
"text": "svnlook log -t \"%2\" \"%1\" | c:\\tools\\grep -c \"[a-zA-z0-9]\" > nul\nif %ERRORLEVEL% NEQ 1 exit 0\n\necho Please enter a check-in comment 1>&2\nexit 1\n"
},
{
"answer_id": 1228108,
"author": "JBRWilkinson",
"author_id": 102345,
"author_profile": "https://Stackoverflow.com/users/102345",
"pm_score": 2,
"selected": false,
"text": "%SystemRoot%\\System32\\CScript.exe //nologo <..path..to..script> %1 %2\n if (WScript.Arguments.Length < 2)\n{\n WScript.StdErr.WriteLine(\"Repository Hook Error: Missing parameters. Should be REPOS_PATH then TXN_NAME, e.g. %1 %2 in pre-commit hook\");\n WScript.Quit(-1);\n}\n\nvar oShell = new ActiveXObject(\"WScript.Shell\");\nvar oFSO = new ActiveXObject(\"Scripting.FileSystemObject\");\n\nvar preCommitStdOut = oShell.ExpandEnvironmentStrings(\"%TEMP%\\\\PRE-COMMIT.\" + WScript.Arguments(1) + \".stdout\");\nvar preCommitStdErr = oShell.ExpandEnvironmentStrings(\"%TEMP%\\\\PRE-COMMIT.\" + WScript.Arguments(1) + \".stderr\");\n\nvar commandLine = \"%COMSPEC% /C \\\"C:\\\\Program Files\\\\VisualSVN Server\\\\bin\\\\SVNLook.exe\\\" log -t \";\n\ncommandLine += WScript.Arguments(1);\ncommandLine += \" \";\ncommandLine += WScript.Arguments(0);\ncommandLine += \"> \" + preCommitStdOut + \" 2> \" + preCommitStdErr;\n\n\n// Run Synchronously, don't show a window\n// WScript.Echo(\"About to run: \" + commandLine);\nvar exitCode = oShell.Run(commandLine, 0, true);\n\nvar fsOUT = oFSO.GetFile(preCommitStdOut).OpenAsTextStream(1);\nvar fsERR = oFSO.GetFile(preCommitStdErr).OpenAsTextStream(1);\n\nvar stdout = fsOUT && !fsOUT.AtEndOfStream ? fsOUT.ReadAll() : \"\";\nvar stderr = fsERR && !fsERR.AtEndOfStream ? fsERR.ReadAll() : \"\";\n\nif (stderr.length > 0)\n{\n WScript.StdErr.WriteLine(\"Error with SVNLook: \" + stderr);\n WScript.Quit(-2);\n}\n\n// To catch naught commiters who write 'blah' as their commit message\n\nif (stdout.length < 5)\n{\n WScript.StdErr.WriteLine(\"Please provide a commit message that describes why you've made these changes.\");\n WScript.Quit(-3);\n}\n\nWScript.Quit(0);\n"
},
{
"answer_id": 1266462,
"author": "sylvanaar",
"author_id": 151501,
"author_profile": "https://Stackoverflow.com/users/151501",
"pm_score": 6,
"selected": false,
"text": "setlocal enabledelayedexpansion\n\nset REPOS=%1\nset TXN=%2\n\nset SVNLOOK=\"%VISUALSVN_SERVER%\\bin\\svnlook.exe\"\n\nSET M=\n\nREM Concatenate all the lines in the commit message\nFOR /F \"usebackq delims==\" %%g IN (`%SVNLOOK% log -t %TXN% %REPOS%`) DO SET M=!M!%%g\n\nREM Make sure M is defined\nSET M=0%M%\n\nREM Here the 6 is the length we require\nIF NOT \"%M:~6,1%\"==\"\" goto NORMAL_EXIT\n\n:ERROR_TOO_SHORT\necho \"Commit note must be at least 6 letters\" >&2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1\n\nREM All checks passed, so allow the commit.\n:NORMAL_EXIT\nexit 0\n"
},
{
"answer_id": 11560554,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 3,
"selected": false,
"text": "pre-commit.bat pre-commit.ps1 hooks C:\\Repositories\\repository\\hooks\\ # Store hook arguments into variables with mnemonic names\n$repos = $args[0]\n$txn = $args[1]\n\n# Build path to svnlook.exe\n$svnlook = \"$env:VISUALSVN_SERVER\\bin\\svnlook.exe\"\n\n# Get the commit log message\n$log = (&\"$svnlook\" log -t $txn $repos)\n\n# Check the log message contains non-empty string\n$datalines = ($log | where {$_.trim() -ne \"\"})\nif ($datalines.length -lt 25)\n{\n # Log message is empty. Show the error.\n [Console]::Error.WriteLine(\"Commit with empty log message is prohibited.\")\n exit 3\n}\n\nexit 0\n @echo off\nset PWSH=%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\n%PWSH% -command $input ^| %1\\hooks\\pre-commit.ps1 %1 %2\nif errorlevel 1 exit %errorlevel%\n pre-commit.bat pre-commit.ps1 pre-commit.bat pre-commit.bat pre-commit.cmd [Console]::Error.WriteLine chcp 1252 pre-commit.bat @echo off"
},
{
"answer_id": 12848845,
"author": "mattmc3",
"author_id": 83144,
"author_profile": "https://Stackoverflow.com/users/83144",
"pm_score": 2,
"selected": false,
"text": "// run from pre-commit.cmd like so:\n// css.exe /nl /c C:\\SVN\\Scripts\\PreCommit.cs %1 %2\nusing System;\nusing System.Diagnostics;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Linq;\n\nclass PreCommitCS {\n\n /// <summary>Controls the procedure flow of this script</summary>\n public static int Main(string[] args) {\n if (args.Length < 2) {\n Console.WriteLine(\"usage: PreCommit.cs repository-path svn-transaction\");\n Environment.Exit(2);\n }\n\n try {\n var proc = new PreCommitCS(args[0], args[1]);\n proc.RunChecks();\n if (proc.MessageBuffer.ToString().Length > 0) {\n throw new CommitException(String.Format(\"Pre-commit hook violation\\r\\n{0}\", proc.MessageBuffer.ToString()));\n }\n }\n catch (CommitException ex) {\n Console.WriteLine(ex.Message);\n Console.Error.WriteLine(ex.Message);\n throw ex;\n }\n catch (Exception ex) {\n var message = String.Format(\"SCRIPT ERROR! : {1}{0}{2}\", \"\\r\\n\", ex.Message, ex.StackTrace.ToString());\n Console.WriteLine(message);\n Console.Error.WriteLine(message);\n throw ex;\n }\n\n // return success if we didn't throw\n return 0;\n }\n\n public string RepoPath { get; set; }\n public string SvnTx { get; set; }\n public StringBuilder MessageBuffer { get; set; }\n\n /// <summary>Constructor</summary>\n public PreCommitCS(string repoPath, string svnTx) {\n this.RepoPath = repoPath;\n this.SvnTx = svnTx;\n this.MessageBuffer = new StringBuilder();\n }\n\n /// <summary>Main logic controller</summary>\n public void RunChecks() {\n CheckCommitMessageLength(10);\n\n // Uncomment for indent checks\n /*\n string[] changedFiles = GetCommitFiles(\n new string[] { \"A\", \"U\" },\n new string[] { \"*.cs\", \"*.vb\", \"*.xml\", \"*.config\", \"*.vbhtml\", \"*.cshtml\", \"*.as?x\" },\n new string[] { \"*.designer.*\", \"*.generated.*\" }\n );\n EnsureTabIndents(changedFiles);\n */\n\n CheckForIllegalFileCommits(new string[] {\"*.suo\", \"*.user\"});\n }\n\n private void CheckForIllegalFileCommits(string[] filesToExclude) {\n string[] illegalFiles = GetCommitFiles(\n new string[] { \"A\", \"U\" },\n filesToExclude,\n new string[] {}\n );\n if (illegalFiles.Length > 0) {\n Echo(String.Format(\"You cannot commit the following files: {0}\", String.Join(\",\", illegalFiles)));\n }\n }\n\n private void EnsureTabIndents(string[] filesToCheck) {\n foreach (string fileName in filesToCheck) {\n string contents = GetFileContents(fileName);\n string[] lines = contents.Replace(\"\\r\\n\", \"\\n\").Replace(\"\\r\", \"\\n\").Split(new string[] { \"\\n\" }, StringSplitOptions.None);\n var linesWithSpaceIndents =\n Enumerable.Range(0, lines.Length)\n .Where(i => lines[i].StartsWith(\" \"))\n .Select(i => i + 1)\n .Take(11)\n .ToList();\n if (linesWithSpaceIndents.Count > 0) {\n var message = String.Format(\"{0} has spaces for indents on line(s): {1}\", fileName, String.Join(\",\", linesWithSpaceIndents));\n if (linesWithSpaceIndents.Count > 10) message += \"...\";\n Echo(message);\n }\n }\n }\n\n private string GetFileContents(string fileName) {\n string args = GetSvnLookCommandArgs(\"cat\") + \" \\\"\" + fileName + \"\\\"\";\n string svnlookResults = ExecCmd(\"svnlook\", args);\n return svnlookResults;\n }\n\n private void CheckCommitMessageLength(int minLength) {\n string args = GetSvnLookCommandArgs(\"log\");\n string svnlookResults = ExecCmd(\"svnlook\", args);\n svnlookResults = (svnlookResults ?? \"\").Trim();\n if (svnlookResults.Length < minLength) {\n if (svnlookResults.Length > 0) {\n Echo(\"Your commit message was too short.\");\n }\n Echo(\"Please describe the changes you've made in a commit message in order to successfully commit. Include support ticket number if relevant.\");\n }\n }\n\n private string[] GetCommitFiles(string[] changedIds, string[] includedFiles, string[] exclusions) {\n string args = GetSvnLookCommandArgs(\"changed\");\n string svnlookResults = ExecCmd(\"svnlook\", args);\n string[] lines = svnlookResults.Split(new string[] { \"\\r\", \"\\n\" }, StringSplitOptions.RemoveEmptyEntries);\n var includedPatterns = (from a in includedFiles select ConvertWildcardPatternToRegex(a)).ToArray();\n var excludedPatterns = (from a in exclusions select ConvertWildcardPatternToRegex(a)).ToArray();\n var opts = RegexOptions.IgnoreCase;\n var results =\n from line in lines\n let fileName = line.Substring(1).Trim()\n let changeId = line.Substring(0, 1).ToUpper()\n where changedIds.Any(x => x.ToUpper() == changeId)\n && includedPatterns.Any(x => Regex.IsMatch(fileName, x, opts))\n && !excludedPatterns.Any(x => Regex.IsMatch(fileName, x, opts))\n select fileName;\n return results.ToArray();\n }\n\n private string GetSvnLookCommandArgs(string cmdType) {\n string args = String.Format(\"{0} -t {1} \\\"{2}\\\"\", cmdType, this.SvnTx, this.RepoPath);\n return args;\n }\n\n /// <summary>\n /// Executes a command line call and returns the output from stdout.\n /// Raises an error is stderr has any output.\n /// </summary>\n private string ExecCmd(string command, string args) {\n Process proc = new Process();\n proc.StartInfo.FileName = command;\n proc.StartInfo.Arguments = args;\n proc.StartInfo.UseShellExecute = false;\n proc.StartInfo.CreateNoWindow = true;\n proc.StartInfo.RedirectStandardOutput = true;\n proc.StartInfo.RedirectStandardError = true;\n proc.Start();\n\n var stdOut = proc.StandardOutput.ReadToEnd();\n var stdErr = proc.StandardError.ReadToEnd();\n\n proc.WaitForExit(); // Do after ReadToEnd() call per: http://chrfalch.blogspot.com/2008/08/processwaitforexit-never-completes.html\n\n if (!string.IsNullOrWhiteSpace(stdErr)) {\n throw new Exception(string.Format(\"Error: {0}\", stdErr));\n }\n\n return stdOut;\n }\n\n /// <summary>\n /// Writes the string provided to the Message Buffer - this fails\n /// the commit and this message is presented to the comitter.\n /// </summary>\n private void Echo(object s) {\n this.MessageBuffer.AppendLine((s == null ? \"\" : s.ToString()));\n }\n\n /// <summary>\n /// Takes a wildcard pattern (like *.bat) and converts it to the equivalent RegEx pattern\n /// </summary>\n /// <param name=\"wildcardPattern\">The wildcard pattern to convert. Syntax similar to VB's Like operator with the addition of pipe (\"|\") delimited patterns.</param>\n /// <returns>A regex pattern that is equivalent to the wildcard pattern supplied</returns>\n private string ConvertWildcardPatternToRegex(string wildcardPattern) {\n if (string.IsNullOrEmpty(wildcardPattern)) return \"\";\n\n // Split on pipe\n string[] patternParts = wildcardPattern.Split('|');\n\n // Turn into regex pattern that will match the whole string with ^$\n StringBuilder patternBuilder = new StringBuilder();\n bool firstPass = true;\n patternBuilder.Append(\"^\");\n foreach (string part in patternParts) {\n string rePattern = Regex.Escape(part);\n\n // add support for ?, #, *, [...], and [!...]\n rePattern = rePattern.Replace(\"\\\\[!\", \"[^\");\n rePattern = rePattern.Replace(\"\\\\[\", \"[\");\n rePattern = rePattern.Replace(\"\\\\]\", \"]\");\n rePattern = rePattern.Replace(\"\\\\?\", \".\");\n rePattern = rePattern.Replace(\"\\\\*\", \".*\");\n rePattern = rePattern.Replace(\"\\\\#\", \"\\\\d\");\n\n if (firstPass) {\n firstPass = false;\n }\n else {\n patternBuilder.Append(\"|\");\n }\n patternBuilder.Append(\"(\");\n patternBuilder.Append(rePattern);\n patternBuilder.Append(\")\");\n }\n patternBuilder.Append(\"$\");\n\n string result = patternBuilder.ToString();\n if (!IsValidRegexPattern(result)) {\n throw new ArgumentException(string.Format(\"Invalid pattern: {0}\", wildcardPattern));\n }\n return result;\n }\n\n private bool IsValidRegexPattern(string pattern) {\n bool result = true;\n try {\n new Regex(pattern);\n }\n catch {\n result = false;\n }\n return result;\n }\n}\n\npublic class CommitException : Exception {\n public CommitException(string message) : base(message) {\n }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] |
247,901
|
<p>We have a production SQL Server 2005 database server with the production version of our application's database on it. I would like to be able to copy down the data contents of the production database to a development server for testing.</p>
<p>Several sites (and Microsoft's forums) suggest using the Backup/Restore options to copy databases from one server from another, but this solution is unworkable for several reasons (I don't have backup authority on our production database, I don't want to overwrite permissions on the development server, I don't want to overwrite structure changes on the development server, etc...)</p>
<p>I've tried using the SQL Import/Export Wizard in SQL Server 2005, but it always reports primary key violations. How can I copy the contents of a database from the production server to development without using the "Backup/Restore" method?</p>
|
[
{
"answer_id": 248078,
"author": "Richard Harrison",
"author_id": 19624,
"author_profile": "https://Stackoverflow.com/users/19624",
"pm_score": 2,
"selected": false,
"text": "DELETE FROM devserv.dbo.tablename;\nSET identity_insert [devserv.dbo.tablename] ON;\nINSERT into devserv.dbo.tablename SELECT * from prodserv.dbo.tablename;\nSET identity_insert [devname.dbo.tablename] OFF;\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21973/"
] |
247,909
|
<p>I have a lot of constants that are somehow related, at some point I need to pair them, something like this:</p>
<pre><code>const
key1 = '1';
key2 = '2';
key3 = '3';
value1 = 'a';
value2 = 'b';
value3 = 'c';
</code></pre>
<p>I want to avoid doing:</p>
<pre><code>if MyValue = key1 then Result := value1;
</code></pre>
<p>I know how to do it with string lists using:</p>
<pre><code>MyStringList.Add(key1 + '=' + value1);
Result := MyStringList.Values[key1];
</code></pre>
<p>But, is there any simpler way to do this?</p>
|
[
{
"answer_id": 247935,
"author": "Jozz",
"author_id": 12351,
"author_profile": "https://Stackoverflow.com/users/12351",
"pm_score": 4,
"selected": true,
"text": "MyStringList.Values[Key1] := Value1;\n"
},
{
"answer_id": 255070,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 0,
"selected": false,
"text": "type\n TKVEnum = (tKey, tValue); // You could give this a better name\nconst\n Count = 3;\n KeyValues: array [1..Count, TKVEnum] of string =\n // This is each of your name / value paris\n (('1', 'a'), ('2', 'b'), ('3', 'd')); \n if MyValue = KeyValues[1, TKVEnum.tKey] then \n Result := KeyValues[1, TKVEnum.tValue]\n type\n TConstPairs = (tcUsername, tcDatabase, tcEtcetera);\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
247,918
|
<p>I have two combos; provinces and cities.
I would like to change cities value when the province combo value changes. Here is my code</p>
<pre><code><div class="cities form">
<?php
$v = $ajax->remoteFunction(array('url' => '/cities/','update' => 'divcity'));
print $form-> input('Province.province_id', array('type' => 'select', 'options'=> $provinces, 'onChange' => $v));
?>
<div id="divcity">
<?php
echo $form->input('Cities.cities_name');
?>
</div>
</code></pre>
<p>Every time I change province combo, it call <code>cities/index.ctp</code>. anybody want to help?
really thank for your help
wawan</p>
|
[
{
"answer_id": 282684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<?php\n// In the view\n$v = $ajax->remoteFunction(array('url' => '/cities/list','update' => 'divcity'));\nprint $form-> input('Province.province_id', array('type' => 'select', 'options'=> $provinces, 'onChange' => $v));\n\n// In CitiesController\nfunction list($province_id = null) {\n // use $this->City->find('list', array('fields'=>array('City.id', 'City.name'))) \n // to generate a list of cities, based on the providence id if required\n if($this->RequestHandler->isAjax()) {\n $this->layout = 'ajax';\n $this->render();\n }\n} ?>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
247,922
|
<p>I have the following code in my Django application:</p>
<pre><code>if 'book' in authorForm.changed_data:
#Do something here...
</code></pre>
<p>I realize Django can tell me which values have changed in my form by utilizing the "changed_data" list object, but I'd like to know the new values of the fields that have changed.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 248200,
"author": "Alex Koshelev",
"author_id": 19772,
"author_profile": "https://Stackoverflow.com/users/19772",
"pm_score": 2,
"selected": false,
"text": "if authorForm.is_valid() and 'book' in authorForm.changed_data:\n new_value = authorForm.cleaned_data['book']\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10040/"
] |
247,928
|
<p>I have a PHP client that requests an XML file over HTTP (i.e. loads an XML file via URL). As of now, the XML file is only several KB in size. A problem I can foresee is that the XML becomes several MBs or Gbs in size. I know that this is a huge question and that there are probably a myriad of solutions, but What ideas do you have to transport this data to the client?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 247942,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 0,
"selected": false,
"text": "post_max_size upload_max_filesize"
},
{
"answer_id": 248765,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "**./test.sh &**"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24059/"
] |
247,929
|
<p>I have to connect my rails app in a legacy Postgre database. It uses schemas so in a SQL its is common to use something like </p>
<pre><code>SELECT * FROM "Financial".budget
</code></pre>
<p>I want to write a Budget model but I don't know how to set the table name in this case. I've tried the following:</p>
<ul>
<li>set_table_name 'budget'</li>
<li>set_table_name '"Financial".budget'</li>
</ul>
<p>None have worket.</p>
|
[
{
"answer_id": 248788,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 0,
"selected": false,
"text": "set_table_name \"Financial.budget\"\n"
},
{
"answer_id": 251151,
"author": "Patryk Kordylewski",
"author_id": 30927,
"author_profile": "https://Stackoverflow.com/users/30927",
"pm_score": 0,
"selected": false,
"text": "SET SEARCH_PATH TO \"Financial\", public;\n SELECT * FROM budget;\n"
},
{
"answer_id": 275162,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 2,
"selected": false,
"text": "set_table_name \"Financial.budget\"\n SELECT * FROM \"Financial.budget\"\n ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.class_eval do\n # abstract_adapter calls quote_column_name from quote_table_name, so prevent that\n def quote_table_name(name)\n name\n end\nend\n set_table_name \"Financial.budget\"\n SELECT * FROM Financial.budget\n"
},
{
"answer_id": 3239094,
"author": "Sam",
"author_id": 42059,
"author_profile": "https://Stackoverflow.com/users/42059",
"pm_score": 2,
"selected": false,
"text": "ActiveRecord::Base.establish_connection(\n :schema_search_path => 'Financial,public'\n)\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
247,936
|
<p>Lately I've been in the habit of assigning integer values to constants and simply using the constant name as a means of identifying its purpose. However, in some cases this has resulted in the need to write a function like typeToString($const) when a string representation is needed. Obviously this is inefficient and unneccesary, but is only an issue every once and a while.</p>
<p>So my question is, are there any other tradeoffs I should consider? Which case is considered to be cleaner/more standards-compliant? Also, is the performance difference negligable for most cases?</p>
<p><strong>Case 1: (faster when a string version is not needed?)</strong></p>
<pre><code>class Foo {
const USER_TYPE_ADMIN = 0;
const USER_TYPE_USER = 1;
const USER_TYPE_GUEST = 2;
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
public function typeToString() {
switch($this->userType) {
case self::USER_TYPE_ADMIN:
return 'admin';
break;
case self::USER_TYPE_USER:
return 'user';
break;
case self::USER_TYPE_GUEST:
return 'guest';
break;
default:
return 'unknown';
break;
}
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->typeToString();
// Displays "guest"
</code></pre>
<p><strong>Case 2:(faster/easier when a string version is needed)</strong></p>
<pre><code>class Foo {
const USER_TYPE_ADMIN = 'admin';
const USER_TYPE_USER = 'user';
const USER_TYPE_GUEST = 'guest';
public $userType = self::USER_TYPE_ADMIN;
public function __construct($type) {
$this->userType = $type;
}
}
$foo = new Foo(Foo::USER_TYPE_GUEST);
echo $foo->userType();
// Displays "guest"
</code></pre>
|
[
{
"answer_id": 247945,
"author": "Jasper Bekkers",
"author_id": 31486,
"author_profile": "https://Stackoverflow.com/users/31486",
"pm_score": 0,
"selected": false,
"text": "$foo = new Foo('guest');"
},
{
"answer_id": 247963,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "toString() $strings = array\n(\n self::USER_TYPE_ADMIN => 'admin',\n self::USER_TYPE_USER => 'user',\n);\n\nif (!isset($strings[$type]))\n return 'unknown';\n\nreturn $strings[$type];\n $strings static"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
247,946
|
<p>I have a .NET UserControl (FFX 3.5). This control contains several child Controls - a Panel, a couple Labels, a couple TextBoxes, and yet another custom Control. I want to handle a right click anywhere on the base Control - so a right click on any child control (or child of a child in the case of the Panel). I'd like to do it so that it's maintainable if someone makes changes to the Control without having to wire in handlers for new Controls for example.</p>
<p>First I tried overriding the WndProc, but as I suspected, I only get messages for clicks on the Form directly, not any of its children. As a semi-hack, I added the following after InitializeComponent:</p>
<pre><code> foreach (Control c in this.Controls)
{
c.MouseClick += new MouseEventHandler(
delegate(object sender, MouseEventArgs e)
{
// handle the click here
});
}
</code></pre>
<p>This now gets clicks for controls that support the event, but Labels, for example, still don't get anything. Is there a simple way to do this that I'm overlooking?</p>
|
[
{
"answer_id": 248017,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "void initControlsRecursive(ControlCollection coll)\n { \n foreach (Control c in coll) \n { \n c.MouseClick += (sender, e) => {/* handle the click here */}); \n initControlsRecursive(c.Controls);\n }\n }\n\n/* ... */\ninitControlsRecursive(Form.Controls);\n"
},
{
"answer_id": 38375366,
"author": "Szabolcs Antal",
"author_id": 2036220,
"author_profile": "https://Stackoverflow.com/users/2036220",
"pm_score": 1,
"selected": false,
"text": "public class MyClass : UserControl\n{\n public MyClass()\n {\n InitializeComponent();\n\n MouseClick += ControlOnMouseClick;\n if (HasChildren)\n AddOnMouseClickHandlerRecursive(Controls);\n }\n\n private void AddOnMouseClickHandlerRecursive(IEnumerable controls)\n {\n foreach (Control control in controls)\n {\n control.MouseClick += ControlOnMouseClick;\n\n if (control.HasChildren)\n AddOnMouseClickHandlerRecursive(control.Controls);\n }\n }\n\n private void ControlOnMouseClick(object sender, MouseEventArgs args)\n {\n if (args.Button != MouseButtons.Right)\n return;\n\n var contextMenu = new ContextMenu(new[] { new MenuItem(\"Copy\", OnCopyClick) });\n contextMenu.Show((Control)sender, new Point(args.X, args.Y));\n }\n\n private void OnCopyClick(object sender, EventArgs eventArgs)\n {\n MessageBox.Show(\"Copy menu item was clicked.\");\n }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13154/"
] |
247,948
|
<p>Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?</p>
<pre class="lang-ruby prettyprint-override"><code>if !my_string || my_string.length == 0
return true
else
return false
end
</code></pre>
<p>In C# there's the handy</p>
<pre class="lang-csharp prettyprint-override"><code>string.IsNullOrEmpty(myString)
</code></pre>
<p>Anything similar to that in Ruby?</p>
|
[
{
"answer_id": 247971,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "nil? if a_variable.nil?\n # the variable has a nil value\nend\n empty? if a_string.empty?\n # the string is empty\n}\n nil empty?"
},
{
"answer_id": 247981,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 4,
"selected": false,
"text": "nil? return my_string.nil? || my_string.empty?\n"
},
{
"answer_id": 248028,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 2,
"selected": false,
"text": "class String\n def self.nilorempty?(string)\n string.nil? || string.empty?\n end\nend\n String.nilorempty? mystring"
},
{
"answer_id": 248056,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 5,
"selected": false,
"text": "class NilClass\n def nil_or_empty?\n true\n end\nend\n\nclass String\n def nil_or_empty?\n empty?\n end\nend\n"
},
{
"answer_id": 248074,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "class NilClass\n def empty?; true; end\nend\n"
},
{
"answer_id": 248217,
"author": "Avdi",
"author_id": 20487,
"author_profile": "https://Stackoverflow.com/users/20487",
"pm_score": 6,
"selected": false,
"text": "#blank?"
},
{
"answer_id": 248265,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 5,
"selected": false,
"text": "class Object\n def blank?\n respond_to?(:empty?) ? empty? : !self\n end\nend\n"
},
{
"answer_id": 251644,
"author": "Ezran",
"author_id": 32883,
"author_profile": "https://Stackoverflow.com/users/32883",
"pm_score": 9,
"selected": true,
"text": "if my_string.to_s == ''\n # It's nil or empty\nend\n if my_string.to_s.strip.length == 0\n # It's nil, empty, or just whitespace\nend\n"
},
{
"answer_id": 9915384,
"author": "Vinay Sahni",
"author_id": 354789,
"author_profile": "https://Stackoverflow.com/users/354789",
"pm_score": 6,
"selected": false,
"text": "variable.to_s.empty?\n nil.to_s == \"\"\n\"\".to_s == \"\"\n"
},
{
"answer_id": 25396972,
"author": "Todd A. Jacobs",
"author_id": 1301972,
"author_profile": "https://Stackoverflow.com/users/1301972",
"pm_score": 2,
"selected": false,
"text": "my_string.to_s.empty? if defined? my_string\n my_string.to_s.empty? rescue NameError\n"
},
{
"answer_id": 49233410,
"author": "mahemoff",
"author_id": 18706,
"author_profile": "https://Stackoverflow.com/users/18706",
"pm_score": 2,
"selected": false,
"text": "(my_string||'').empty?"
},
{
"answer_id": 51532697,
"author": "snipsnipsnip",
"author_id": 188256,
"author_profile": "https://Stackoverflow.com/users/188256",
"pm_score": 0,
"selected": false,
"text": "if my_string=~/./\n p 'non-empty string'\nelse\n p 'nil or empty string'\nend\n if my_string&.size&.positive?\n # nonzero? also works\n p 'non-empty string'\nelse\n p 'nil or empty string'\nend\n"
},
{
"answer_id": 51595744,
"author": "Nondv",
"author_id": 3891844,
"author_profile": "https://Stackoverflow.com/users/3891844",
"pm_score": 0,
"selected": false,
"text": "#blank? nil.blank? # ==> true\n''.blank? # ==> true\n' '.blank? # ==> true\n'false'.blank? # ==> false\n"
},
{
"answer_id": 52274364,
"author": "RichOrElse",
"author_id": 6913691,
"author_profile": "https://Stackoverflow.com/users/6913691",
"pm_score": 1,
"selected": false,
"text": "module Nothingness\n refine String do\n alias_method :nothing?, :empty?\n end\n\n refine NilClass do\n alias_method :nothing?, :nil?\n end\nend\n\nusing Nothingness\n\nreturn my_string.nothing?\n"
},
{
"answer_id": 61100635,
"author": "Dhivya Dandapani",
"author_id": 4253388,
"author_profile": "https://Stackoverflow.com/users/4253388",
"pm_score": 2,
"selected": false,
"text": "#present? require 'rails'\n\nnil.present? # ==> false (Works on nil)\n''.present? # ==> false (Works on strings)\n' '.present? # ==> false (Works on blank strings)\n[].present? # ==> false(Works on arrays)\nfalse.present? # ==> false (Works on boolean)\n !present? !(nil.present?) # ==> true\n!(''.present?) # ==> true\n!(' '.present?) # ==> true\n!([].present?) # ==> true\n!(false.present?) # ==> true\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/650/"
] |
247,954
|
<p>I have a Tab Control with multiple Tab Pages. I want to be able to fade the tabs back and forth. I don't see an opacity option on the Tab Controls. Is there a way to cause a fade effect when I switch from one Tab Page to another?</p>
|
[
{
"answer_id": 257037,
"author": "Kevin W Lee",
"author_id": 26474,
"author_profile": "https://Stackoverflow.com/users/26474",
"pm_score": -1,
"selected": false,
"text": "<meta http-equiv=\"Page-Enter\" content=\"blendTrans(Duration=0)\">\n<meta http-equiv=\"Page-Exit\" content=\"blendTrans(Duration=0)\">\n"
},
{
"answer_id": 261140,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 0,
"selected": false,
"text": "ListView ControlTemplate"
},
{
"answer_id": 275394,
"author": "Matt",
"author_id": 19802,
"author_profile": "https://Stackoverflow.com/users/19802",
"pm_score": 2,
"selected": false,
"text": "using System.Drawing.Imaging;\nusing System.Drawing.Drawing2D;\n\npublic int alphablend;\npublic Bitmap myBitmap;\n\n private void button1_Click(object sender, EventArgs e)\n {\n alphablend = 0;\n pictureBox1.Visible = true;\n myBitmap = new Bitmap(tabControl1.Width, tabControl1.Height);\n while (alphablend <= 246)\n {\n tabControl1.DrawToBitmap(myBitmap, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));\n alphablend = alphablend + 10;\n pictureBox1.Refresh();//this calls the paint action\n }\n tabControl1.SelectTab(\"tabPage2\");\n while (alphablend >= 0)\n {\n tabControl1.DrawToBitmap(myBitmap, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));\n alphablend = alphablend - 10; \n pictureBox1.Refresh();//this calls the paint action\n }\n pictureBox1.Visible = false;\n }\n\n private void pictureBox1_Paint(object sender, PaintEventArgs e)\n {\n Graphics bitmapGraphics = Graphics.FromImage(myBitmap);\n\n SolidBrush greyBrush = new SolidBrush(Color.FromArgb(alphablend, 240, 240, 240));\n\n bitmapGraphics.CompositingMode = CompositingMode.SourceOver;\n\n bitmapGraphics.FillRectangle(greyBrush, new Rectangle(0, 0, tabControl1.Width, tabControl1.Height));\n\n e.Graphics.CompositingQuality = CompositingQuality.GammaCorrected;\n\n e.Graphics.DrawImage(myBitmap, 0, 0);\n\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19802/"
] |
247,961
|
<p>Exception: Failed to compare two elements in the array.</p>
<pre><code>private void assignNames(DropDownList ddl, Hashtable names)
{
List<ListItem> nameList = new List<ListItem>();
if (ddl != null)
{
ddl.ClearSelection();
ddl.Items.Add(new ListItem("Select Author"));
foreach (string key in names.Keys)
{
nameList.Add(new ListItem(names[key].ToString(), key));
}
nameList.Sort();
}
</code></pre>
<p>So how can I use Sort() to compare on the "names" and not get stuck on the key?</p>
|
[
{
"answer_id": 247983,
"author": "Marcus King",
"author_id": 19840,
"author_profile": "https://Stackoverflow.com/users/19840",
"pm_score": 1,
"selected": false,
"text": "List<string> auhtorNames;\nauthorNames.Sort();\nddl.DataSource = authorNames;\nddl.DataBind();\n"
},
{
"answer_id": 248008,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": true,
"text": "Comparison<T> List nameList.Sort(delegate(ListItem thisItem, ListItem otherItem) {\n return thisItem.Text.CompareTo(otherItem.Text);\n});\n null"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24565/"
] |
247,977
|
<p>I have this in some WSDL:</p>
<pre><code><element name="startDate" type="xsd:dateTime"/>
<element name="endDate" type="xsd:dateTime"/>
</code></pre>
<p>Which results in the following text in the SOAP envelope:</p>
<pre><code><startDate>2008-10-29T12:01:05</startDate>
<endDate>2008-10-29T12:38:59.65625-04:00</endDate>
</code></pre>
<p>Only some times have the milliseconds and zone offset. This causes me a headache because I'm trying to get a range of 37 minutes and 54 seconds in this example, but because of the offset I end up with 4 hours, 37 minutes, 54.65625 seconds. Is this some kind of rounding error in DateTime? How do I prevent this from happening?</p>
|
[
{
"answer_id": 248099,
"author": "Dan Finucane",
"author_id": 30026,
"author_profile": "https://Stackoverflow.com/users/30026",
"pm_score": 1,
"selected": false,
"text": "DateTime startDate = DateTime.Now;\nstring startDateString = System.Xml.XmlConvert.ToString(startDate);\n DateTime startDateFromXml = System.Xml.XmlConvert.ToDateTime(startDateString);\n"
},
{
"answer_id": 249547,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Unspecified)\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3275/"
] |
247,991
|
<p>I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.</p>
<p>This view would be included in another, non-Drupal site.</p>
<p>I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.</p>
|
[
{
"answer_id": 248044,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "// page.tpl.php\n<div id=\"page\"><?php print $content ?></div>\n theme_registry_alter() function modulejustforalteration_theme_registry_alter(&$variables) {\n if (isset($variables['views_ui_list_views']) ) {\n // not sure if that's the best index to test for \"views\" but i imagine it'll work\n // as well as others\n $variables['page']['template'] = 'override_page'; \n }\n}\n views_ui_list_views theme paths page template_preprocess_page()"
},
{
"answer_id": 248096,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 0,
"selected": false,
"text": "echo htmlspecialchars_decode($content);\n"
},
{
"answer_id": 248770,
"author": "Chris",
"author_id": 16960,
"author_profile": "https://Stackoverflow.com/users/16960",
"pm_score": 2,
"selected": false,
"text": "phptemplate_views_view_unformatted_VIEWNAME template.php NULL"
},
{
"answer_id": 609338,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "function phptemplate_preprocess_page(&$vars) {\n\n if ( isset($_GET['ajax']) && $_GET['ajax'] == 1 ) {\n $vars['template_file'] = 'page-ajax';\n }\n\n}\n <?php print $content; ?>\n"
},
{
"answer_id": 978817,
"author": "rinogo",
"author_id": 114558,
"author_profile": "https://Stackoverflow.com/users/114558",
"pm_score": 3,
"selected": false,
"text": "function mymodule_do_ajax($node)\n{\n $rval = <<<RVAL\n <table>\n <th>\n <td>Data</td>\n <td>Data</td>\n <td>Data</td>\n </th>\n <tr>\n <td>Cool</td>\n <td>Cool</td>\n <td>Cool</td>\n </tr>\n </table>\nRVAL;\n\n //return $rval; Nope! Will render via the templating engine.\n print $rval; //Much better. No wrapper.\n}\n"
},
{
"answer_id": 2065936,
"author": "nerdbabe",
"author_id": 250920,
"author_profile": "https://Stackoverflow.com/users/250920",
"pm_score": 1,
"selected": false,
"text": "page.tpl.php template.php function mytheme_preprocess_page(&$vars) {\n if ($vars['node'] && arg(2) != 'edit') {\n $vars['template_files'][] = 'page-nodetype-'. $vars['node']->type;\n }\n}\n page-nodetype-examplecontenttype.tpl.php page.tpl.php print $content"
},
{
"answer_id": 4924982,
"author": "Ufonion Labs",
"author_id": 606822,
"author_profile": "https://Stackoverflow.com/users/606822",
"pm_score": 2,
"selected": false,
"text": "function pixture_reloaded_preprocess_page(&$vars)\n{\n if ( isset($_GET['vlozeno']) && $_GET['vlozeno'] == 1 ) {\n $vars['theme_hook_suggestions'][] = 'page__vlozeno';\n } \n}\n <?php print render($page['content']); ?>\n"
},
{
"answer_id": 8396968,
"author": "jeroen",
"author_id": 306800,
"author_profile": "https://Stackoverflow.com/users/306800",
"pm_score": 4,
"selected": false,
"text": "hook_preprocess_page hook_preprocess_html function MY_THEME_preprocess_page(&$variables) {\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'page__embed';\n }\n}\n\nfunction MY_THEME_preprocess_html(&$variables) {\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'html__embed';\n }\n}\n html--embed.tpl.php <?php print $page; ?>\n page--embed.tpl.php <?php print render($page['content']); ?>\n <div>"
},
{
"answer_id": 8823037,
"author": "Nabil Kadimi",
"author_id": 358906,
"author_profile": "https://Stackoverflow.com/users/358906",
"pm_score": 2,
"selected": false,
"text": "/**\n * Implementation of hook_menu.\n */\nfunction test_menu(){\n $items['test'] = array (\n /* [...] */ \n 'page callback' => 'test_callback',\n /* [...] */ \n );\n return $items;\n}\n\nfunction test_callback() {\n // echo or print whatever you want\n // embed views if you want\n // DO NOT RETURN A STRING\n return TRUE;\n} \n exit(); return TRUE;"
},
{
"answer_id": 11908461,
"author": "SwarmIntelligence",
"author_id": 1183175,
"author_profile": "https://Stackoverflow.com/users/1183175",
"pm_score": 3,
"selected": false,
"text": "<?php print $content; ?>\n function MY_MODULE_NAME_preprocess_page(&$vars) {\n if ( isset($_GET['raw']) && $_GET['raw'] == 1 ) {\n $vars['template_file'] = 'raw';\n }\n} \n function MY_MODULE_NAME_theme_registry_alter(&$theme_registry) {\n $modulepath = drupal_get_path('module','MY_MODULE_NAME');\n array_unshift($theme_registry['page']['theme paths'], $modulepath.'/templates');\n}\n"
},
{
"answer_id": 25518051,
"author": "Alan Bondarchuk",
"author_id": 3204244,
"author_profile": "https://Stackoverflow.com/users/3204244",
"pm_score": 0,
"selected": false,
"text": "$build = menu_execute_active_handler('user', FALSE);\nreturn render($build);\n"
},
{
"answer_id": 51628323,
"author": "Wilhelm Stoker",
"author_id": 10164474,
"author_profile": "https://Stackoverflow.com/users/10164474",
"pm_score": 0,
"selected": false,
"text": "MY_THEME function MY_THEME_preprocess_page(&$variables) { } if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n $variables['theme_hook_suggestions'][] = 'page__embed';\n}\n $vars $variables"
},
{
"answer_id": 51651047,
"author": "Wilhelm Stoker",
"author_id": 10164474,
"author_profile": "https://Stackoverflow.com/users/10164474",
"pm_score": 0,
"selected": false,
"text": "function MY_THEME_page_alter($page) {\n\n if (isset($_GET['response_type']) && $_GET['response_type'] == 'embed') {\n header_remove('X-Frame-Options');\n } \n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/247991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1902010/"
] |
248,011
|
<p><code>pre</code> tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?</p>
|
[
{
"answer_id": 248013,
"author": "adambox",
"author_id": 2462,
"author_profile": "https://Stackoverflow.com/users/2462",
"pm_score": 11,
"selected": true,
"text": "pre {\n white-space: pre-wrap; /* Since CSS 2.1 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n"
},
{
"answer_id": 248023,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 4,
"selected": false,
"text": "pre { white-space: normal; }\n pre { overflow: auto; }\n"
},
{
"answer_id": 248034,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 3,
"selected": false,
"text": "<pre style=\"white-space:normal;\">. \n"
},
{
"answer_id": 6008351,
"author": "ekerner",
"author_id": 233060,
"author_profile": "https://Stackoverflow.com/users/233060",
"pm_score": 4,
"selected": false,
"text": "<textarea style=\"font-family:monospace;\" onfocus=\"copyClipboard(this);\"><?=htmlspecialchars($codeBlock);?></textarea>\n code {\n background-color: #EEEEEE;\n font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;\n}\npre {\n background-color: #EEEEEE;\n font-family: Consolas,Menlo,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New,monospace,serif;\n margin-bottom: 10px;\n max-height: 600px;\n overflow: auto;\n padding: 5px;\n width: auto;\n}\n"
},
{
"answer_id": 6098078,
"author": "Richard McKechnie",
"author_id": 525185,
"author_profile": "https://Stackoverflow.com/users/525185",
"pm_score": 8,
"selected": false,
"text": "pre pre {\n white-space: pre-wrap;\n}\n"
},
{
"answer_id": 17420314,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "pre {\n white-space: normal;\n word-wrap: break-word;\n}\n"
},
{
"answer_id": 20618776,
"author": "Mason240",
"author_id": 615285,
"author_profile": "https://Stackoverflow.com/users/615285",
"pm_score": 6,
"selected": false,
"text": " <div style=\"white-space: pre-wrap;\">content</div>\n"
},
{
"answer_id": 21241578,
"author": "user1433454",
"author_id": 1433454,
"author_profile": "https://Stackoverflow.com/users/1433454",
"pm_score": 4,
"selected": false,
"text": "word-break: keep-all;\n"
},
{
"answer_id": 30299462,
"author": "rob_st",
"author_id": 1991146,
"author_profile": "https://Stackoverflow.com/users/1991146",
"pm_score": 2,
"selected": false,
"text": "<pre> <pre>"
},
{
"answer_id": 31466925,
"author": "feacco",
"author_id": 5035625,
"author_profile": "https://Stackoverflow.com/users/5035625",
"pm_score": 1,
"selected": false,
"text": "xmp{ white-space:pre-wrap; word-wrap:break-word; }\n <xmp> your text or code </xmp>\n"
},
{
"answer_id": 45783868,
"author": "vovahost",
"author_id": 1502079,
"author_profile": "https://Stackoverflow.com/users/1502079",
"pm_score": 5,
"selected": false,
"text": "<pre style=\"white-space: pre-wrap; word-break: keep-all;\">\n\n</pre>\n"
},
{
"answer_id": 52130554,
"author": "Erin Delacroix",
"author_id": 10302071,
"author_profile": "https://Stackoverflow.com/users/10302071",
"pm_score": 6,
"selected": false,
"text": "pre pre {\n white-space: pre-wrap;\n word-break: keep-all\n}\n"
},
{
"answer_id": 59185290,
"author": "Someone",
"author_id": 12260140,
"author_profile": "https://Stackoverflow.com/users/12260140",
"pm_score": 3,
"selected": false,
"text": "white-space: pre-wrap pre word-wrap: break-word"
},
{
"answer_id": 69546216,
"author": "Saleh Abdulaziz",
"author_id": 1895511,
"author_profile": "https://Stackoverflow.com/users/1895511",
"pm_score": 1,
"selected": false,
"text": "pre {\n overflow-x: auto !important;\n white-space: pre-wrap !important; /* Since CSS 2.1 */\n white-space: -moz-pre-wrap !important; /* Mozilla, since 1999 */\n white-space: -pre-wrap !important; /* Opera 4-6 */\n white-space: -o-pre-wrap !important; /* Opera 7 */\n word-wrap: break-word !important; /* Internet Explorer 5.5+ */\n}\n\ncode{\n white-space: normal !important;\n}\n"
},
{
"answer_id": 70455437,
"author": "pbies",
"author_id": 1701812,
"author_profile": "https://Stackoverflow.com/users/1701812",
"pm_score": 1,
"selected": false,
"text": "<pre> <code>"
},
{
"answer_id": 72023541,
"author": "Nima Habibollahi",
"author_id": 1935499,
"author_profile": "https://Stackoverflow.com/users/1935499",
"pm_score": 1,
"selected": false,
"text": "pre {\n white-space: pre-wrap; /* css-3 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
248,014
|
<p>We have always had languages that were preferable to be used in a particular scenario. For a quick prototype development, VB6 was an obvious choice. VB6 was chosen in projects that had a simple desktop user interface and standard and un-complicated database interaction requirements. If you wanted to develop a device driver using low-level routines, you probably relied on C or Visual C++. ASP was a standard choice for development of web interfaces. Every language had a particular 'domain' or 'specialization', speaking crudely.</p>
<p>With .NET framework, all languages are interoperable and presumably consistent. You can have a project with modules from different languages all together but all ultimately being treated fairly similarly (all get compiled to IL).</p>
<p>Does this mean that the distinction we had earlier no longer exists? That differentiation was not necessarily bad rather something that was there by design and not due to any constraint. That apparently is diminished somewhat with the .NET framework and its treatment of various languages.</p>
|
[
{
"answer_id": 248510,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 0,
"selected": false,
"text": "CLSCompliant"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065163/"
] |
248,018
|
<p>I have a GIF image that has an alpha set, and when my site loads in Firefox 3.0, it acts transparently on the parts of the image that should. However, when I try to load the GIF image in IE7, it comes back as a solid block. Actually, it is like the color from the image bled into the transparent area.</p>
<p>Do anyone have any suggestions for resolving this kind of problem? Pointers on what to look into, or a route you've used to solve this kind of problem.</p>
<p>I've been controlling this in CSS -- and while I'd like to avoid the conditional comments route and multiple CSSes, I'd be willing if the suggestion tangibly shows how I can resolve the IE compatibility problems.</p>
<p>Thanks,
Sean</p>
|
[
{
"answer_id": 248042,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "opacity: 7;\nfilter: alpha(Opacity=7);\n"
},
{
"answer_id": 248093,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 0,
"selected": false,
"text": "//margin-top: 46px;\n//background-color: #377696;\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13990/"
] |
248,031
|
<p>Hi I'm trying to get some practice with Linked Lists.</p>
<p>I Defined an Object class called <code>Student</code>:</p>
<pre><code>public class Student
{
protected string Student_Name;
protected int Student_ID;
protected int Student_Mark;
protected char Student_Grade;
public Student() // default Constructor
{
Student_Name = " ";
Student_ID = 0;
Student_Mark = 0;
Student_Grade = ' ';
}
public Student(string Sname, int Sid, int Smark, char Sgrade) // Constructor
{
int len = sname.Length;
Student_Name = sname.Substring(0, len);
//Student_Name = sname.Substring(0, sname.Length);
Student_ID = Sid;
Student_Mark = Smark;
Student_Grade = Sgrade;
}
}
</code></pre>
<p>and then a <code>Node</code> class:</p>
<pre><code>public class S_Node
{
public Student Element;
public S_Node Link;
public S_Node()
{
Element = new Student();
Link = null;
}
public Node(Student theElement)
{
Element = theElement;
Link = null;
}
}
</code></pre>
<p>and the <code>LinkedList</code>:</p>
<pre><code>public class S_LinkedList
{
protected S_Node header;
protected S_Node tail;
public S_LinkedList()
{
header = new S_Node();
Tail = new S_Node();
header.Link = Tail;
}
// METHODS which i don't know how to do it (never use linkedlist before)
}
</code></pre>
<p>I need to organize this data using a “linkedlist data structure type”.</p>
<p>Contain all methods of linkedlist as Adding nodes to the list as I've learned -->(Insert),Deleting nodes from the list,as I've learned -->((Remove),Traversing the lists I've learned -->((PrintList),Finding a node in the list as I've learned -->((Find , FindPrevious) the problem I'm selflearning and I've tried to search the net and read more from the stupid C# that was a disaster.
I've done too much that I'm so sad that i don't know how to complete it .</p>
<p>I'm trying hard to Use this classes to write an executable program and to Test it .</p>
<p>If you don't want to help in completing this program (hope not) at least show me some real examples or ideas , after all I'm a selflearner geek :-)</p>
|
[
{
"answer_id": 248105,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 2,
"selected": false,
"text": "public class S_LinkedList {\n\n protected S_Node header = null;\n\n protected S_Node tail = null;\n\n public S_LinkedList()\n {\n }\n\n // METHODS which i don't know how to do it (never use linkedlist before)\n void Insert(Student s)\n {\n if( header == null )\n {\n header = new S_Node(s);\n tail = header;\n }\n else\n {\n tail.Link = new S_Node(s);\n tail = tail.Link;\n }\n }\n}\n"
},
{
"answer_id": 248279,
"author": "Ryan Rodemoyer",
"author_id": 1444511,
"author_profile": "https://Stackoverflow.com/users/1444511",
"pm_score": 1,
"selected": false,
"text": "public class Student\n{\n protected string Name;\n protected int ID;\n protected int Mark;\n protected char Grade;\n\n public Student() // default Constructor\n {\n Name = \"\";\n ID = 0;\n Mark = 0;\n Grade = '';\n }\n\n public Student(string Name, int ID, int Mark, char Grade) // Constructor\n {\n this.Name = Name;\n this.ID = ID;\n this.Mark = Mark;\n this.Grade = Grade;\n }\n}\n"
},
{
"answer_id": 248899,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 5,
"selected": true,
"text": "// create a list of students and print them back out.\nStudentList list = new StudentList();\nlist.Add( new Student(\"Bob\", 1234, 2, 'A') );\nlist.Add( new Student(\"Mary\", 2345, 4, 'C') );\n\nforeach( Student student in list)\n{\n Console.WriteLine(student.Name);\n}\n public class StudentList \n{\n private ListNode _firstElement; // always need to keep track of the head.\n\n private class ListNode\n {\n public Student Element { get; set; }\n public ListNode Next { get; set; }\n }\n\n public void Add(Student student) { /* TODO */ }\n\n}\n public void Add(Student student)\n{\n if (student == null)\n throw new ArgumentNullException(\"student\");\n\n // create the new element\n ListNode insert = new ListNode() { Element = student };\n\n if( _firstElement == null )\n {\n _firstElement = insert;\n return;\n }\n\n ListNode current = _firstElement;\n while (current.Next != null)\n {\n current = current.Next;\n }\n\n current.Next = insert;\n}\n private ListNode _lastElement; // keep track of the last element: Adding is O(1) instead of O(n)\n\npublic void Add(Student student)\n{\n if( student == null )\n throw new ArgumentNullException(\"student\");\n\n // create the new element\n ListNode insert = new ListNode() { Element = student };\n\n if (_firstElement == null)\n {\n _firstElement = insert;\n _lastElement = insert;\n return;\n }\n\n // fix up Next reference\n ListNode last = _lastElement;\n last.Next = insert;\n _lastElement = insert;\n}\n foreach // don't add this to StudentList\nvoid IterateOverList( ListNode current )\n{\n while (current != null)\n {\n current = current.Next;\n }\n}\n // StudentList now implements IEnumerable<Student>\npublic class StudentList : IEnumerable<Student>\n{\n // previous code omitted\n\n #region IEnumerable<Student> Members\n public IEnumerator<Student> GetEnumerator()\n {\n ListNode current = _firstElement;\n\n while (current != null)\n {\n yield return current.Element;\n current = current.Next;\n }\n }\n #endregion\n\n #region IEnumerable Members\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n #endregion\n}\n yield _ public class Student\n{\n private string _name;\n private int _id;\n private int _mark;\n private char _letterGrade;\n\n private Student() // hide default Constructor\n { }\n\n public Student(string name, int id, int mark, char letterGrade) // Constructor\n {\n if( string.IsNullOrEmpty(name) )\n throw new ArgumentNullException(\"name\");\n if( id <= 0 )\n throw new ArgumentOutOfRangeException(\"id\");\n\n _name = name;\n _id = id;\n _mark = mark;\n _letterGrade = letterGrade;\n }\n // read-only properties - compressed to 1 line for SO answer.\n public string Name { get { return _name; } }\n public int Id { get { return _id; } }\n public int Mark { get { return _mark; } }\n public char LetterGrade { get { return _letterGrade; } }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31512/"
] |
248,046
|
<p>Oracle is giving me an error (ORA-00907: missing right parenthesis) when I run this query:</p>
<pre><code>select *
from reason_for_appointment
where reason_for_appointment_id in
(
select reason_for_appointment_id
from appointment_reason
where appointment_id = 11
order by appointment_reason_id
)
</code></pre>
<p>However, when I run just the subquery, there's no error.</p>
<p>Can anyone explain what the problem is?</p>
|
[
{
"answer_id": 248935,
"author": "darreljnz",
"author_id": 10538,
"author_profile": "https://Stackoverflow.com/users/10538",
"pm_score": 1,
"selected": false,
"text": "select reason_for_appointment.*\nfrom reason_for_appointment rfa, appointment_reason ar\nwhere rfa.reason_for_appointment_id = ar.reason_for_appointment_id\nand ar.appointment_id = 11\norder by ar.appointment_reason_id;\n"
},
{
"answer_id": 461986,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "select * from reason_for_appointment where reason_for_appointment_id in\n (select reason_for_appointment_id from appointment_reason where appointment_id = 11)\n order by reason_for_appointment_id\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
248,052
|
<p>I'm checking for existing of a row in in_fmd, and the ISBN I look up can be the ISBN parameter, or another ISBN in a cross-number table that may or may not have a row.</p>
<pre><code>select count(*)
from in_fmd i
where (description='GN')
and ( i.isbn in
(
select bwi_isbn from bw_isbn where orig_isbn = ?
union all
select cast(? as varchar) as isbn
)
)
</code></pre>
<p>I don't actually care about the count of the rows, but rather mere existence of at least one row.</p>
<p>This used to be three separate queries, and I squashed it into one, but I think there's room for more improvement. It's PostgreSQL 8.1, if it matters.</p>
|
[
{
"answer_id": 248071,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": true,
"text": "UNION ALL select count(*)\nfrom in_fmd i\nwhere (description='GN')\n and (\n i.isbn in (\n select bwi_isbn from bw_isbn where orig_isbn = ?\n )\n or i.isbn = cast(? as varchar)\n )\n LEFT JOIN IN select count(*)\nfrom in_fmd i\nleft join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\nwhere (i.description='GN')\n and (\n bw_isbn.bwi_isbn is not null\n or i.isbn = cast(? as varchar)\n )\n SELECT SUM(ct)\nFROM (\n select count(*) as ct\n from in_fmd i\n inner join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\n and i.isbn <> cast(? as varchar)\n and i.description = 'GN'\n\n UNION\n\n select count(*) as ct\n from in_fmd i\n where i.isbn = cast(? as varchar)\n and i.description = 'GN'\n) AS x\n"
},
{
"answer_id": 248075,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select count(*)\nfrom in_fmd i\nwhere description = 'GN'\n and exists (select 1 \n from bwi_isbn \n where bw_isbn.bwi_isbn = in_fmd.isbn)\n"
},
{
"answer_id": 248076,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 1,
"selected": false,
"text": "SELECT ... LIMIT 1"
},
{
"answer_id": 494618,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "SELECT SUM(ct)\nFROM (select count(*) as ct\n from in_fmd i\n inner join bw_isbn\n on bw_isbn.bwi_isbn = i.isbn\n and bw_isbn.orig_isbn = ?\n and i.isbn <> cast(? as varchar)\n and i.description = 'GN'\n UNION\n select count(*) as ct\n from in_fmd i\n where i.isbn = cast(? as varchar)\n and i.description = 'GN'\n ) AS x\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8454/"
] |
248,067
|
<p>The only method provided by the DNN framework to get a module by ID also required a tab ID. What can I do if I don't <em>have</em> a tab ID?</p>
|
[
{
"answer_id": 248068,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 4,
"selected": true,
"text": "new ModuleController().GetModule(moduleId, DotNetNuke.Common.Utilities.Null.NullInteger)\n"
},
{
"answer_id": 256004,
"author": "Rafe",
"author_id": 27497,
"author_profile": "https://Stackoverflow.com/users/27497",
"pm_score": -1,
"selected": false,
"text": "ALTER PROCEDURE [dbo].[dnn_GetModule]\n\n @ModuleId int,\n @TabId int\n\nAS\nSELECT * \nFROM dbo.dnn_vw_Modules\nWHERE ModuleId = @ModuleId\nAND (TabId = @TabId or @TabId is null)\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248067",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688/"
] |
248,072
|
<p>Evil or not evil?</p>
<pre><code>public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}
// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);
// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty);
</code></pre>
<p>Note that due to the nature of extension methods, MyButtonClicked.Raise will not throw a NullReferenceException if MyButtonClicked is null. (E.g. there are no listeners to MyButtonClicked event).</p>
<p>Evil or not?</p>
|
[
{
"answer_id": 248103,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 4,
"selected": false,
"text": "public event EventHandler<EventArgs> OnClicked = delegate { };\n"
},
{
"answer_id": 248110,
"author": "Greg D",
"author_id": 6932,
"author_profile": "https://Stackoverflow.com/users/6932",
"pm_score": 0,
"selected": false,
"text": "protected virtual OnSomeEvent(EventArgs e){ }\n"
},
{
"answer_id": 280688,
"author": "Squirrel",
"author_id": 11835,
"author_profile": "https://Stackoverflow.com/users/11835",
"pm_score": 3,
"selected": false,
"text": " public static void Raise(this EventHandler handler, object sender)\n {\n Raise(handler, sender, EventArgs.Empty);\n }\n\n public static void Raise<TA>(this EventHandler<TA> handler, object sender, TA args)\n where TA : EventArgs\n {\n if (handler != null)\n {\n handler(sender, args);\n }\n }\n"
},
{
"answer_id": 293414,
"author": "alvin",
"author_id": 15121,
"author_profile": "https://Stackoverflow.com/users/15121",
"pm_score": 3,
"selected": false,
"text": "[MethodImpl(MethodImplOptions.NoInlining)]"
},
{
"answer_id": 2288042,
"author": "Bob",
"author_id": 49548,
"author_profile": "https://Stackoverflow.com/users/49548",
"pm_score": 0,
"selected": false,
"text": "myEvent.Raise(this, new EventArgs()); if (myEvent!= null) {\n myEvent(this, new EventArgs());\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
248,102
|
<p>By default, I think my vimrc setttings enable the auto-wrapping. However, sometimes, I would like to see text lines are not wrapped. Is there any command I toggle the text line wrapping enabled and disabled? This would avoid me to exit and to change settings.</p>
|
[
{
"answer_id": 248116,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": true,
"text": ":set nowrap\n linebreak"
},
{
"answer_id": 248125,
"author": "m0j0",
"author_id": 31319,
"author_profile": "https://Stackoverflow.com/users/31319",
"pm_score": 4,
"selected": false,
"text": ":function ToggleWrap()\n: if (&wrap == 1)\n: set nowrap\n: else\n: set wrap\n: endif\n:endfunction\n map <F9> :call ToggleWrap()<CR>\nmap! <F9> ^[:call ToggleWrap()<CR>\n"
},
{
"answer_id": 248165,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 6,
"selected": false,
"text": ":set wrap!\n :help :_!\n"
},
{
"answer_id": 60289964,
"author": "Shyam Habarakada",
"author_id": 850996,
"author_profile": "https://Stackoverflow.com/users/850996",
"pm_score": 2,
"selected": false,
"text": "w map <C-w> :set wrap!<CR>\n"
},
{
"answer_id": 60293010,
"author": "D. Ben Knoble",
"author_id": 4400820,
"author_profile": "https://Stackoverflow.com/users/4400820",
"pm_score": 0,
"selected": false,
"text": "yow"
},
{
"answer_id": 74378126,
"author": "tothedistance",
"author_id": 13947038,
"author_profile": "https://Stackoverflow.com/users/13947038",
"pm_score": 0,
"selected": false,
"text": "qt qt"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
248,104
|
<p>I don't use Eclipse as an IDE, and have no interest in doing so. However, I do like its source-level debugging.</p>
<p>Is there any way I can use it to debug a C++ Linux app without going through the ritual of creating a project? (In effect, can I just use it like a frontend to gdb?)</p>
<p>If not, what are the steps I need to follow to create a project that I can use to just debug an existing C++ program that is built using Makefiles or other tools (SCons, CMake, etc.). I don't want to be able to "develop" in Eclipse; all I need to do is debug.</p>
|
[
{
"answer_id": 32523752,
"author": "user5325398",
"author_id": 5325398,
"author_profile": "https://Stackoverflow.com/users/5325398",
"pm_score": 0,
"selected": false,
"text": "Path Mapping:Project source and click on apply and then ok"
},
{
"answer_id": 35152931,
"author": "EML",
"author_id": 785194,
"author_profile": "https://Stackoverflow.com/users/785194",
"pm_score": 3,
"selected": false,
"text": "> eclipse&\n File Import C/C++ C/C++ Executable Next Next Finish"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
] |
248,112
|
<p>I need to invoke a c# application within my c# control, as I do not feel like rewriting the application as a control. </p>
<p>I am able to launch the application using System.Diagnostics.Process.Start.</p>
<p>Now how do I call the methods in my application from/via the c# control as this is where I invoked the application using System.Diagnostics.Process.Start</p>
|
[
{
"answer_id": 248630,
"author": "Harry Tsai",
"author_id": 31954,
"author_profile": "https://Stackoverflow.com/users/31954",
"pm_score": 0,
"selected": false,
"text": "string fileName = \"MainApp.exe\";\nstring className = \"Program\";\nstring methodName = \"Main\";\nstring[] args = {\"arg1\", \"arg2\"};\n\nAssembly asm = Assembly.LoadFrom(fileName);\nforeach (Type typ in asm.GetTypes())\n{\n if (typ.Name == className) \n {\n BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static;\n MethodInfo method = typ.GetMethod(methodName, flags);\n method.Invoke(null, new object[] { args });\n }\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
248,141
|
<p>I have a block of product images we received from a customer. Each product image is a picture of something and it was taken with a white background. I would like to crop all the surrounding parts of the image but leave only the product in the middle. Is this possible?</p>
<p>As an example: [<a href="http://www.5dnet.de/media/catalog/product/d/r/dress_shoes_5.jpg][1]" rel="noreferrer">http://www.5dnet.de/media/catalog/product/d/r/dress_shoes_5.jpg][1]</a></p>
<p>I don't want all white pixels removed, however I do want the image cropped so that the top-most row of pixels contains one non-white pixel, the left-most vertical row of pixels contains one non-white pixel, bottom-most horizontal row of pixels contains one non-white pixel, etc.</p>
<p>Code in C# or VB.net would be appreciated.</p>
|
[
{
"answer_id": 248205,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 4,
"selected": true,
"text": "Bitmap.GetPixel() Bitmap.LockBits() unsafe { }"
},
{
"answer_id": 248220,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "topmost = 0\nfor row from 0 to numRows:\n if allWhiteRow(row): \n topmost = row\n else:\n # found first non-white row from top\n break\n\nbotmost = 0\nfor row from numRows-1 to 0:\n if allWhiteRow(row): \n botmost = row\n else:\n # found first non-white row from bottom\n break\n allWhiteRow"
},
{
"answer_id": 249590,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": "pnmcrop netpbm"
},
{
"answer_id": 790541,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 4,
"selected": false,
"text": "public Bitmap Crop(Bitmap bmp)\n{\n int w = bmp.Width, h = bmp.Height;\n\n Func<int, bool> allWhiteRow = row =>\n {\n for (int i = 0; i < w; ++i)\n if (bmp.GetPixel(i, row).R != 255)\n return false;\n return true;\n };\n\n Func<int, bool> allWhiteColumn = col =>\n {\n for (int i = 0; i < h; ++i)\n if (bmp.GetPixel(col, i).R != 255)\n return false;\n return true;\n };\n\n int topmost = 0;\n for (int row = 0; row < h; ++row)\n {\n if (allWhiteRow(row))\n topmost = row;\n else break;\n }\n\n int bottommost = 0;\n for (int row = h - 1; row >= 0; --row)\n {\n if (allWhiteRow(row))\n bottommost = row;\n else break;\n }\n\n int leftmost = 0, rightmost = 0;\n for (int col = 0; col < w; ++col)\n {\n if (allWhiteColumn(col))\n leftmost = col;\n else\n break;\n }\n\n for (int col = w-1; col >= 0; --col)\n {\n if (allWhiteColumn(col))\n rightmost = col;\n else\n break;\n }\n\n int croppedWidth = rightmost - leftmost;\n int croppedHeight = bottommost - topmost;\n try\n {\n Bitmap target = new Bitmap(croppedWidth, croppedHeight);\n using (Graphics g = Graphics.FromImage(target))\n {\n g.DrawImage(bmp,\n new RectangleF(0, 0, croppedWidth, croppedHeight),\n new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),\n GraphicsUnit.Pixel);\n }\n return target;\n }\n catch (Exception ex)\n {\n throw new Exception(\n string.Format(\"Values are topmost={0} btm={1} left={2} right={3}\", topmost, bottommost, leftmost, rightmost),\n ex);\n }\n}\n"
},
{
"answer_id": 10392379,
"author": "Darren",
"author_id": 329367,
"author_profile": "https://Stackoverflow.com/users/329367",
"pm_score": 6,
"selected": false,
"text": " public static Bitmap Crop(Bitmap bmp)\n {\n int w = bmp.Width;\n int h = bmp.Height;\n\n Func<int, bool> allWhiteRow = row =>\n {\n for (int i = 0; i < w; ++i)\n if (bmp.GetPixel(i, row).R != 255)\n return false;\n return true;\n };\n\n Func<int, bool> allWhiteColumn = col =>\n {\n for (int i = 0; i < h; ++i)\n if (bmp.GetPixel(col, i).R != 255)\n return false;\n return true;\n };\n\n int topmost = 0;\n for (int row = 0; row < h; ++row)\n {\n if (allWhiteRow(row))\n topmost = row;\n else break;\n }\n\n int bottommost = 0;\n for (int row = h - 1; row >= 0; --row)\n {\n if (allWhiteRow(row))\n bottommost = row;\n else break;\n }\n\n int leftmost = 0, rightmost = 0;\n for (int col = 0; col < w; ++col)\n {\n if (allWhiteColumn(col))\n leftmost = col;\n else\n break;\n }\n\n for (int col = w - 1; col >= 0; --col)\n {\n if (allWhiteColumn(col))\n rightmost = col;\n else\n break;\n }\n\n if (rightmost == 0) rightmost = w; // As reached left\n if (bottommost == 0) bottommost = h; // As reached top.\n\n int croppedWidth = rightmost - leftmost;\n int croppedHeight = bottommost - topmost;\n\n if (croppedWidth == 0) // No border on left or right\n {\n leftmost = 0;\n croppedWidth = w;\n }\n\n if (croppedHeight == 0) // No border on top or bottom\n {\n topmost = 0;\n croppedHeight = h;\n }\n\n try\n {\n var target = new Bitmap(croppedWidth, croppedHeight);\n using (Graphics g = Graphics.FromImage(target))\n {\n g.DrawImage(bmp,\n new RectangleF(0, 0, croppedWidth, croppedHeight),\n new RectangleF(leftmost, topmost, croppedWidth, croppedHeight),\n GraphicsUnit.Pixel);\n }\n return target;\n }\n catch (Exception ex)\n {\n throw new Exception(\n string.Format(\"Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}\", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),\n ex);\n }\n }\n"
},
{
"answer_id": 29785775,
"author": "Brian Hasden",
"author_id": 28926,
"author_profile": "https://Stackoverflow.com/users/28926",
"pm_score": 3,
"selected": false,
"text": "public static Image AutoCrop(this Bitmap bmp)\n{\n if (Image.GetPixelFormatSize(bmp.PixelFormat) != 32)\n throw new InvalidOperationException(\"Autocrop currently only supports 32 bits per pixel images.\");\n\n // Initialize variables\n var cropColor = Color.White;\n\n var bottom = 0;\n var left = bmp.Width; // Set the left crop point to the width so that the logic below will set the left value to the first non crop color pixel it comes across.\n var right = 0;\n var top = bmp.Height; // Set the top crop point to the height so that the logic below will set the top value to the first non crop color pixel it comes across.\n\n var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, bmp.PixelFormat);\n\n unsafe\n {\n var dataPtr = (byte*)bmpData.Scan0;\n\n for (var y = 0; y < bmp.Height; y++)\n {\n for (var x = 0; x < bmp.Width; x++)\n {\n var rgbPtr = dataPtr + (x * 4);\n\n var b = rgbPtr[0];\n var g = rgbPtr[1];\n var r = rgbPtr[2];\n var a = rgbPtr[3];\n\n // If any of the pixel RGBA values don't match and the crop color is not transparent, or if the crop color is transparent and the pixel A value is not transparent\n if ((cropColor.A > 0 && (b != cropColor.B || g != cropColor.G || r != cropColor.R || a != cropColor.A)) || (cropColor.A == 0 && a != 0))\n {\n if (x < left)\n left = x;\n\n if (x >= right)\n right = x + 1;\n\n if (y < top)\n top = y;\n\n if (y >= bottom)\n bottom = y + 1;\n }\n }\n\n dataPtr += bmpData.Stride;\n }\n }\n\n bmp.UnlockBits(bmpData);\n\n if (left < right && top < bottom)\n return bmp.Clone(new Rectangle(left, top, right - left, bottom - top), bmp.PixelFormat);\n\n return null; // Entire image should be cropped, so just return null\n}\n"
},
{
"answer_id": 36001569,
"author": "user6064120",
"author_id": 6064120,
"author_profile": "https://Stackoverflow.com/users/6064120",
"pm_score": 3,
"selected": false,
"text": " public Bitmap Crop(Bitmap bitmap)\n {\n int w = bitmap.Width;\n int h = bitmap.Height;\n\n Func<int, bool> IsAllWhiteRow = row =>\n {\n for (int i = 0; i < w; i++)\n {\n if (bitmap.GetPixel(i, row).R != 255)\n {\n return false;\n }\n }\n return true;\n };\n\n Func<int, bool> IsAllWhiteColumn = col =>\n {\n for (int i = 0; i < h; i++)\n {\n if (bitmap.GetPixel(col, i).R != 255)\n {\n return false;\n }\n }\n return true;\n };\n\n int leftMost = 0;\n for (int col = 0; col < w; col++)\n {\n if (IsAllWhiteColumn(col)) leftMost = col + 1;\n else break;\n }\n\n int rightMost = w - 1;\n for (int col = rightMost; col > 0; col--)\n {\n if (IsAllWhiteColumn(col)) rightMost = col - 1;\n else break;\n }\n\n int topMost = 0;\n for (int row = 0; row < h; row++)\n {\n if (IsAllWhiteRow(row)) topMost = row + 1;\n else break;\n }\n\n int bottomMost = h - 1;\n for (int row = bottomMost; row > 0; row--)\n {\n if (IsAllWhiteRow(row)) bottomMost = row - 1;\n else break;\n }\n\n if (rightMost == 0 && bottomMost == 0 && leftMost == w && topMost == h)\n {\n return bitmap;\n }\n\n int croppedWidth = rightMost - leftMost + 1;\n int croppedHeight = bottomMost - topMost + 1;\n\n try\n {\n Bitmap target = new Bitmap(croppedWidth, croppedHeight);\n using (Graphics g = Graphics.FromImage(target))\n {\n g.DrawImage(bitmap,\n new RectangleF(0, 0, croppedWidth, croppedHeight),\n new RectangleF(leftMost, topMost, croppedWidth, croppedHeight),\n GraphicsUnit.Pixel);\n }\n return target;\n }\n catch (Exception ex)\n {\n throw new Exception(string.Format(\"Values are top={0} bottom={1} left={2} right={3}\", topMost, bottomMost, leftMost, rightMost), ex);\n }\n }\n"
},
{
"answer_id": 52492146,
"author": "Trung",
"author_id": 4038253,
"author_profile": "https://Stackoverflow.com/users/4038253",
"pm_score": 2,
"selected": false,
"text": "public void TrimImage() {\n int threshhold = 250;\n\n\n int topOffset = 0;\n int bottomOffset = 0;\n int leftOffset = 0;\n int rightOffset = 0;\n Bitmap img = new Bitmap(@\"e:\\Temp\\Trim_Blank_Image.png\");\n\n\n bool foundColor = false;\n // Get left bounds to crop\n for (int x = 1; x < img.Width && foundColor == false; x++)\n {\n for (int y = 1; y < img.Height && foundColor == false; y++)\n {\n Color color = img.GetPixel(x, y);\n if (color.R < threshhold || color.G < threshhold || color.B < threshhold)\n foundColor = true;\n }\n leftOffset += 1;\n }\n\n\n foundColor = false;\n // Get top bounds to crop\n for (int y = 1; y < img.Height && foundColor == false; y++)\n {\n for (int x = 1; x < img.Width && foundColor == false; x++)\n {\n Color color = img.GetPixel(x, y);\n if (color.R < threshhold || color.G < threshhold || color.B < threshhold)\n foundColor = true;\n }\n topOffset += 1;\n }\n\n\n foundColor = false;\n // Get right bounds to crop\n for (int x = img.Width - 1; x >= 1 && foundColor == false; x--)\n {\n for (int y = 1; y < img.Height && foundColor == false; y++)\n {\n Color color = img.GetPixel(x, y);\n if (color.R < threshhold || color.G < threshhold || color.B < threshhold)\n foundColor = true;\n }\n rightOffset += 1;\n }\n\n\n foundColor = false;\n // Get bottom bounds to crop\n for (int y = img.Height - 1; y >= 1 && foundColor == false; y--)\n {\n for (int x = 1; x < img.Width && foundColor == false; x++)\n {\n Color color = img.GetPixel(x, y);\n if (color.R < threshhold || color.G < threshhold || color.B < threshhold)\n foundColor = true;\n }\n bottomOffset += 1;\n }\n\n\n // Create a new image set to the size of the original minus the white space\n //Bitmap newImg = new Bitmap(img.Width - leftOffset - rightOffset, img.Height - topOffset - bottomOffset);\n\n Bitmap croppedBitmap = new Bitmap(img);\n croppedBitmap = croppedBitmap.Clone(\n new Rectangle(leftOffset - 3, topOffset - 3, img.Width - leftOffset - rightOffset + 6, img.Height - topOffset - bottomOffset + 6),\n System.Drawing.Imaging.PixelFormat.DontCare);\n\n\n // Get a graphics object for the new bitmap, and draw the original bitmap onto it, offsetting it do remove the whitespace\n //Graphics g = Graphics.FromImage(croppedBitmap);\n //g.DrawImage(img, 1 - leftOffset, 1 - rightOffset);\n croppedBitmap.Save(@\"e:\\Temp\\Trim_Blank_Image-crop.png\", ImageFormat.Png);\n}\n"
},
{
"answer_id": 70237594,
"author": "Jonesie",
"author_id": 98406,
"author_profile": "https://Stackoverflow.com/users/98406",
"pm_score": -1,
"selected": false,
"text": "using SkiaSharp;\nusing System;\n\n//\n// Based on the original stackoverflow post: https://stackoverflow.com/questions/248141/remove-surrounding-whitespace-from-an-image\n//\nnamespace BlahBlah\n{\n\n public static class BitmapExtensions\n {\n public static SKBitmap TrimWhitespace(this SKBitmap bmp)\n {\n int w = bmp.Width;\n int h = bmp.Height;\n \n // get all the pixels here - this can take a while so dont want it in the loops below\n // maybe theres a more efficient way? loading all the pixels could be greedy\n var pixels = bmp.Pixels;\n\n bool IsTransparent(SKColor color)\n {\n return (color.Red == 0 && color.Green == 0 && color.Blue == 0 && color.Alpha == 0) || \n (color == SKColors.Transparent);\n }\n\n Func<int, bool> allWhiteRow = row =>\n {\n for (int i = 0; i < w; ++i)\n {\n var px = row * w + i;\n if (!IsTransparent(pixels[px]))\n return false;\n }\n return true;\n };\n\n Func<int, bool> allWhiteColumn = col =>\n {\n for (int i = 0; i < h; ++i)\n {\n var px = col * h + i;\n if (!IsTransparent(pixels[px]))\n return false;\n }\n return true;\n };\n\n int topmost = 0;\n for (int row = 0; row < h; ++row)\n {\n if (allWhiteRow(row))\n topmost = row;\n else break;\n }\n\n int bottommost = 0;\n for (int row = h - 1; row >= 0; --row)\n {\n if (allWhiteRow(row))\n bottommost = row;\n else break;\n }\n\n int leftmost = 0, rightmost = 0;\n for (int col = 0; col < w; ++col)\n {\n if (allWhiteColumn(col))\n leftmost = col;\n else\n break;\n }\n\n for (int col = w - 1; col >= 0; --col)\n {\n if (allWhiteColumn(col))\n rightmost = col;\n else\n break;\n }\n\n if (rightmost == 0) rightmost = w; // As reached left\n if (bottommost == 0) bottommost = h; // As reached top.\n\n int croppedWidth = rightmost - leftmost;\n int croppedHeight = bottommost - topmost;\n\n if (croppedWidth == 0) // No border on left or right\n {\n leftmost = 0;\n croppedWidth = w;\n }\n\n if (croppedHeight == 0) // No border on top or bottom\n {\n topmost = 0;\n croppedHeight = h;\n }\n\n try\n {\n var target = new SKBitmap(croppedWidth, croppedHeight);\n\n using var canvas = new SKCanvas(target);\n using var img = SKImage.FromBitmap(bmp);\n canvas.DrawImage(img,\n new SKRect(leftmost, topmost, rightmost, bottommost),\n new SKRect(0, 0, croppedWidth, croppedHeight));\n\n return target;\n }\n catch (Exception ex)\n {\n throw new Exception(\n string.Format(\"Values are topmost={0} btm={1} left={2} right={3} croppedWidth={4} croppedHeight={5}\", topmost, bottommost, leftmost, rightmost, croppedWidth, croppedHeight),\n ex);\n }\n }\n\n }\n}\n"
},
{
"answer_id": 74287231,
"author": "Senad Mulaosmanović",
"author_id": 7017588,
"author_profile": "https://Stackoverflow.com/users/7017588",
"pm_score": 0,
"selected": false,
"text": "var px = i * w + col;"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6158/"
] |
248,149
|
<p><code>Connection.close()</code> may throw <code>SqlException</code>, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them). </p>
<p>Normally I would write:</p>
<pre><code> try{
connection.close();
}catch(Exception e) {}
</code></pre>
<p>Or </p>
<pre><code> try{
connection.close();
}catch(Exception e) {
logger.log(e.getMessage(), e);
}
</code></pre>
<p>The question is:</p>
<ol>
<li>Is it bad practice (and has anyone had problems when ignoring such exceptions).</li>
<li>When <code>Connection.close()</code> does throw any exception. </li>
<li>If it is bad how should I handle the exception. </li>
</ol>
<p>Comment: </p>
<p>I know that discarding exceptions is evil, but I'm reffering only to exceptions thrown when closing a connection (and as I've seen this is fairly common in this case). </p>
<p>Does anyone know when <code>Connection.close()</code> may throw anything? </p>
|
[
{
"answer_id": 248167,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 4,
"selected": false,
"text": "try {\n Thread.sleep(1000);\ncatch (InterruptedException e) {\n // I really don't care if this sleep is interrupted!\n}\n boolean interrupted=Thread.sleep(1000);\n"
},
{
"answer_id": 248210,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 1,
"selected": false,
"text": "if (connection != null) {\n try { \n connection.close(); \n } catch (SQLException sqle) { \n logger.log(e.getMessage(), e); \n }\n}\n"
},
{
"answer_id": 249023,
"author": "Fábio",
"author_id": 9458,
"author_profile": "https://Stackoverflow.com/users/9458",
"pm_score": 1,
"selected": false,
"text": "try {\n connection.close();\n } catch(Exception e) {\n throw new RuntimeException(e); \n }\n"
},
{
"answer_id": 249149,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 5,
"selected": true,
"text": "/**\n * Close the given ResultSet and ignore any thrown exception.\n * This is useful for typical finally blocks in manual code.\n * @param resultSet the ResultSet to close\n * @see javax.resource.cci.ResultSet#close()\n */\nprivate void closeResultSet(ResultSet resultSet) {\n if (resultSet != null) {\n try {\n resultSet.close();\n }\n catch (SQLException ex) {\n logger.debug(\"Could not close ResultSet\", ex);\n }\n catch (Throwable ex) {\n // We don't trust the driver: It might throw RuntimeException or Error.\n logger.debug(\"Unexpected exception on closing ResultSet\", ex);\n }\n }\n}\n"
},
{
"answer_id": 626449,
"author": "Brian Agnew",
"author_id": 12960,
"author_profile": "https://Stackoverflow.com/users/12960",
"pm_score": 1,
"selected": false,
"text": "closeQuietly() close()"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
] |
248,161
|
<p>I got curious by <a href="http://dotnet.kapenilattex.com/?p=93" rel="nofollow noreferrer">Jon Limjap's interview mishap</a> and started to look for efficient ways to do palindrome detection. I checked the <a href="https://stackoverflow.com/questions/228518/palindrome-golf">palindrome golf</a> answers and it seems to me that in the answers are two algorithms only, reversing the string and checking from tail and head.</p>
<pre class="lang-py prettyprint-override"><code>def palindrome_short(s):
length = len(s)
for i in xrange(0,length/2):
if s[i] != s[(length-1)-i]: return False
return True
def palindrome_reverse(s):
return s == s[::-1]
</code></pre>
<p>I think neither of these methods are used in the detection of exact palindromes in huge DNA sequences. I looked around a bit and didn't find any free article about what an ultra efficient way for this might be.</p>
<p>A good way might be parallelizing the first version in a divide-and-conquer approach, assigning a pair of char arrays 1..n and length-1-n..length-1 to each thread or processor. </p>
<p>What would be a better way?</p>
<p>Do you know any?</p>
|
[
{
"answer_id": 248189,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "i [i*n/2, (i+1)*N/2) [L-(i+1)*N/2, L-i*N/2)"
},
{
"answer_id": 248214,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": true,
"text": "isPal(w[0:100],w[-100:]) and isPal(w[101:200], w[-200:-100]) ...\n isPal = {(\"ATTAGC\", \"CGATTA\"): True, (\"ATTGCA\", \"CAGTAA\"): False}\n"
},
{
"answer_id": 486278,
"author": "Demur Rumed",
"author_id": 40172,
"author_profile": "https://Stackoverflow.com/users/40172",
"pm_score": -1,
"selected": false,
"text": "def ispalin(x):\n return all(x[a]==x[-a-1] for a in xrange(len(x)>>1))\n"
},
{
"answer_id": 801422,
"author": "drnk",
"author_id": 77619,
"author_profile": "https://Stackoverflow.com/users/77619",
"pm_score": 2,
"selected": false,
"text": "def palindrome_reverse(s):\n l = len(s) / 2\n return s[:l] == s[l::-1]\n"
},
{
"answer_id": 45397145,
"author": "mahashwetha",
"author_id": 1229998,
"author_profile": "https://Stackoverflow.com/users/1229998",
"pm_score": -1,
"selected": false,
"text": "For odd lettered string the counter should be back to 1 and for even it should hit 0.I hope this approach is right.\n\nSee below the snippet.\ns->refers to string\neg: String s=\"abbcaddc\";\nHashtable<Character,Integer> textMap= new Hashtable<Character,Integer>();\n char charA[]= s.toCharArray();\n for(int i=0;i<charA.length;i++)\n {\n\n if(!textMap.containsKey(charA[i]))\n { \n textMap.put(charA[i], ++count);\n\n }\n else\n {\n textMap.put(charA[i],--count);\n\n\n }\n if(length%2 !=0)\n {\n if(count == 1)\n System.out.println(\"(odd case:PALINDROME)\");\n else\n System.out.println(\"(odd case:not palindrome)\");\n }\n else if(length%2==0) \n {\n if(count ==0)\n System.out.println(\"(even case:palindrome)\");\n else\n System.out.println(\"(even case :not palindrome)\");\n }\n"
},
{
"answer_id": 53533419,
"author": "Tangang Atanga",
"author_id": 10720960,
"author_profile": "https://Stackoverflow.com/users/10720960",
"pm_score": -1,
"selected": false,
"text": "public class Palindrome{\n private static boolean isPalindrome(String s){\n if(s == null)\n return false; //unitialized String ? return false\n if(s.isEmpty()) //Empty Strings is a Palindrome \n return true;\n //we want check characters on opposite sides of the string \n //and stop in the middle <divide and conquer>\n int left = 0; //left-most char \n int right = s.length() - 1; //right-most char\n\n while(left < right){ //this elegantly handles odd characters string \n if(s.charAt(left) != s.charAt(right)) //left char must equal \n return false; //right else its not a palindrome\n left++; //converge left to right \n right--;//converge right to left \n }\n return true; // return true if the while doesn't exit \n }\n}\n"
},
{
"answer_id": 71468254,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": 0,
"selected": false,
"text": "quick check whether tail-character matches \n head character \n\nif NOT, just early exit by returning Boolean-False\n\nif (input-length < 4) { \n\n # The quick check just now already confirmed it's palindrome \n\n return Boolean-True \n\n} else if (200 < input-length) {\n \n # adjust this parameter to your preferences\n #\n # e.g. make it 20 for longer than 8000 etc\n # or make it scale to input size,\n # either logarithmically, or a fixed ratio like 2.5%\n #\n reverse last ( N = 4 ) characters/bytes of the input \n\n if that **DOES NOT** match first N chars/bytes {\n\n return boolean-false # early exit\n # no point to reverse rest of it\n # when head and tail don't even match\n } else {\n \n if N was substantial\n\n trim out the head and tail of the input\n you've confirmed; avoid duplicated work\n\n remember to also update the variable(s)\n you've elected to track the input size \n\n }\n\n [optional 1 : if that substring of N characters you've \n just checked happened to all contain the\n same character, let's call it C,\n \n then locate the index position, P, for the first \n character that isn't C\n \n if P == input-size \n\n then you've already proven\n the entire string is a nonstop repeat \n of one single character, which, by def, \n must be a palindrome\n\n then just return Boolean-True\n\n\n but the P is more than the half-way point,\n you've also proven it cannot possibly be a \n palindrome, because second half contains a \n component that doesn't exist in first half,\n \n\n then just return Boolean-False ]\n\n\n [optional 2 : for extremely long inputs, \n like over 200,000 chars,\n take the N chars right at the middle of it,\n and see if the reversed one matches\n \n if that fails, then do early exit and save time ]\n\n }\n\n if all pre-checks passed,\n then simply do it BAU style :\n\n reverse second-half of it, \n and see if it's same as first half\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
248,181
|
<p>I've never used any kind of source control before although I understand the concept. What I am confused about (and perhaps just not aware) is what benefit do I achieve and/or why would I want to configure Subversion and Apache? Do I need to configure it with Apache to be able to access my repositories from other computers over a network? Please feel free to provide any other details you feel are relevant?</p>
<p>My setup right now is a laptop (Windows XP Pro) and a virtual machine (Windows XP Pro). On my virtual machine I have Apache 2.2, MySQL 5 and PHP 5. This setup is my main concern although I'm happy to hear examples/situations that deviate from my scenario.</p>
|
[
{
"answer_id": 248201,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 1,
"selected": false,
"text": "svnserve"
},
{
"answer_id": 248204,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 2,
"selected": false,
"text": "svnserve"
},
{
"answer_id": 248895,
"author": "Hector Sosa Jr",
"author_id": 12829,
"author_profile": "https://Stackoverflow.com/users/12829",
"pm_score": 0,
"selected": false,
"text": "--port svnserve"
},
{
"answer_id": 552412,
"author": "Kyle Brantley",
"author_id": 66329,
"author_profile": "https://Stackoverflow.com/users/66329",
"pm_score": 2,
"selected": false,
"text": "svnserve"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444511/"
] |
248,186
|
<p>I'm working on a service that needs to detect user states for all user(s) logged on to a single machine. Specifically, I want to check to see whether or not the screen saver is active and whether or not their session is locked.</p>
<p>This code will run under a system-level service, and has no visible UI, so that may rule out several options (trapping WM messages, etc).</p>
<p>Aside from normal workstations, I'd like for this to work on terminal servers that have multiple users logged in to it. Due to these requirements I'm wondering if several Win32 APIs will need to be involved.</p>
<p>Any ideas on where to begin?</p>
|
[
{
"answer_id": 733960,
"author": "Dan Ports",
"author_id": 88885,
"author_profile": "https://Stackoverflow.com/users/88885",
"pm_score": 2,
"selected": false,
"text": "using Cassia;\n\nforeach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions())\n{\n if ((session.CurrentTime - session.LastInputTime > TimeSpan.FromMinutes(10)) &&\n (!string.IsNullOrEmpty(session.UserName)))\n {\n Console.WriteLine(\"Session {0} (User {1}) is idle\", session.SessionId, session.UserName);\n }\n}\n"
},
{
"answer_id": 734037,
"author": "Michael Piendl",
"author_id": 1838492,
"author_profile": "https://Stackoverflow.com/users/1838492",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.ServiceProcess;\nusing System.Diagnostics;\n\nnamespace MyCode\n{\n class MyService : ServiceBase\n {\n public MyService()\n {\n this.CanHandleSessionChangeEvent = true;\n }\n\n protected override void OnSessionChange(SessionChangeDescription changeDescription)\n {\n switch (changeDescription.Reason)\n {\n case SessionChangeReason.SessionLogon:\n Debug.WriteLine(changeDescription.SessionId + \" logon\");\n break;\n case SessionChangeReason.SessionLogoff:\n Debug.WriteLine(changeDescription.SessionId + \" logoff\");\n break;\n case SessionChangeReason.SessionLock:\n Debug.WriteLine(changeDescription.SessionId + \" lock\");\n break;\n case SessionChangeReason.SessionUnlock:\n Debug.WriteLine(changeDescription.SessionId + \" unlock\");\n break;\n }\n\n base.OnSessionChange(changeDescription);\n }\n }\n}\n public static WindowsIdentity GetUserName(int sessionId)\n {\n foreach (Process p in Process.GetProcesses())\n {\n if(p.SessionId == sessionId) { \n return new WindowsIdentity(p.Handle); \n } \n }\n return null;\n }\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32536/"
] |
248,219
|
<p>i know how to import an sql file via the cli:</p>
<pre><code>mysql -u USER -p DBNAME < dump.sql
</code></pre>
<p>but that's if the dump.sql file is local. how could i use a file on a remote server?</p>
|
[
{
"answer_id": 248329,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 6,
"selected": true,
"text": "ssh remote.com \"mysqldump remotedb\" | mysql localdb\n .my.cnf -u -p -h ssh remote.com \"mysqldump -u remoteuser -p'remotepass' remotedb\" | mysql -u localuser -p'localpass' localdb\n gzip ssh remote.com \"mysqldump remotedb | gzip\" | gzip -d | mysql localdb\n"
},
{
"answer_id": 31727748,
"author": "skh",
"author_id": 2772071,
"author_profile": "https://Stackoverflow.com/users/2772071",
"pm_score": 2,
"selected": false,
"text": "ssh <ip-address> \"cat /path/to/db.sql\" | mysql -u <user> -p<password> <dbname>\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18285/"
] |
248,222
|
<p>What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?</p>
<p>For example. If I have some Products and I'm pulling from a database</p>
<p>explicit way:</p>
<pre><code>public List<Product> GetProduct(int productId) { // return a List }
public List<Product> GetProductByCategory(Category category) { // return a List }
public List<Product> GetProductByName(string Name ) { // return a List }
</code></pre>
<p>overloaded way:</p>
<pre><code>public List<Product> GetProducts() { // return a List of all products }
public List<Product> GetProducts(Category category) { // return a List by Category }
public List<Product> GetProducts(string searchString ) { // return a List by search string }
</code></pre>
<p>I realize you may get into a problem with <strong>similar signatures</strong>, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to <strong>overload a method</strong> to reduce the number of methods you have and for clarity, <strong>or</strong> should <strong>each method</strong> that filters the data a different way <strong>have a different method name</strong>?</p>
|
[
{
"answer_id": 248237,
"author": "ema",
"author_id": 19520,
"author_profile": "https://Stackoverflow.com/users/19520",
"pm_score": 2,
"selected": false,
"text": "public List<Product> GetProducts(Query query)\n"
},
{
"answer_id": 248267,
"author": "JTew",
"author_id": 25372,
"author_profile": "https://Stackoverflow.com/users/25372",
"pm_score": 1,
"selected": false,
"text": "GetQuery<Type>().ApplyCategoryFilter(category).ApplyProductNameFilter(productName);\n public static IQueryable<T> ApplyXYZFilter(this IQueryable<T> query, string filter)\n{\n return query.Where(XYZ => XYZ == filter);\n} \n"
},
{
"answer_id": 248284,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 2,
"selected": false,
"text": "public List<Product> GetProduct(int productId) { // return a List }\npublic List<Product> GetProduct(int productId, int ownerId ) { // return a List }\npublic List<Product> GetProduct(int productId, int vendorId, boolean printInvoice) { // return a List }\n int"
},
{
"answer_id": 248473,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 3,
"selected": false,
"text": "public List<Employee> GetEmployees(int supervisorId);\npublic List<Employee> GetEmployees(int departmentId); // Not Allowed !!\n public struct EmployeeId \n { \n private int empId;\n public int EmployeeId { get { return empId; } set { empId = value; } }\n public EmployeeId(int employeId) { empId = employeeId; }\n }\n\n public struct DepartmentId \n {\n // analogous content\n }\n\n // Now it's fine, as the parameters are defined as distinct types...\n public List<Employee> GetEmployees(EmployeeId supervisorId);\n public List<Employee> GetEmployees(DepartmentId departmentId);\n"
},
{
"answer_id": 248590,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 2,
"selected": false,
"text": "ref out null"
},
{
"answer_id": 249624,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 7,
"selected": true,
"text": "void DeleteFile(string filePath);\nvoid DeleteFile(FileInfo file);\nvoid DeleteFile(DirectoryInfo directory, string fileName);\n public IList<Product> GetProductById(int productId) {...}\npublic IList<Product> GetProductByCategory(Category category) {...}\npublic IList<Product> GetProductByName(string Name ) {...}\n // No collisions, even though both methods take int parameters\npublic IList<Employee> GetEmployeesBySupervisor(int supervisorId);\npublic IList<Employee> GetEmployeesByDepartment(int departmentId);\n // Examples for GetEmployees\n\npublic IList<Employee> GetEmployeesBySupervisor(int supervisorId);\npublic IList<Employee> GetEmployeesBySupervisor(Supervisor supervisor);\npublic IList<Employee> GetEmployeesBySupervisor(Person supervisor);\n\npublic IList<Employee> GetEmployeesByDepartment(int departmentId);\npublic IList<Employee> GetEmployeesByDepartment(Department department);\n\n// Examples for GetProduct\n\npublic IList<Product> GetProductById(int productId) {...}\npublic IList<Product> GetProductById(params int[] productId) {...}\n\npublic IList<Product> GetProductByCategory(Category category) {...}\npublic IList<Product> GetProductByCategory(IEnumerable<Category> category) {...}\npublic IList<Product> GetProductByCategory(params Category[] category) {...}\n"
},
{
"answer_id": 442205,
"author": "Daniel Daranas",
"author_id": 96780,
"author_profile": "https://Stackoverflow.com/users/96780",
"pm_score": 0,
"selected": false,
"text": "Add(...) AddRecord(const Record&) AddCell(const Cell&)"
},
{
"answer_id": 10635156,
"author": "AgentFire",
"author_id": 558018,
"author_profile": "https://Stackoverflow.com/users/558018",
"pm_score": 0,
"selected": false,
"text": "public IList<Product> GetProducts() { /* Return all. */}\n\npublic IList<Product> GetProductBy(int productId) {...}\npublic IList<Product> GetProductBy(Category category) {...}\npublic IList<Product> GetProductBy(string Name ) {...}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26931/"
] |
248,224
|
<p>I downloaded the free CodeRush Xpress version to try it. Is there a way to change the colors it uses for it's highlighting and line drawing? ie the matching braces. I have a dark color scheme and my monitor I have VS on must suck because I can't see the lines. Yet on the LCD I can. Is there a way to change the colors?</p>
|
[
{
"answer_id": 862842,
"author": "Christian",
"author_id": 54193,
"author_profile": "https://Stackoverflow.com/users/54193",
"pm_score": 4,
"selected": true,
"text": "Alt+Ctrl+Shift+O [HKEY_LOCAL_MACHINE\\SOFTWARE\\Developer Express\\CodeRush for VS\\9.2]\n \"HideMenu\"=dword:00000000\n"
},
{
"answer_id": 15099143,
"author": "Samir Banjanovic",
"author_id": 1332387,
"author_profile": "https://Stackoverflow.com/users/1332387",
"pm_score": 0,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Developer Express\\CodeRush for VS"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7024/"
] |
248,227
|
<p>I have an XML file, and I want to find nodes that have duplicate CDATA. Are there any tools that exist that can help me do this?</p>
<p>I'd be fine with a tool that does this generally for text documents.</p>
|
[
{
"answer_id": 473563,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 2,
"selected": false,
"text": "import xml.etree.ElementTree as ElementTree\nimport sys\n\ndef print_elem(element):\n return \"<%s>\" % element.tag\n\nif len(sys.argv) != 2:\n print >> sys.stderr, \"Usage: %s filename\" % sys.argv[0]\n sys.exit(1)\nfilename = sys.argv[1] \ntree = ElementTree.parse(filename)\nroot = tree.getroot()\nchunks = {}\niter = root.findall('.//*')\nfor element in iter:\n if element.text in chunks:\n chunks[element.text].append(element)\n else:\n chunks[element.text] = [element,]\nfor text in chunks:\n if len(chunks[text]) > 1:\n print \"\\\"%s\\\" is a duplicate: found in %s\" % \\\n (text, map(print_elem, chunks[text]))\n <foo>\n<bar>Hop</bar><quiz>Gaw</quiz>\n<sub>\n<und>Hop</und>\n</sub>\n \"Hop\" is a duplicate: found in ['<bar>', '<und>']\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245644/"
] |
248,243
|
<p>A library using off_t as a parameter for one function (seek). Library and application are compiled differently, one with large file support switched off, the other with large file support. This situation results in strange runtime errors, because both interpret off_t differently. How can the library check at runtime the size of off_t for the app? Or is there another solution, so that at least the user gets a meaningful error?</p>
<p>EDIT: The library (programmed in c and with autoconf) already exists and some third-party application use it. The library can be compiled with large file support (by default via AC_SYS_LARGEFILE). It is multiplatform, not only linux. How can be detected/prevented that installed applications will be broken by the change in LFS?</p>
|
[
{
"answer_id": 248309,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": false,
"text": "size_t lib_get_off_t_size (void)\n{\n return (sizeof(off_t));\n}\n if (lib_get_off_t_size() != sizeof(off_t) {\n printf(\"Oh no!\\n\");\n exit();\n}\n"
},
{
"answer_id": 248417,
"author": "lImbus",
"author_id": 32490,
"author_profile": "https://Stackoverflow.com/users/32490",
"pm_score": 0,
"selected": false,
"text": "//in library:\nBOOL isLargeFileSupport (void)\n{\n#ifdef LARGE_FILE_SUPPORT\n return TRUE;\n#else\n return FALSE;\n#endif\n}\n //in application\nBOOL bLibLFS = lib_isLargeFileSupport();\nBOOL bAppLFS = FALSE;\n#ifdef LARGE_FILE_SUPPORT\n bAppLFS = TRUE;\n#endif\n\nif (bLibLFS != bAppLFS)\n //incompatible versions, bail out\n exit(0);\n"
},
{
"answer_id": 248539,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "off_t off64_t off64_t off_t _LARGEFILE64_SOURCE _FILE_OFFSET_BITS 32 #error /usr/include/features.h"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
248,246
|
<p>Do any queries exist that require RIGHT JOIN, or can they always be re-written with LEFT JOIN?</p>
<p>And more specifically, how do you re-write this one without the right join (and I guess implicitly without any subqueries or other fanciness):</p>
<p><pre><code>
SELECT *
FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
</pre></code></p>
|
[
{
"answer_id": 248253,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "SELECT * /* example: don't care what's returned */\nFROM LargeTable L\nLEFT JOIN MediumTable M ON M.L_ID=L.ID\nLEFT JOIN SmallTable S ON S.M_ID=M.ID\nWHERE ...\n"
},
{
"answer_id": 248403,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 5,
"selected": true,
"text": "SELECT * FROM t1\n LEFT JOIN t2 ON t1.k2 = t2.k2\n RIGHT JOIN t3 ON t3.k3 = t2.k3\n Select * From t3 \n Left Join (t1 Left Join t2 \n On t2.k2 = t1.k2)\n On T2.k3 = T3.K3\n"
},
{
"answer_id": 248413,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": -1,
"selected": false,
"text": "LEFT JOIN RIGHT JOIN SELECT *\nFROM t1\nCROSS JOIN t3\nLEFT JOIN t2\n ON t1.k2 = t2.k2\n AND t3.k3 = t2.k3\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12861/"
] |
248,254
|
<p>I want to be able to see how many lines were added to a file since the last quering without reading the whole file again.</p>
<p>Something like :</p>
<pre><code>ptail my_file | fgrep "[ERROR]" | wc -l
</code></pre>
<p>A solution in simple Perl would be prefered, since I don't have an easy access to a compiler.</p>
|
[
{
"answer_id": 248253,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": false,
"text": "SELECT * /* example: don't care what's returned */\nFROM LargeTable L\nLEFT JOIN MediumTable M ON M.L_ID=L.ID\nLEFT JOIN SmallTable S ON S.M_ID=M.ID\nWHERE ...\n"
},
{
"answer_id": 248403,
"author": "charles bretana",
"author_id": 32561,
"author_profile": "https://Stackoverflow.com/users/32561",
"pm_score": 5,
"selected": true,
"text": "SELECT * FROM t1\n LEFT JOIN t2 ON t1.k2 = t2.k2\n RIGHT JOIN t3 ON t3.k3 = t2.k3\n Select * From t3 \n Left Join (t1 Left Join t2 \n On t2.k2 = t1.k2)\n On T2.k3 = T3.K3\n"
},
{
"answer_id": 248413,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": -1,
"selected": false,
"text": "LEFT JOIN RIGHT JOIN SELECT *\nFROM t1\nCROSS JOIN t3\nLEFT JOIN t2\n ON t1.k2 = t2.k2\n AND t3.k3 = t2.k3\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24760/"
] |
248,263
|
<p>I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in order to access virtual method). </p>
<p>Is there any way around this? I guess I could use a singleton.. HelperClass.Instance.HelperMethod() isn't so much worse than HelperClass.HelperMethod(). Brownie points for anyone that can point out some languages that support virtual static methods.</p>
<p><strong>Edit:</strong> OK yeah I'm crazy. Google search results had me thinking I wasn't for a bit there.</p>
|
[
{
"answer_id": 248276,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 6,
"selected": true,
"text": "HelperClass.HelperMethod(); HelperClass"
},
{
"answer_id": 248348,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 4,
"selected": false,
"text": "type\n TForm1 = class(TForm)\n procedure FormShow(Sender: TObject);\n end;\n\n TTestClass = class\n public\n class procedure TestMethod(); virtual;\n end;\n\n TTestDerivedClass = class(TTestClass)\n public\n class procedure TestMethod(); override;\n end;\n\n TTestMetaClass = class of TTestClass;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nclass procedure TTestClass.TestMethod();\nbegin\n Application.MessageBox('base', 'Message');\nend;\n\nclass procedure TTestDerivedClass.TestMethod();\nbegin\n Application.MessageBox('descendant', 'Message');\nend;\n\n\nprocedure TForm1.FormShow(Sender: TObject);\nvar\n sample: TTestMetaClass;\nbegin\n sample := TTestClass;\n sample.TestMethod;\n sample := TTestDerivedClass;\n sample.TestMethod;\nend;\n"
},
{
"answer_id": 1689647,
"author": "Mart",
"author_id": 183386,
"author_profile": "https://Stackoverflow.com/users/183386",
"pm_score": 1,
"selected": false,
"text": "new virtual class Car\n{\n public static int TyreCount = 4;\n public virtual int GetTyreCount() { return TyreCount; }\n}\nclass Tricar : Car\n{\n public static new int TyreCount = 3;\n public override int GetTyreCount() { return TyreCount; }\n}\n\n...\n\nCar[] cc = new Car[] { new Tricar(), new Car() };\nint t0 = cc[0].GetTyreCount(); // t0 == 3\nint t1 = cc[1].GetTyreCount(); // t1 == 4\n TyreCount GetTyreCount"
},
{
"answer_id": 2421476,
"author": "SeeR",
"author_id": 22569,
"author_profile": "https://Stackoverflow.com/users/22569",
"pm_score": 6,
"selected": false,
"text": "public interface ISumable<T>\n{\n static T Add(T left, T right);\n}\n public T Aggregate<T>(T left, T right) where T : ISumable<T>\n{\n return T.Add(left, right);\n}\n public static class Static<T> where T : new()\n {\n public static T Value = new T();\n }\n\n public interface ISumable<T>\n {\n T Add(T left, T right);\n }\n\n public T Aggregate<T>(T left, T right) where T : ISumable<T>, new()\n {\n return Static<T>.Value.Add(left, right);\n }\n"
},
{
"answer_id": 3188907,
"author": "Ken Revak",
"author_id": 384826,
"author_profile": "https://Stackoverflow.com/users/384826",
"pm_score": 3,
"selected": false,
"text": " class Root {\n public static virtual string TestMethod() {return \"Root\"; }\n }\n TRootClass = class of TRoot; // Here is the typed type declaration\n\n class Derived : Root {\n public static overide string TestMethod(){ return \"derived\"; }\n }\n\n class Test {\n public static string Run(){\n TRootClass rc;\n rc = Root;\n Test(rc);\n rc = Derived();\n Test(rc);\n }\n public static Test(TRootClass AClass){\n string str = AClass.TestMethod();\n Console.WriteLine(str);\n }\n } \n"
},
{
"answer_id": 6178793,
"author": "Level 42",
"author_id": 776507,
"author_profile": "https://Stackoverflow.com/users/776507",
"pm_score": 1,
"selected": false,
"text": "public abstract class HouseDeed : Item\n{\n public static int m_price = 0;\n public abstract int Price { get; }\n /* more impl here */\n}\n public class FieldStoneHouseDeed : HouseDeed\n{\n public static new int m_price = 43800;\n public override int Price { get { return m_price; } }\n /* more impl here */\n}\n public class SmallTowerDeed : HouseDeed\n{\n public static new int m_price = 88500;\n public override int Price { get { return m_price; } }\n /* more impl here */\n}\n"
},
{
"answer_id": 9996990,
"author": "Dennis Walter",
"author_id": 741839,
"author_profile": "https://Stackoverflow.com/users/741839",
"pm_score": 0,
"selected": false,
"text": "namespace AspDotNetStorefront\n{\n // This Class is need to override StudioOnlineCommonHelper Methods in a branch\n public class StudioOnlineCommonHelper : StudioOnlineCore.StudioOnlineCommonHelper\n {\n //\n public static new void DoBusinessRulesChecks(Page page)\n {\n StudioOnlineCore.StudioOnlineCommonHelper.DoBusinessRulesChecks(page);\n }\n }\n}\n"
},
{
"answer_id": 12080528,
"author": "Davy8",
"author_id": 23822,
"author_profile": "https://Stackoverflow.com/users/23822",
"pm_score": 4,
"selected": false,
"text": "new public class Base \n{\n //Other stuff\n\n public static void DoSomething()\n {\n Console.WriteLine(\"Base\");\n }\n}\n\npublic class SomeClass : Base\n{\n public new static void DoSomething()\n {\n Console.WriteLine(\"SomeClass\");\n }\n}\npublic class SomeOtherClass : Base\n{\n}\n Base.DoSomething(); //Base\nSomeClass.DoSomething(); //SomeClass\nSomeOtherClass.DoSomething(); //Base\n"
},
{
"answer_id": 40593810,
"author": "Lostblue",
"author_id": 7157935,
"author_profile": "https://Stackoverflow.com/users/7157935",
"pm_score": 2,
"selected": false,
"text": "public abstract class Mother<T> where T : Mother<T>, new()\n{\n public abstract void DoSomething();\n\n public static void Do()\n {\n (new T()).DoSomething();\n }\n\n}\n\npublic class ChildA : Mother<ChildA>\n{\n public override void DoSomething() { /* Your Code */ }\n}\n\npublic class ChildB : Mother<ChildB>\n{\n public override void DoSomething() { /* Your Code */ }\n}\n public class ChildA : Mother<ChildA>\n{\n public override void DoSomething() { Console.WriteLine(\"42\"); }\n}\n\npublic class ChildB : Mother<ChildB>\n{\n public override void DoSomething() { Console.WriteLine(\"12\"); }\n}\n\npublic class Program\n{\n static void Main()\n {\n ChildA.Do(); //42\n ChildB.Do(); //12\n Console.ReadKey();\n }\n}\n"
},
{
"answer_id": 68650904,
"author": "Krauss",
"author_id": 2693399,
"author_profile": "https://Stackoverflow.com/users/2693399",
"pm_score": 0,
"selected": false,
"text": "public class BaseClass{\n public static string GetString(){\n throw new NotSupportedException(); // This is not possible\n }\n}\n\npublic class DerivedClassA : BaseClass {\n public static new string GetString(){\n return \"This is derived class A\";\n }\n}\n\npublic class DerivedClassB : BaseClass {\n public static new string GetString(){\n return \"This is derived class B\";\n }\n}\n\nstatic public void Main(String[] args)\n{\n Console.WriteLine(DerivedClassA.GetString()); // Prints \"This is derived class A\"\n Console.WriteLine(DerivedClassB.GetString()); // Prints \"This is derived class B\"\n Console.WriteLine(BaseClass.GetString()); // Throws NotSupportedException\n}\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
] |
248,273
|
<p>Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.</p>
<p>I am currently working in C#.</p>
|
[
{
"answer_id": 248356,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": false,
"text": "DateTime[] dates = { new DateTime(2008,10,6), new DateTime(2008,10,7)}; //etc....\n\nvar mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday); // = {10/6/2008}\n var datesgrouped = from d in dates\n group d by d.DayOfWeek into grouped\n select new { WeekDay = grouped.Key, Days = grouped };\n\nforeach (var g in datesgrouped)\n{\n Console.Write (String.Format(\"{0} : {1}\", g.WeekDay,g.Days.Count());\n}\n"
},
{
"answer_id": 248359,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 3,
"selected": false,
"text": "DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayOfWeek(Start) <= DayImLookingFor\n+ 1 if DayOfWeek(End) >= DayImLookingFor\n- 1\n DifferenceInDays End - Start DayOfWeek DayOfWeek DayImLookingFor End"
},
{
"answer_id": 248369,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 4,
"selected": false,
"text": " private int CountMondays(DateTime startDate, DateTime endDate)\n {\n int mondayCount = 0;\n\n for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))\n {\n if (dt.DayOfWeek == DayOfWeek.Monday)\n {\n mondayCount++;\n }\n }\n\n return mondayCount;\n }\n dt < endDate.AddDays(1.0)\n"
},
{
"answer_id": 248370,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 1,
"selected": false,
"text": "JD1=JulianDayOf(the_first_date)\nJD2=JulianDayOf(the_second_date)\nRound JD1 up to nearest multiple of 7\nRound JD2 up to nearest multiple of 7\nd = JD2-JD1\nnMondays = (JD2-JD1+7)/7 # integer divide\n"
},
{
"answer_id": 248374,
"author": "Will Rickards",
"author_id": 290835,
"author_profile": "https://Stackoverflow.com/users/290835",
"pm_score": 0,
"selected": false,
"text": " 1 \n 2 ' WorkDays\n 3 ' returns the number of working days between two dates\n 4 Public Function WorkDays(ByVal dtBegin As Date, ByVal dtEnd As Date) As Long\n 5 \n 6 Dim dtFirstSunday As Date\n 7 Dim dtLastSaturday As Date\n 8 Dim lngWorkDays As Long\n 9 \n 10 ' get first sunday in range\n 11 dtFirstSunday = dtBegin + ((8 - Weekday(dtBegin)) Mod 7)\n 12 \n 13 ' get last saturday in range\n 14 dtLastSaturday = dtEnd - (Weekday(dtEnd) Mod 7)\n 15 \n 16 ' get work days between first sunday and last saturday\n 17 lngWorkDays = (((dtLastSaturday - dtFirstSunday) + 1) / 7) * 5\n 18 \n 19 ' if first sunday is not begin date\n 20 If dtFirstSunday <> dtBegin Then\n 21 \n 22 ' assume first sunday is after begin date\n 23 ' add workdays from begin date to first sunday\n 24 lngWorkDays = lngWorkDays + (7 - Weekday(dtBegin))\n 25 \n 26 End If\n 27 \n 28 ' if last saturday is not end date\n 29 If dtLastSaturday <> dtEnd Then\n 30 \n 31 ' assume last saturday is before end date\n 32 ' add workdays from last saturday to end date\n 33 lngWorkDays = lngWorkDays + (Weekday(dtEnd) - 1)\n 34 \n 35 End If\n 36 \n 37 ' return working days\n 38 WorkDays = lngWorkDays\n 39 \n 40 End Function\n"
},
{
"answer_id": 248525,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 7,
"selected": true,
"text": "static int CountDays(DayOfWeek day, DateTime start, DateTime end)\n{\n TimeSpan ts = end - start; // Total duration\n int count = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks\n int remainder = (int)(ts.TotalDays % 7); // Number of remaining days\n int sinceLastDay = (int)(end.DayOfWeek - day); // Number of days since last [day]\n if (sinceLastDay < 0) sinceLastDay += 7; // Adjust for negative days since last [day]\n\n // If the days in excess of an even week are greater than or equal to the number days since the last [day], then count this one, too.\n if (remainder >= sinceLastDay) count++; \n\n return count;\n}\n"
},
{
"answer_id": 248579,
"author": "Paul Osterhout",
"author_id": 30976,
"author_profile": "https://Stackoverflow.com/users/30976",
"pm_score": 0,
"selected": false,
"text": "private System.Int32 CountDaysOfWeek(System.DayOfWeek dayOfWeek, System.DateTime date1, System.DateTime date2)\n{\n System.DateTime EndDate;\n System.DateTime StartDate;\n\n if (date1 > date2)\n {\n StartDate = date2;\n EndDate = date1;\n }\n else\n {\n StartDate = date1;\n EndDate = date2;\n }\n\n while (StartDate.DayOfWeek != dayOfWeek)\n StartDate = StartDate.AddDays(1);\n\n return EndDate.Subtract(StartDate).Days / 7 + 1;\n}\n"
},
{
"answer_id": 1322835,
"author": "Olivier de Rivoyre",
"author_id": 26071,
"author_profile": "https://Stackoverflow.com/users/26071",
"pm_score": 1,
"selected": false,
"text": "DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayOfWeek(Start) <= DayImLookingFor\n+ 1 if DayOfWeek(End) >= DayImLookingFor\n- 1\n DifferenceInDays(Start, End) / 7 // Integer division discarding remainder\n+ 1 if DayImLookingFor is between Start.Day and End.Day \n private int CountDays(DateTime start, DateTime end, DayOfWeek selectedDay)\n{\n if (start.Date > end.Date)\n {\n return 0;\n }\n int totalDays = (int)end.Date.Subtract(start.Date).TotalDays;\n DayOfWeek startDay = start.DayOfWeek;\n DayOfWeek endDay = end.DayOfWeek;\n ///look if endDay appears before or after the selectedDay when we start from startDay.\n int startToEnd = (int)endDay - (int)startDay;\n if (startToEnd < 0)\n {\n startToEnd += 7;\n }\n int startToSelected = (int)selectedDay - (int)startDay;\n if (startToSelected < 0)\n {\n startToSelected += 7;\n }\n bool isSelectedBetweenStartAndEnd = startToEnd >= startToSelected;\n if (isSelectedBetweenStartAndEnd)\n {\n return totalDays / 7 + 1;\n }\n else\n {\n return totalDays / 7;\n }\n}\n"
},
{
"answer_id": 8397382,
"author": "Terje Kvannli",
"author_id": 1081743,
"author_profile": "https://Stackoverflow.com/users/1081743",
"pm_score": 2,
"selected": false,
"text": "public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)\n{\n var selectedDates = new List<DateTime>();\n\n if (startDate >= endDate)\n return selectedDates; //No days to return\n\n if (daysToCheck == null || daysToCheck.Count == 0)\n return selectedDates; //No days to select\n\n try\n {\n //Get the total number of days between the two dates\n var totalDays = (int)endDate.Subtract(startDate).TotalDays;\n\n //So.. we're creating a list of all dates between the two dates:\n var allDatesQry = from d in Enumerable.Range(1, totalDays)\n select new DateTime(\n startDate.AddDays(d).Year,\n startDate.AddDays(d).Month,\n startDate.AddDays(d).Day);\n\n //And extracting those weekdays we explicitly wanted to return\n var selectedDatesQry = from d in allDatesQry\n where daysToCheck.Contains(d.DayOfWeek)\n select d;\n\n //Copying the IEnumerable to a List\n selectedDates = selectedDatesQry.ToList();\n }\n catch (Exception ex)\n {\n //Log error\n //...\n\n //And re-throw\n throw;\n }\n return selectedDates;\n}\n"
},
{
"answer_id": 9026080,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 0,
"selected": false,
"text": "[TestMethod]\npublic void ShouldFindFridaysInTimeSpan()\n{\n //reference: http://stackoverflow.com/questions/248273/count-number-of-mondays-in-a-given-date-range\n\n var spanOfSixtyDays = new TimeSpan(60, 0, 0, 0);\n var setOfDates = new List<DateTime>(spanOfSixtyDays.Days);\n var now = DateTime.Now;\n\n for(int i = 0; i < spanOfSixtyDays.Days; i++)\n {\n setOfDates.Add(now.AddDays(i));\n }\n\n Assert.IsTrue(setOfDates.Count == 60,\n \"The expected number of days is not here.\");\n\n var fridays = setOfDates.Where(i => i.DayOfWeek == DayOfWeek.Friday);\n\n Assert.IsTrue(fridays.Count() > 0,\n \"The expected Friday days are not here.\");\n Assert.IsTrue(fridays.First() == setOfDates.First(i => i.DayOfWeek == DayOfWeek.Friday),\n \"The expected first Friday day is not here.\");\n Assert.IsTrue(fridays.Last() == setOfDates.Last(i => i.DayOfWeek == DayOfWeek.Friday),\n \"The expected last Friday day is not here.\");\n}\n TimeSpan TimeSpan"
},
{
"answer_id": 9418562,
"author": "Peter Morris",
"author_id": 61311,
"author_profile": "https://Stackoverflow.com/users/61311",
"pm_score": 1,
"selected": false,
"text": " int[] CountDays(DateTime firstDate, DateTime lastDate)\n {\n var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;\n var weeks = (int)Math.Floor(totalDays / 7);\n\n var result = Enumerable.Repeat<int>(weeks, 7).ToArray();\n if (totalDays % 7 != 0)\n {\n int firstDayOfWeek = (int)firstDate.DayOfWeek;\n int lastDayOfWeek = (int)lastDate.DayOfWeek;\n if (lastDayOfWeek < firstDayOfWeek)\n lastDayOfWeek += 7;\n for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)\n result[dayOfWeek % 7]++;\n }\n return result;\n }\n public static Dictionary<DayOfWeek, int> TotalDaysOfWeeks(this DateTime firstDate, DateTime lastDate)\n {\n var totalDays = lastDate.Date.Subtract(firstDate.Date).TotalDays + 1;\n var weeks = (int)Math.Floor(totalDays / 7);\n\n var resultArray = Enumerable.Repeat<int>(weeks, 7).ToArray();\n if (totalDays % 7 != 0)\n {\n int firstDayOfWeek = (int)firstDate.DayOfWeek;\n int lastDayOfWeek = (int)lastDate.DayOfWeek;\n if (lastDayOfWeek < firstDayOfWeek)\n lastDayOfWeek += 7;\n for (int dayOfWeek = firstDayOfWeek; dayOfWeek <= lastDayOfWeek; dayOfWeek++)\n resultArray[dayOfWeek % 7]++;\n }\n var result = new Dictionary<DayOfWeek, int>();\n for (int dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++)\n result[(DayOfWeek)dayOfWeek] = resultArray[dayOfWeek];\n return result;\n }\n"
},
{
"answer_id": 56919715,
"author": "Monzur",
"author_id": 1331294,
"author_profile": "https://Stackoverflow.com/users/1331294",
"pm_score": 1,
"selected": false,
"text": " private int CountDays(DayOfWeek day, DateTime startDate, DateTime endDate)\n {\n int dayCount = 0;\n\n for (DateTime dt = startDate; dt < endDate; dt = dt.AddDays(1.0))\n {\n if (dt.DayOfWeek == day)\n {\n dayCount++;\n }\n }\n\n return dayCount;\n }\n int Days = CountDays(DayOfWeek.Friday, Convert.ToDateTime(\"2019-07-04\"), \n Convert.ToDateTime(\"2019-07-27\")).ToString();\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32552/"
] |
248,297
|
<p>Suppose <code>xmlNode</code> is a XML DOM node, how do you get its XML system independently? </p>
<p>For IE, it is <code>xmlNode.xml;</code></p>
<p>For Netscape, it is <code>new XMLSerializer().serializeToString(xmlNode)</code>. </p>
<p>In jQuery, is there any built-in method I can leverage?</p>
|
[
{
"answer_id": 312146,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 0,
"selected": false,
"text": "$(xmlNode).html();\n"
},
{
"answer_id": 623982,
"author": "acrosman",
"author_id": 24215,
"author_profile": "https://Stackoverflow.com/users/24215",
"pm_score": 0,
"selected": false,
"text": "var xmlContent = $(xmlNode)\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
248,312
|
<p>Two table:</p>
<pre><code>StoreInfo:
UserId uniqueidentifier
StoreNo nvarchar
UserName nvarchar
Password nvarchar
UserInfo:
UserId uniqueidentifier
UserName nvarchar
Password nvarchar
</code></pre>
<p>the UserId on StoreInfo is currently null. How do i update StoreInfo's UserId with UserInfo's UserId based on StoreInfo's UserName and Password is match to the UserName and Password from UserInfo. </p>
<p>the following is the query that i wrote which update the entire UserId in StoreInfo with the first UserId from UserInfo so i know it's wrong.</p>
<pre><code>declare @UserName nvarchar(255)
declare @Password nvarchar(25)
declare @UserId uniqueidentifier
select @UserName = UserName, @Password = Password, @UserId = UserId
from UserInfo
select UserId, Password
from FranchiseInfo
where UserID = @UserName and Password = @Password
update FranchiseInfo
set UserI = @UserId
</code></pre>
|
[
{
"answer_id": 248323,
"author": "Philip Kelley",
"author_id": 7491,
"author_profile": "https://Stackoverflow.com/users/7491",
"pm_score": 0,
"selected": false,
"text": "UPDATE StoreInfo\n set UserId = ui.UserId\n from StoreInfo si\n inner join UserInfo ui\n on ui.UserName = si.UserName\n and ui.Password = si.Password\n where si.UserId is null\n"
},
{
"answer_id": 248324,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "update storeinfo\nset userid = u.userid\nfrom userinfo u \ninner join storeinfo s on (s.username = u.username and s.password = u.password)\nwhere userid is null\n"
},
{
"answer_id": 248326,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 0,
"selected": false,
"text": "UPDATE ... FROM UPDATE StoreInfo\nSET\n UserId = ui.UserId\nFROM\n StoreInfo si\n INNER JOIN UserInfo ui ON ui.UserName = si.UserName AND ui.Password = si.Password;\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28647/"
] |
248,315
|
<p>I have a simple Flex application that is a panel with a repeater inside of it; albeit a little simplified, it is like such:</p>
<pre>
<code>
<mx:Panel id="pnl">
<mx:Repeater id="rp">
<mx:Label text = "foo" />
</mx:Repeater>
</mx:Panel>
</code>
</pre>
<p>I am then embedding this Flex application into an HTML wrapper. I am then attempting to dynamically re size the embedded Flash object in the HTML as the Flex panel changes size (thus allowing the Flex application to consume as much of the HTML page as it needs). </p>
<p>I am doing this by doing the following actionscipt:</p>
<p><pre>
<code>
pnl.addEventListener(ResizeEvent.RESIZE,function(event:Event):void {
ExternalInterface.call("resize",event.target.height);
});
</code>
</pre>which in turn calls this javascript function:</p>
<pre>
<code>
function resize(height) {
// the embed or object that contains the flex app
var e = document.getElementById('flex_object');
if(e) e.height = height;
}
</code>
</pre>
<p>This seems to work perfect in IE, however I get strange results in Firefox / Safari, the repeater works for <em>n</em> number of times, and then the text seems to get cut off / disappear in the repeater, see the attached image:
<a href="http://img528.imageshack.us/img528/9538/rpre0.jpg" rel="nofollow noreferrer">alt text http://img528.imageshack.us/img528/9538/rpre0.jpg</a></p>
<p>Can anyone explain why this is happening, and if there are any workarounds / ways of doing the same thing?</p>
|
[
{
"answer_id": 264222,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 0,
"selected": false,
"text": "DIV DIV"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
248,320
|
<p>I have some HTML that looks like this:</p>
<pre><code><ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
</code></pre>
<p>Using CSS I'm setting the <code>p</code> tag to <code>display:none;</code>. I want to use jQuery to display or hide the <code>p</code> tag when the <code>anchor</code> is clicked, but I'm having some troubles with the sibling selector. </p>
<p>Just trying to get the selector working, I tried:</p>
<pre><code>$("a.question").click(function () {
$(this + " ~ p").css("background-color", "red");
});
</code></pre>
<p>to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen. </p>
|
[
{
"answer_id": 248331,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 4,
"selected": false,
"text": "$(this).next(\"p\").css(\"...\")\n"
},
{
"answer_id": 248335,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 6,
"selected": true,
"text": "$(this).siblings('p').css()\n"
},
{
"answer_id": 248347,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 3,
"selected": false,
"text": " $(\"a.question\").click(function (event) {\n $(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element\n event.preventDefault(); //stop the browser from following the link\n }); \n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4106/"
] |
248,332
|
<p>I have this large C++ project that I need to build on a platform that does not have a parallel make (like make -j on Linux). The server has 6 CPU's and I want to do a parallel build manually. </p>
<p>I can generate a task list like this for about 300 object files. I use the Makefile for the dependency checks and incremental build:</p>
<p>make -f Makefile obj1.o</p>
<p>make -f Makefile obj2.o</p>
<p>make -f Makefile obj3.o
...</p>
<p>How would I execute these tasks in parallel with no more then 6 tasks running at a time using Ksh and Perl? (Java or Python are not available :-( )</p>
|
[
{
"answer_id": 248365,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": -1,
"selected": false,
"text": "make -f Makefile obj1.o &\nmake -f Makefile obj2.o &\n...\nmake -f Makefile objn.o &\n &&"
},
{
"answer_id": 248447,
"author": "mpeters",
"author_id": 12094,
"author_profile": "https://Stackoverflow.com/users/12094",
"pm_score": 4,
"selected": true,
"text": "my @make_obj = qw(\n obj1.o\n obj2.o\n obj3.o\n ...\n);\n\nmy $fm = $pm = new Parallel::ForkManager(6);\nforeach my $obj (@make_obj) {\n $fm->start and next;\n system(\"make -f Makefile $make_obj\");\n $fm->finish();\n}\n"
},
{
"answer_id": 248890,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 2,
"selected": false,
"text": "use threads;\n\nmy $max_threads = 5;\n\nmy @targets = qw(obj1.o obj2.o obj3.o ...);\nwhile(@targets) {\n my $num_threads = threads->list(threads::running);\n if( $num_threads < $max_threads ) {\n my $target = shift @targets;\n threads->create(sub { return system \"make $target\" });\n }\n}\n"
},
{
"answer_id": 19799409,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 1,
"selected": false,
"text": "parallel -j6 make -f Makefile obj{}.o ::: {1..500}\n (wget -O - pi.dk/3 || curl pi.dk/3/ || fetch -o - http://pi.dk/3) | bash\n"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7743/"
] |
248,340
|
<p>I have some configuration values for an asp.net web app. They will be maintained by a system admin once the system goes live. Should I store these values in the database or in a config file? Is there a best practice for this sort of thing?</p>
|
[
{
"answer_id": 599139,
"author": "Protagonist",
"author_id": 460006,
"author_profile": "https://Stackoverflow.com/users/460006",
"pm_score": 0,
"selected": false,
"text": ".ini Setting"
}
] |
2008/10/29
|
[
"https://Stackoverflow.com/questions/248340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24908/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.