qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
177,558
|
<p>Something like this is on my mind: I put one or a few strings in, and the algorithm shows me a matching regex.</p>
<p>Is there an "<em>easy</em>" way to do this, or does something like this already exist?</p>
<p><strong><em>Edit 1</em></strong>: Yes, I'm trying to find a way to generate regex. </p>
<p><strong><em>Edit 2</em></strong>: Regulazy is not what I am looking for. The common use for the code I want is to find a correct RegEx; for example, article numbers:<br/></p>
<ul>
<li>I put in <em>123456</em>, the regex should be <code>\d{6}</code></li>
<li>I put in <em>nb-123456</em>, the regex should be <code>\w{2}-\d{6}</code></li>
</ul>
|
[
{
"answer_id": 177592,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "regexp-opt (regexp-opt (list \"my\" \"list\" \"of\" \"some\" \"strings\" \"to\" \"search\"))\n \"list\\\\|my\\\\|of\\\\|s\\\\(?:earch\\\\|ome\\\\|trings\\\\)\\\\|to\"\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25730/"
] |
177,559
|
<p>This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this?</p>
<p>EDIT: And as the tags might indicate, this is on Win32 using C++.</p>
|
[
{
"answer_id": 177571,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "CreateProcess"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177559",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25731/"
] |
177,569
|
<p>I have Eclipse 3.3.2 with PDT doing PHP development.
All projects that I create, even SVN projects have code completion.
Now I just opened another SVN project and it has no code completion or PHP templates (CTRL-space does nothing in that project).
However, I can open the other projects and code completion all work in them.</p>
<p>Why would code completion and templates be "off" in just one project and how can I turn it back on?</p>
|
[
{
"answer_id": 177601,
"author": "Guido",
"author_id": 12388,
"author_profile": "https://Stackoverflow.com/users/12388",
"pm_score": 6,
"selected": true,
"text": " <natures>\n <nature>org.eclipse.php.core.PHPNature</nature>\n </natures>\n"
},
{
"answer_id": 178097,
"author": "powtac",
"author_id": 22470,
"author_profile": "https://Stackoverflow.com/users/22470",
"pm_score": -1,
"selected": false,
"text": "if(false) {\n require_once 'class/one.php';\n require_once 'class/two.php';\n require_once 'class/three.php';\n}\n"
},
{
"answer_id": 897349,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<buildpathentry kind=\"con\" path=\"org.eclipse.php.core.LANGUAGE\"/>"
},
{
"answer_id": 2100178,
"author": "lagopixel",
"author_id": 254732,
"author_profile": "https://Stackoverflow.com/users/254732",
"pm_score": 3,
"selected": false,
"text": "---\n <natures>\n </natures>\n---\n ---\n <natures>\n <nature>org.eclipse.php.core.PHPNature</nature>\n </natures>\n---\n"
},
{
"answer_id": 5350018,
"author": "umpirsky",
"author_id": 177056,
"author_profile": "https://Stackoverflow.com/users/177056",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><buildpath>\n<buildpathentry kind=\"src\" path=\"\"/>\n<buildpathentry kind=\"con\" path=\"org.eclipse.php.core.LANGUAGE\"/></buildpath>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
177,606
|
<p>I am running windows XP with ruby 1.8.6 patchlevel 111. I am using HTTP to connect to a remote server and it has been running fine. All of a sudden it started to through the exception listed below (I did not change any code since the last time I ran it successfully). Does anybody know what is going on?</p>
<pre>
c:/ruby/lib/ruby/1.8/timeout.rb:54:in `rbuf_fill': execution expired (Timeout::E
rror)
from c:/ruby/lib/ruby/1.8/timeout.rb:56:in `timeout'
from c:/ruby/lib/ruby/1.8/timeout.rb:76:in `timeout'
from c:/ruby/lib/ruby/1.8/net/protocol.rb:132:in `rbuf_fill'
from c:/ruby/lib/ruby/1.8/net/protocol.rb:116:in `readuntil'
from c:/ruby/lib/ruby/1.8/net/protocol.rb:126:in `readline'
from c:/ruby/lib/ruby/1.8/net/http.rb:2029:in `read_status_line'
from c:/ruby/lib/ruby/1.8/net/http.rb:2018:in `read_new'
from c:/ruby/lib/ruby/1.8/net/http.rb:1059:in `request'
... 19 levels...
from c:/ruby/lib/ruby/1.8/test/unit/autorunner.rb:216:in `run'
from c:/ruby/lib/ruby/1.8/test/unit/autorunner.rb:12:in `run'
from c:/ruby/lib/ruby/1.8/test/unit.rb:278
from c:/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
.rb:5
rake aborted!
Command failed with status (3): [c:/ruby/bin/ruby -Ilib;test "c:/ruby/lib/r...]
</pre>
|
[
{
"answer_id": 5054097,
"author": "Brian Armstrong",
"author_id": 76486,
"author_profile": "https://Stackoverflow.com/users/76486",
"pm_score": 0,
"selected": false,
"text": "rescue Timeout::Error => e"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
177,611
|
<p>I am creating an Eclipse RCP application.</p>
<p>I am following Joel's advice in the following article "Daily Builds are your friend":</p>
<p><a href="http://www.joelonsoftware.com/articles/fog0000000023.html" rel="nofollow noreferrer">http://www.joelonsoftware.com/articles/fog0000000023.html</a></p>
<p>So, I've written a nice build script that creates an Eclipse RCP product and that runs unit tests on the code. All results are then distributed to the developer's list (after some grumbling). Now my next step, I want it to create the setup package that I normally create manually using the inno setup compiler.</p>
<p>The question is, how would I get around creating this package automatically? I guess I can generate the inno setup file automatically from ant, and then invoke the compiler from the command line, but I don't know if this is possible.</p>
<p>Any tips for this task? Maybe any other setup application that can be used from ant?</p>
|
[
{
"answer_id": 178237,
"author": "Tom",
"author_id": 20979,
"author_profile": "https://Stackoverflow.com/users/20979",
"pm_score": 4,
"selected": true,
"text": "#include \"settings.txt\"\n #define myver=xxx.xxx\n#define tags\n <exec dir=\".\" executable=\"cmd\" os=\"Windows NT\">\n <arg line=\"/c build.bat\"/>\n</exec>\n set isxpath=\"c:\\program files\\inno setup 5\"\nset isx=%isxpath%\\iscc.exe\nset iwz=myproj.iss\nif not exist %isx% set errormsg=%isx% not found && goto errorhandler\n%isx% \"%iwz%\" /O\"%buildpath%\" /F\"MySetupper.exe\" >>%logfile%\ngoto :eof\n"
},
{
"answer_id": 290148,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 3,
"selected": false,
"text": "GetFileVersion settings.txt #define AppName \"My App\"\n#define SrcApp \"MyApp.exe\"\n#define FileVerStr GetFileVersion(SrcApp)\n#define StripBuild(str VerStr) Copy(VerStr, 1, RPos(\".\", VerStr)-1)\n#define AppVerStr StripBuild(FileVerStr)\n\n[Setup]\nAppName={#AppName}\nAppVersion={#AppVerStr}\nAppVerName={#AppName} {#AppVerStr}\nUninstallDisplayName={#AppName} {#AppVerStr}\nVersionInfoVersion={#FileVerStr}\nVersionInfoTextVersion={#AppVerStr}\nOutputBaseFilename=MyApp-{#FileVerStr}-setup\n /d iscc.exe /dSpecialEdition ...\n ifdef [Registry]\n#ifdef SpecialEdition\nRoot: HKLM; Subkey: Software\\MyCompany\\MyApp; ValueName: SpecialEdition; ValueType: dword; ValueData: 1 ...\n#endif\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2309/"
] |
177,613
|
<p>My <code>Account</code> model has the following two associations:</p>
<pre><code>has_many :expenses,
:order => 'expenses.dated_on DESC',
:dependent => :destroy
has_many :recent_expenses,
:class_name => 'Expense',
:conditions => "expenses.dated_on <= '#{Date.today}'",
:order => 'dated_on DESC',
:limit => 5
</code></pre>
<p>In one of my views I'm rendering recent expenses like so:</p>
<pre><code><% @account.recent_expenses.each do |expense| %>
...
<% end %>
</code></pre>
<p>On my development machine, on the staging server (which runs in production mode) and also on the production console, <code>@account.recent_expenses</code> returns the correct list. However, on our live production server, the most recent expenses are not returned. </p>
<p>If I replace <code>@account.recent_expenses</code> with <code>@account.expenses</code> in the view, the most recent expenses <em>are</em> displayed, so my guess is that the <code>#{Date.today}</code> part of the conditions clause is somehow being cached the first time it is executed. If I restart the production Mongrel cluster, all the latest expenses are returned correctly.</p>
<p>Can anyone think why this would occur and how might I change the <code>:recent_expenses</code> query to prevent this from happening?</p>
<p>I'm using Rails 2.1.0.</p>
|
[
{
"answer_id": 177794,
"author": "Andrew",
"author_id": 17408,
"author_profile": "https://Stackoverflow.com/users/17408",
"pm_score": 4,
"selected": true,
"text": "named_scope :recent, lambda { {:conditions => [\"expenses.dated_on <= ?\", Date.today], :order => 'dated_on DESC', :limit => 5 } }\n has_many :recent_expenses ...\n <% @account.expenses.recent.each do |expense| %>\n...\n<% end %>\n"
},
{
"answer_id": 177806,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 2,
"selected": false,
"text": "def self.recent\n find(:all, :conditions => ['dated_on <= ?', Date.today], :limit => 5, :order => 'dated_on DESC')\nend\n"
},
{
"answer_id": 4693009,
"author": "johnmcaliley",
"author_id": 378044,
"author_profile": "https://Stackoverflow.com/users/378044",
"pm_score": 1,
"selected": false,
"text": "scope :recent, lambda { where(\"expenses.dated_on <= ?\", Date.today).order('dated_on DESC').limit(5) }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174/"
] |
177,638
|
<p>I had a little discussion with a friend about the usage of collections in return/input values of a method. He told me that we have to use
- the most derived type for return values.
- the least derived type for input parameters.</p>
<p>So, it means that, for example, a method has to get a ReadOnlyCollection as parameter, and as return a List.</p>
<p>Moreover, he said that we must not use List or Dictionary in publics API, and that we have to use, instead Collection, ReadOnlyCollection, ... So, in the case where a method is public, its parameters and its return values must be Collection, ReadOnlyCollection, ...</p>
<p>Is it right ?</p>
|
[
{
"answer_id": 177647,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 4,
"selected": true,
"text": "public void ProcessCustomers(IEnumerable<Customer> customers)\n{\n ... implementation ...\n}\n private IEnumerable<Customer> GetCustomersByCountryCode(IEnumerable<Customer> customers, int countryCode)\n{\n foreach(Customer c in customers)\n {\n if (c.CountryCode == countryCode) yield return c;\n }\n}\n\n... \nProcessCustomers(GetCustomersByCountryCode(myCustomers, myCountryCode);\n...\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12703/"
] |
177,673
|
<p>I have a strongly-typed MVC View Control which is responsible for the UI where users can create and edit Client items. I'd like them to be able to define the <code>ClientId</code> on creation, but not edit, and this to be reflected in the UI.</p>
<p>To this end, I have the following line:</p>
<pre><code><%= Html.TextBox("Client.ClientId", ViewData.Model.ClientId, new
{ @readonly =
(ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0
? "readonly" : "false")
} )
%>
</code></pre>
<p>It seems that no matter what value I give the readonly attribute (even "false" and ""), Firefox and IE7 make the input read-only, which is annoyingly counter-intuitive. Is there a nice, ternary-operator-based way to drop the attribute completely if it is not required?</p>
|
[
{
"answer_id": 178024,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 6,
"selected": true,
"text": "readonly <%= Html.TextBox(\"Client.ClientId\", ViewData.Model.ClientId, \n ViewData.Model.ClientId != null && ViewData.Model.ClientId.Length > 0 \n ? new { @readonly = \"readonly\" } \n : null) \n%>\n ClientId.Length > 0 \n ? (object)new { @readonly = \"readonly\", @class = \"myCSS\" } \n : (object)new { @class = \"myCSS\" }\n"
},
{
"answer_id": 178047,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 2,
"selected": false,
"text": "<input type=\"checkbox\" name=\"roles\" value='<%# Eval(\"Name\") %>' \n <%# ((bool) Eval(\"InRole\")) ? \"checked\" : \"\" %> \n <%# ViewData.Model.IsInRole(\"Admin\") ? \"\" : \"disabled\" %> />\n"
},
{
"answer_id": 340179,
"author": "Olaj",
"author_id": 40609,
"author_profile": "https://Stackoverflow.com/users/40609",
"pm_score": 1,
"selected": false,
"text": "<%= ((bool) Eval(\"InRole\")) ? \"checked\" : \"\" %> \n <%# ((bool) Eval(\"InRole\")) ? \"checked\" : \"\" %> \n"
},
{
"answer_id": 13817483,
"author": "Aviko",
"author_id": 1544054,
"author_profile": "https://Stackoverflow.com/users/1544054",
"pm_score": 5,
"selected": false,
"text": "Dictionary<string, object> htmlAttributes = new Dictionary<string, object>();\nhtmlAttributes.Add(\"class\", \"myCSS\");\nhtmlAttributes.Add(\"data-attr1\", \"val1\");\nhtmlAttributes.Add(\"data-attr2\", \"val2\");\nif (Model.LoggedInData.IsAdmin == false)\n{\n htmlAttributes.Add(\"readonly\", \"readonly\");\n}\n\n\n@:User: @Html.TextBoxFor(\n m => m.User,\n htmlAttributes) \n"
},
{
"answer_id": 24056129,
"author": "cronixis",
"author_id": 3203334,
"author_profile": "https://Stackoverflow.com/users/3203334",
"pm_score": -1,
"selected": false,
"text": "@Html.TextBoxFor(m => m.Email, !isEdit ? new { id = \"email_box\" } : new { id = \"email_box\", @readonly = isEdit ? \"readonly\" : \"false\" } as object)\n"
},
{
"answer_id": 33865092,
"author": "pranavn",
"author_id": 2882025,
"author_profile": "https://Stackoverflow.com/users/2882025",
"pm_score": 3,
"selected": false,
"text": "@Html.TextBoxFor(x => x.Name, isReadonly ?(object) new { @readonly = true } : new { /*Some other attributes*/ })\n"
},
{
"answer_id": 43881425,
"author": "cristian gonzalez",
"author_id": 6946357,
"author_profile": "https://Stackoverflow.com/users/6946357",
"pm_score": 1,
"selected": false,
"text": " @Html.TextAreaFor(model => model.ComentarioGestor, comentarioGestor? new { @class = \"form-control\" } : new { @class = \"form-control\", @readonly = \"readonly\" } as object)\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
177,677
|
<p>I am trying to uncompress some data created in VB6 using the zlib API.</p>
<p>I have read this is possible with the qUncompress function:
<a href="http://doc.trolltech.com/4.4/qbytearray.html#qUncompress" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/qbytearray.html#qUncompress</a></p>
<p>I have read the data in from QDataStream via readRawBytes into a char
array, which I then converted to a QByteArray for decompression. I
have the compressed length and the expected decompressed length but am not getting
anything back from qUncompress.</p>
<p>However I need to prepend the expected decompressed length in big endian format. Has anybody done this and have an example?</p>
|
[
{
"answer_id": 177793,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 3,
"selected": true,
"text": "qArr(1) = int(Size/(256*256*256))\nqArr(2) = 255 And int(Size/256*256)\nqArr(3) = 255 And int(Size/256)\nqArr(4) = 255 And int(Size)\n"
},
{
"answer_id": 177876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "//int length;\nbyte[] bigEndianBytes = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(length))\n //byte[] bigEndianBytes;\nint length = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bigEndianBytes))\n"
},
{
"answer_id": 178285,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 1,
"selected": false,
"text": "Private Type LongByte\n H1 As Byte\n H2 As Byte\n L1 As Byte\n L2 As Byte\nEnd Type\n\nPrivate Type LongType\n L As Long\nEnd Type\n\nFunction SwapEndian(ByVal LongData as Long) as Long\n Dim TempL As LongType\n Dim TempLB As LongByte\n Dim TempVar As Long\n\n TempL.L = LongData\n LSet TempLB = TempL\n'Swap is a subroutine I wrote to swap two variables\n Swap TempLB.H1, TempLB.L2\n Swap TempLB.H2, TempLB.L1\n LSet TempL = TempLB\n TempVar = TempL.L\n\n SwapEndian = TempVar\nEnd Function\n Private Structure Int32Byte\n Public H1 As Byte\n Public H2 As Byte\n Public L1 As Byte\n Public L2 As Byte\n Public Function Convert() As Integer\n Dim M As New MemoryStream()\n Dim bR As IO.BinaryReader\n Dim bW As New IO.BinaryWriter(M)\n Swap(H1, L2)\n Swap(H2, L1)\n bW.Write(H1)\n bW.Write(H2)\n bW.Write(L1)\n bW.Write(L2)\n M.Seek(0, SeekOrigin.Begin)\n bR = New IO.BinaryReader(M)\n Convert = bR.ReadInt32()\n End Function\nEnd Structure\n"
},
{
"answer_id": 178319,
"author": "David Dibben",
"author_id": 5022,
"author_profile": "https://Stackoverflow.com/users/5022",
"pm_score": 0,
"selected": false,
"text": "bazip[0] = (nbytes & 0xff000000) >> 24;\nbazip[1] = (nbytes & 0x00ff0000) >> 16;\nbazip[2] = (nbytes & 0x0000ff00) >> 8;\nbazip[3] = (nbytes & 0x000000ff);\n baunzip.resize(len);\nres = ::uncompress((uchar*)baunzip.data(), &len,\n (uchar*)data+4, nbytes-4);\n"
},
{
"answer_id": 178995,
"author": "Phil Hannent",
"author_id": 24459,
"author_profile": "https://Stackoverflow.com/users/24459",
"pm_score": 0,
"selected": false,
"text": " char slideStr[currentCompressedLen];\n int slideByteRead = in.readRawData(slideStr, currentCompressedLen);\n QByteArray aInCompBytes = QByteArray(slideStr, slideByteRead);\n aInCompBytesPlusLen = aInCompBytes;\n aInCompBytesPlusLen.prepend(QByteArray::number(currentUnCompressedLen));\n aInUnCompBytes.resize(currentUnCompressedLen);\n aInUnCompBytes = qUncompress(aInCompBytesPlusLen);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
] |
177,717
|
<p>Please share you experiences regarding how you localized your WPF applications to support multiple languages and any resources that helped you in it?</p>
<p>Thanks for your feedbacks.</p>
|
[
{
"answer_id": 640277,
"author": "Robert Macnee",
"author_id": 19273,
"author_profile": "https://Stackoverflow.com/users/19273",
"pm_score": 2,
"selected": false,
"text": "ResourceDictionary <Button Content=\"{StaticResource Strings.FooDialog.BarButtonText}\"/>\n ResourceDictionary <sys:String x:Key=\"Strings.FooDialog.BarButtonText\">Bar!</sys:String>\n ResourceDictionary Application.Resources private static void LoadLocalizedStrings(CultureInfo uiCulture)\n{\n ResourceDictionary stringsResourceDictionary = new ResourceDictionary();\n stringsResourceDictionary.Source = new Uri(@\"pack://application:,,,/Resources/Strings/\" + uiCulture.Name + \".xaml\");\n Application.Current.Resources.MergedDictionaries.Add(stringsResourceDictionary);\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
177,719
|
<p>I'm trying to get a case-insensitive search with two strings in JavaScript working.</p>
<p>Normally it would be like this:</p>
<pre><code>var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
</code></pre>
<p>The <code>/i</code> flag would be for case-insensitive.</p>
<p>But I need to search for a second string; without the flag it works perfect:</p>
<pre><code>var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
</code></pre>
<p>If I add the <code>/i</code> flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):</p>
<pre><code>var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
</code></pre>
<p>How can I achieve this?</p>
|
[
{
"answer_id": 177724,
"author": "Dan",
"author_id": 17121,
"author_profile": "https://Stackoverflow.com/users/17121",
"pm_score": 10,
"selected": true,
"text": ".match .search .match var string = \"Stackoverflow is the BEST\";\nvar result = string.match(/best/i);\n// result == 'BEST';\n\nif (result){\n alert('Matched');\n}\n indexOf matchString = 'best';\n// If the match string is coming from user input you could do\n// matchString = userInput.toLowerCase() here.\n\nif (string.toLowerCase().indexOf(matchString) != -1){\n alert('Matched');\n}\n"
},
{
"answer_id": 177775,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 8,
"selected": false,
"text": "var result= string.search(/searchstring/i);\n var result= string.search(new RegExp(searchstring, \"i\"));\n"
},
{
"answer_id": 178383,
"author": "Odilon Redo",
"author_id": 21166,
"author_profile": "https://Stackoverflow.com/users/21166",
"pm_score": 5,
"selected": false,
"text": "indexOf() indexOf() var string=\"Stackoverflow is the BEST\"; \nvar searchstring=\"best\";\n\n// lowercase both strings\nvar lcString=string.toLowerCase();\nvar lcSearchString=searchstring.toLowerCase();\n\nvar result = lcString.indexOf(lcSearchString)>=0;\nalert(result);\n var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;\n"
},
{
"answer_id": 27272159,
"author": "Ago",
"author_id": 2448897,
"author_profile": "https://Stackoverflow.com/users/2448897",
"pm_score": -1,
"selected": false,
"text": "var $local_source = [{\n value: 1,\n label: \"c++\"\n }, {\n value: 2,\n label: \"java\"\n }, {\n value: 3,\n label: \"php\"\n }, {\n value: 4,\n label: \"coldfusion\"\n }, {\n value: 5,\n label: \"javascript\"\n }, {\n value: 6,\n label: \"asp\"\n }, {\n value: 7,\n label: \"ruby\"\n }];\n $('#search-fld').autocomplete({\n source: $local_source,\n select: function (event, ui) {\n $(\"#search-fld\").val(ui.item.label); // display the selected text\n $(\"#search-fldID\").val(ui.item.value); // save selected id to hidden input\n return false;\n },\n change: function( event, ui ) {\n\n var isInArray = false;\n\n $local_source.forEach(function(element, index){\n\n if ($(\"#search-fld\").val().toUpperCase() == element.label.toUpperCase()) {\n isInArray = true;\n $(\"#search-fld\").val(element.label); // display the selected text\n $(\"#search-fldID\").val(element.value); // save selected id to hidden input\n console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value);\n };\n\n });\n\n if(!isInArray){\n\n $(\"#search-fld\").val(''); // display the selected text\n $( \"#search-fldID\" ).val( ui.item? ui.item.value : 0 );\n\n }\n } \n"
},
{
"answer_id": 31001303,
"author": "Sohail Arif",
"author_id": 4677755,
"author_profile": "https://Stackoverflow.com/users/4677755",
"pm_score": 1,
"selected": false,
"text": "=== <!doctype html>\n<html>\n\n<head>\n <script>\n // 1st way\n\n var a = \"apple\";\n var b = \"APPLE\";\n if (a.toUpperCase() === b.toUpperCase()) {\n alert(\"equal\");\n }\n\n //2nd way\n\n var a = \" Null and void\";\n document.write(a.search(/null/i));\n </script>\n</head>\n\n</html>"
},
{
"answer_id": 38151393,
"author": "Chris Chute",
"author_id": 3095845,
"author_profile": "https://Stackoverflow.com/users/3095845",
"pm_score": 5,
"selected": false,
"text": "needle haystack string.toUpperCase string.toLowerCase var needleRegExp = new RegExp(needle, \"i\"); needleRegExp.test(haystack) needle needle needle.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\"); needle haystack \"^\" \"$\" var haystack = \"A. BAIL. Of. Hay.\";\nvar needle = \"bail.\";\nvar needleRegExp = new RegExp(needle.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g, \"\\\\$&\"), \"i\");\nvar result = needleRegExp.test(haystack);\nalert(result);\n"
},
{
"answer_id": 38318366,
"author": "Kind Contributor",
"author_id": 887092,
"author_profile": "https://Stackoverflow.com/users/887092",
"pm_score": 2,
"selected": false,
"text": "var haystack = 'A. BAIL. Of. Hay.';\nvar needle = 'bail.';\nvar index = haystack.naturalIndexOf(needle);\n"
},
{
"answer_id": 50080484,
"author": "Andrew",
"author_id": 2079831,
"author_profile": "https://Stackoverflow.com/users/2079831",
"pm_score": 3,
"selected": false,
"text": "let string=\"Stackoverflow is the BEST\";\nlet searchstring=\"best\";\n\n\nlet found = string.toLowerCase()\n .includes(searchstring.toLowerCase());\n includes() true searchString false"
},
{
"answer_id": 51799980,
"author": "Steven Spungin",
"author_id": 5093961,
"author_profile": "https://Stackoverflow.com/users/5093961",
"pm_score": 1,
"selected": false,
"text": "myString.containsIgnoreCase('red','orange','yellow')\n /**\n * @param {...string} var_strings Strings to search for\n * @return {boolean} true if ANY of the arguments is contained in the string\n */\nString.prototype.containsIgnoreCase = function(var_strings) {\n const thisLowerCase = this.toLowerCase()\n for (let i = 0; i < arguments.length; i++) {\n let needle = arguments[i]\n if (thisLowerCase.indexOf(needle.toLowerCase()) >= 0) {\n return true\n }\n }\n return false\n}\n\n/**\n * @param {...string} var_strings Strings to search for\n * @return {boolean} true if ALL of the arguments are contained in the string\n */\nString.prototype.containsAllIgnoreCase = function(var_strings) {\n const thisLowerCase = this.toLowerCase()\n for (let i = 0; i < arguments.length; i++) {\n let needle = arguments[i]\n if (thisLowerCase.indexOf(needle.toLowerCase()) === -1) {\n return false\n }\n }\n return true\n}\n\n// Unit test\n\nlet content = `\nFIRST SECOND\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\n\"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.\"\nFOO BAR\n`\n\nlet data = [\n 'foo',\n 'Foo',\n 'foobar',\n 'barfoo',\n 'first',\n 'second'\n]\n\nlet result\ndata.forEach(item => {\n console.log('Searching for', item)\n result = content.containsIgnoreCase(item)\n console.log(result ? 'Found' : 'Not Found')\n})\n\nconsole.log('Searching for', 'x, y, foo')\nresult = content.containsIgnoreCase('x', 'y', 'foo');\nconsole.log(result ? 'Found' : 'Not Found')\n\nconsole.log('Searching for all', 'foo, bar, foobar')\nresult = content.containsAllIgnoreCase('foo', 'bar', 'foobar');\nconsole.log(result ? 'Found' : 'Not Found')\n\nconsole.log('Searching for all', 'foo, bar')\nresult = content.containsAllIgnoreCase('foo', 'bar');\nconsole.log(result ? 'Found' : 'Not Found')"
},
{
"answer_id": 54416115,
"author": "Robbert",
"author_id": 10414516,
"author_profile": "https://Stackoverflow.com/users/10414516",
"pm_score": 0,
"selected": false,
"text": "var string=\"Stackoverflow is the BEST\";\nvar searchstring=\"best\";\nvar result= (string.toLowerCase()).search((searchstring.toLowerCase()));\nalert(result);\n"
},
{
"answer_id": 67195629,
"author": "Yogaraj K L",
"author_id": 12056822,
"author_profile": "https://Stackoverflow.com/users/12056822",
"pm_score": 0,
"selected": false,
"text": " var result = string.toLowerCase().match(searchstring) \n var result= string.search(new RegExp(searchstring, \"i\"));\n var result = string.match(new RegExp(searchstring, \"i\"));\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25741/"
] |
177,722
|
<p>Perl has several built-in functions for accessing /etc/passwd on Unix systems (and elsewhere when supported) for user and group information. For instance,</p>
<pre><code>my $name = getpwuid($uid);
</code></pre>
<p>will return the user name given the user ID, or undef if there is no such user.</p>
<p>If a Perl script needs to be portable and run on Unices and Windows, how should one access user and group information? ActivePerl seems to support User::grent and User::pwent modules, which provide by-field access to /etc/passwd -- even in Windows. Curiously they do not support the built-in functions getpw* and getgr*. What other alternatives are there?</p>
|
[
{
"answer_id": 177865,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "Win32::NetAdmin UserGetAttributes GroupIsMember"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
177,723
|
<p>I'm currently working on a project that depends on me providing a path to a file (eg. <code>C:\Path.pth</code>). Now, I had everything working yesterday by calling my <code>std::string</code> with:</p>
<pre><code>std::string path(`"C:\\Path.pth`");
</code></pre>
<p>But now it doesn't work. It throws a <code>bad_alloc</code>. Seems like the '<code>\</code>' character is the problem. I even tried using <code>\x5C</code> as the ascii-value of it instead, but same result.</p>
<p>Now, my question is, is it possible that I have screwed up some <code>#define</code>, some compiler-option or something else "non-code" that could've caused this? I'm using VS 2005.</p>
<p>Any help would be much appreciated</p>
<hr>
<p>PierreBdR</p>
<p>.. That sounds very likely. Or at least, it have to :P</p>
<p>Since no one have mentioned some kind of /SetStringCharSize:2bit-compiler option, I think it's safe to assume that my code has to mess something up, somewhere, and that it's not just a silly compiler-option (or similar) that's wrong..</p>
|
[
{
"answer_id": 177731,
"author": "user22044",
"author_id": 22044,
"author_profile": "https://Stackoverflow.com/users/22044",
"pm_score": 0,
"selected": false,
"text": "std::string path(\"c:\\\\path.pth\");\n std::string path(\"c:/path.pth\");\n"
},
{
"answer_id": 178180,
"author": "Meeh",
"author_id": 25745,
"author_profile": "https://Stackoverflow.com/users/25745",
"pm_score": 2,
"selected": false,
"text": "TIXML_USE_STL TiDocument std::string bad_alloc"
},
{
"answer_id": 178609,
"author": "Jon",
"author_id": 25111,
"author_profile": "https://Stackoverflow.com/users/25111",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\n\nint main()\n{\n #if 1\n std::ifstream file(\"../test.dat\"); // RIGHT!\n #else\n std::ifstream file(\"..\\test.dat\"); // WRONG!\n #endif\n\n ...\n} \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25745/"
] |
177,725
|
<p>I got a simple page with a HtmlInputHidden field. I use a javascript to update that value and when posting back the page i want to read the value of that HtmlInputHidden field.</p>
<p>The Value property of that HtmlInputHidden field is on postback the default value (the value it had when the page got created, not the value reflected through the javascript).</p>
<p>I also tried to Register the HtmlInputHidden field with ScriptManager.RegisterHiddenField(Page, "MyHtmlImputHiddenField", "initialvalue") but it still only lets me read the 'initialvalue' even though i (through javascript) can inspect that the value has changed.</p>
|
[
{
"answer_id": 178095,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "<asp:HiddenField id=\"myHiddenField\" runat=\"server\" />\n string value = myHiddenField.Value; // retrieve the value in hidden field\n control.ClientID"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11619/"
] |
177,727
|
<p>When I add &nbsp; or &eacute; to a text value of a listitem, it display the code of the HTML entity instead of the result (a space or é).</p>
<p>I can add "physical" non-breaking spaces or special chars, but I would like to avoid that if possible. Sometimes the data stored in database is encoded, and I don't want to always process data before displaying it.</p>
<p>Any solution ?</p>
<p>Thanks</p>
<p>Edit note : previous description noted it was about a dropdownlist simulating a treeview, but it was merely an example ; I can't and don't want to replace the dropdownlist by anything else.</p>
|
[
{
"answer_id": 177741,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<optgroup> <select>\n <optgroup label=\"Parent 1\">\n <option>Child 1.1</option>\n <option>Child 1.2</option>\n </optgroup>\n <optgroup label=\"Parent 2\">\n <option>Child 2.1</option>\n <option>Child 2.2</option>\n </optgroup>\n</select> \n"
},
{
"answer_id": 177846,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 4,
"selected": true,
"text": "DropDownList1.DataSource = new List<string> { Server.HtmlDecode(\"A…\"), Server.HtmlDecode(\"B C\") };\nDropDownList1.DataBind();\n"
},
{
"answer_id": 42601605,
"author": "ChrisW",
"author_id": 49942,
"author_profile": "https://Stackoverflow.com/users/49942",
"pm_score": 0,
"selected": false,
"text": "– <asp:RadioButtonList ID=\"Visibility\" runat=\"server\">\n <asp:ListItem Value=\"public\" Text=\"Public – All users\"></asp:ListItem>\n <asp:ListItem Value=\"private\">Private – Only you</asp:ListItem>\n </asp:RadioButtonList>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6776/"
] |
177,747
|
<p>We have a "master database structure", and need a routine to keep the database structure on client sites up-to-date.</p>
<p>A number of suggestions have been given <a href="https://stackoverflow.com/questions/115389/update-sql-sever-database-schema-with-software-update" title="here">to a related question</a>, but I am looking for a more specific solution, along these lines:</p>
<ol>
<li>I would like to generate a text file (XML or other readable format) which describes the entire database structure (this could go into version control). This routine will run in-house, to provide a database schema file to be distributed with the next version of our product.</li>
<li>Then I need a way to update the database structure on the client site so that it corresponds to the master database structure. (In other words, I don't want to have to keep track of numerous change scripts for different versions of the database structure, but a more general routine which can get the client database structure updated to the current master database structure.)</li>
</ol>
<p>So the main feature I'm looking for could be described as "database structure to text" and "text to database structure".</p>
|
[
{
"answer_id": 177741,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<optgroup> <select>\n <optgroup label=\"Parent 1\">\n <option>Child 1.1</option>\n <option>Child 1.2</option>\n </optgroup>\n <optgroup label=\"Parent 2\">\n <option>Child 2.1</option>\n <option>Child 2.2</option>\n </optgroup>\n</select> \n"
},
{
"answer_id": 177846,
"author": "martin",
"author_id": 8421,
"author_profile": "https://Stackoverflow.com/users/8421",
"pm_score": 4,
"selected": true,
"text": "DropDownList1.DataSource = new List<string> { Server.HtmlDecode(\"A…\"), Server.HtmlDecode(\"B C\") };\nDropDownList1.DataBind();\n"
},
{
"answer_id": 42601605,
"author": "ChrisW",
"author_id": 49942,
"author_profile": "https://Stackoverflow.com/users/49942",
"pm_score": 0,
"selected": false,
"text": "– <asp:RadioButtonList ID=\"Visibility\" runat=\"server\">\n <asp:ListItem Value=\"public\" Text=\"Public – All users\"></asp:ListItem>\n <asp:ListItem Value=\"private\">Private – Only you</asp:ListItem>\n </asp:RadioButtonList>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18651/"
] |
177,750
|
<p>I am trying to get some XML data with LINQ, but running into a problem.</p>
<p>I am using a schema, which is set in the attribute xmlns ...</p>
<pre><code><CarsForSale xmlns="http://schemas.sharplogic.net/CarSales.xsd">
<CarForSale>
</code></pre>
<p>There are many CarForSale elements.</p>
<p>When the schema is set and I do this...</p>
<pre><code>XElement doc = XElement.Load(HttpContext.Current.Server.MapPath("App_Data/XML/CarsForSale.xml"));
var cars2 = from d in doc.Descendants("CarForSale")
select d;
</code></pre>
<p>Then I get in the results i get Enumeration yielded no results </p>
<p>Strip the xmlns out of the XML file and the data comes back as expected??</p>
<p>Any ideas?</p>
<p>Thx</p>
|
[
{
"answer_id": 177754,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "var ns = \"http://schemas.sharplogic.net/CarSales.xsd\";\nvar cars2 = from d in doc.Descendants(ns + \"CarForSale\") \n select d;\n var cars2 = from d in doc.Descendants()\n where d.Name.LocalName == \"CarForSale\" \n select d;\n"
},
{
"answer_id": 1276991,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "XNamespace ns = doc.Root.Name.Namespace;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6125/"
] |
177,752
|
<p>I'm migrating a TSQL stored procedure to PL/SQL and have encountered a problem - the lack of a CONTINUE keyword in Oracle 10g.</p>
<p>I've read that Oracle 11g has this as a new feature, but upgrading is not an option unfortunately.</p>
<p>Is there any alternative to CONTINUE in 10g? I don't believe it's practical to restructure the logic of the SP as a work-around, because I have an outer loop, an IF, then a nested IF, then the CONTINUE at the end of a statement block within that IF.</p>
<p>Any help would be greatly appreciated, cheers.</p>
|
[
{
"answer_id": 177785,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 7,
"selected": true,
"text": "DECLARE\n done BOOLEAN;\nBEGIN\n FOR i IN 1..50 LOOP\n IF done THEN\n GOTO end_loop;\n END IF;\n <<end_loop>> -- not allowed unless an executable statement follows\n NULL; -- add NULL statement to avoid error\n END LOOP; -- raises an error without the previous NULL\nEND;\n"
},
{
"answer_id": 177869,
"author": "Thorsten",
"author_id": 25320,
"author_profile": "https://Stackoverflow.com/users/25320",
"pm_score": 1,
"selected": false,
"text": "DECLARE\n done BOOLEAN;\nBEGIN\n FOR i IN 1..50 LOOP\n EXIT WHEN done;\n END LOOP;\nEND;\n"
},
{
"answer_id": 637453,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "DECLARE\n i NUMBER :=0;\n my_ex exception;\nBEGIN\n FOR i IN 1..10\n LOOP\n BEGIN\n IF i = 5 THEN\n raise my_ex;\n END IF;\n DBMS_OUTPUT.PUT_LINE (i);\n EXCEPTION WHEN my_ex THEN\n NULL;\n END;\n END LOOP;\n\nEND;\n"
},
{
"answer_id": 1380326,
"author": "David Oneill",
"author_id": 168646,
"author_profile": "https://Stackoverflow.com/users/168646",
"pm_score": 2,
"selected": false,
"text": "DECLARE\n done BOOLEAN;\nBEGIN\n FOR i IN 1..50 LOOP\n IF done THEN\n NULL;\n ELSE\n <do loop stuff>;\n END IF;\n END LOOP; \nEND;\n"
},
{
"answer_id": 7149583,
"author": "Sylvain Rodrigue",
"author_id": 54783,
"author_profile": "https://Stackoverflow.com/users/54783",
"pm_score": 3,
"selected": false,
"text": "declare\n i integer;\nbegin\n i := 0;\n\n <<My_Small_Loop>>loop\n\n i := i + 1;\n if i <= 3 then goto My_Small_Loop; end if; -- => means continue\n\n exit;\n\n end loop;\nend;\n"
},
{
"answer_id": 17588534,
"author": "eric.itzhak",
"author_id": 1026199,
"author_profile": "https://Stackoverflow.com/users/1026199",
"pm_score": 3,
"selected": false,
"text": "continue SQL> BEGIN\n 2 FOR i IN 1 .. 5 LOOP\n 3 IF i IN (2,4) THEN\n 4 CONTINUE;\n 5 END IF;\n 6 DBMS_OUTPUT.PUT_LINE('Reached on line ' || TO_CHAR(i));\n 7 END LOOP;\n 8 END;\n 9 /\nReached on line 1\nReached on line 3\nReached on line 5\n\nPL/SQL procedure successfully completed.\n"
},
{
"answer_id": 58116974,
"author": "hvb",
"author_id": 2814025,
"author_profile": "https://Stackoverflow.com/users/2814025",
"pm_score": 1,
"selected": false,
"text": "continue skip for i in .. tab_xy.count loop\n CONTINUE WHEN some_condition(tab_xy(i));\n do_process(tab_xy(i));\nend loop;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5827/"
] |
177,762
|
<p>Trying to perform a single boolean NOT operation, it appears that under MS SQL Server 2005, the following block does not work</p>
<pre><code>DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = NOT @MyBoolean;
SELECT @MyBoolean;
</code></pre>
<p>Instead, I am getting more successful with</p>
<pre><code>DECLARE @MyBoolean bit;
SET @MyBoolean = 0;
SET @MyBoolean = 1 - @MyBoolean;
SELECT @MyBoolean;
</code></pre>
<p>Yet, this looks a bit a twisted way to express something as simple as a negation.</p>
<p>Am I missing something?</p>
|
[
{
"answer_id": 177770,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 5,
"selected": false,
"text": "DECLARE @MyBoolean bit;\nSET @MyBoolean = 0;\nSET @MyBoolean = @MyBoolean ^ 1; \nSELECT @MyBoolean;\n"
},
{
"answer_id": 177782,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 5,
"selected": false,
"text": "SET @MyBoolean = CASE @MyBoolean WHEN 0 THEN 1 ELSE 0 END\n"
},
{
"answer_id": 177893,
"author": "Jonas Lincoln",
"author_id": 17436,
"author_profile": "https://Stackoverflow.com/users/17436",
"pm_score": 8,
"selected": true,
"text": "DECLARE @MyBoolean bit\nSET @MyBoolean = 0\nSET @MyBoolean = ~@MyBoolean\nSELECT @MyBoolean\n"
},
{
"answer_id": 3558825,
"author": "Stephen B Craver",
"author_id": 429810,
"author_profile": "https://Stackoverflow.com/users/429810",
"pm_score": 2,
"selected": false,
"text": "ABS DECLARE @Trend AS BIT\nSET @Trend = 0\nSELECT @Trend, ABS(@Trend-1)\n"
},
{
"answer_id": 10299953,
"author": "FistOfFury",
"author_id": 606725,
"author_profile": "https://Stackoverflow.com/users/606725",
"pm_score": 4,
"selected": false,
"text": "Select ~1 \n select ~convert(bit, 1)\n declare @t bit\nset @t=1\nselect ~@t\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
] |
177,778
|
<p>I am trying to set the background color for a double spin box, and I am not sure what function I should use.</p>
<p>I saw some function called <code>SetBackgroundRole</code> which accepts a <code>Qt::ColorRole</code>, but I am not sure how to use this one as well.</p>
<p>Kindly let me know, what's the simple way to change the background color of a <code>QComboBox</code> or <code>QDoubleSpinBox</code>?</p>
|
[
{
"answer_id": 177802,
"author": "fhe",
"author_id": 4445,
"author_profile": "https://Stackoverflow.com/users/4445",
"pm_score": 0,
"selected": false,
"text": "QPalette pal = widget.palette();\npal.setColor(QPalette::Window, Qt::blue);\nwidget.setPalette(pal);\n"
},
{
"answer_id": 178178,
"author": "Jérôme",
"author_id": 2796,
"author_profile": "https://Stackoverflow.com/users/2796",
"pm_score": 6,
"selected": true,
"text": "QPalette QComboBox myComboBox->setStyleSheet(\"QComboBox { background-color: blue; }\"); QSpinBox"
},
{
"answer_id": 178521,
"author": "Caleb Huitt - cjhuitt",
"author_id": 9876,
"author_profile": "https://Stackoverflow.com/users/9876",
"pm_score": 6,
"selected": false,
"text": "QPalette pal = widget.palette();\npal.setColor(widget.backgroundRole(), Qt::blue);\nwidget.setPalette(pal);\n"
},
{
"answer_id": 1184283,
"author": "Marc Mutz - mmutz",
"author_id": 134841,
"author_profile": "https://Stackoverflow.com/users/134841",
"pm_score": 2,
"selected": false,
"text": "comboBox->setPalette( QPalette( Qt::blue ) );\n"
},
{
"answer_id": 1572358,
"author": "shake",
"author_id": 190619,
"author_profile": "https://Stackoverflow.com/users/190619",
"pm_score": 4,
"selected": false,
"text": "this->setAutoFillBackground( true );"
},
{
"answer_id": 2959813,
"author": "Corwin Joy",
"author_id": 150709,
"author_profile": "https://Stackoverflow.com/users/150709",
"pm_score": 4,
"selected": false,
"text": "QPalette pal = myComboBox->palette();\npal.setColor(QPalette::Base, pal.color(QPalette::Window));\nmyComboBox->setPalette(pal);\n"
},
{
"answer_id": 4700971,
"author": "Rodrigo Haas",
"author_id": 576892,
"author_profile": "https://Stackoverflow.com/users/576892",
"pm_score": -1,
"selected": false,
"text": "comboBox->setPalette( QPalette( Qt::blue ) );\n"
},
{
"answer_id": 21291490,
"author": "Dan Blanks",
"author_id": 3224869,
"author_profile": "https://Stackoverflow.com/users/3224869",
"pm_score": 2,
"selected": false,
"text": "QComboBox QComboBox QLineEdit QComboBox *myComboBox = new QComboBox();\n myComboBox->setEditable(true);\n QColor backColor = QColor(246, 230, 230);\n QLineEdit *lineEditor = myComboBox->lineEdit();\n QPalette pal = lineEditor->palette();\n pal.setColor(QPalette::Base, backColor);\n lineEditor->setPalette(pal);\n"
},
{
"answer_id": 56169890,
"author": "Patapoom",
"author_id": 1217854,
"author_profile": "https://Stackoverflow.com/users/1217854",
"pm_score": 1,
"selected": false,
"text": "QPalette pal = ui.widget->palette();\npal.setColor(QPalette::Base, Qt::red);\nui.widget->setPalette(pal);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
] |
177,814
|
<p>During an ASP.NET page load I'm opening and closing multiple System.Data.SqlClient.SqlConnections inside multiple controls contained in the page. I thought it would be a good idea instead to create a "pool" of connections and when opening a connection check to see if the connection string matches that of an open connection in the pool, and return that connection. I was expecting to see a difference in the page load times, but I haven't seen any change. I know that with PHP if you attempt to open a new connection with a connection string that has already been used in that page request it won't attempt to open a new connection and will return the existing open connection instead. Is this true with .NET?</p>
|
[
{
"answer_id": 177825,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 0,
"selected": false,
"text": "Open() Close()"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2179408/"
] |
177,815
|
<p>I am changing a GET to a POST. Currently I have .jsp?id=a,b,c,d. When changing this to a post I am still sitting the id parameter a,b,c,d . This is not working for me. Can I submit a comma separated list to a post parameter?</p>
|
[
{
"answer_id": 177822,
"author": "Fionn",
"author_id": 21566,
"author_profile": "https://Stackoverflow.com/users/21566",
"pm_score": 4,
"selected": false,
"text": "string[] values = Request.Form.GetValues(\"param\");\n"
},
{
"answer_id": 177853,
"author": "Olvagor",
"author_id": 17473,
"author_profile": "https://Stackoverflow.com/users/17473",
"pm_score": 4,
"selected": false,
"text": "url?param=value1¶m=value2¶m=value3\n String[] values = request.getParameterValues(\"param\");\n"
},
{
"answer_id": 177866,
"author": "random",
"author_id": 9314,
"author_profile": "https://Stackoverflow.com/users/9314",
"pm_score": 2,
"selected": false,
"text": "<form method=\"post\">\n<select multiple name=\"id[]\">\n<option value=\"1\">1</option>\n<option value=\"2\">2</option>\n<option value=\"3\">3</option>\n</select>\n<input type=\"submit\" value=\"send\">\n</form>\n"
},
{
"answer_id": 178015,
"author": "user25778",
"author_id": 25778,
"author_profile": "https://Stackoverflow.com/users/25778",
"pm_score": 0,
"selected": false,
"text": " http_request = false;\n if (window.XMLHttpRequest) { // Mozilla, Safari,...\n http_request = new XMLHttpRequest();\n if (http_request.overrideMimeType) {\n // set type accordingly to anticipated content type\n //http_request.overrideMimeType('text/xml');\n http_request.overrideMimeType('text/html');\n }\n } else if (window.ActiveXObject) { // IE\n try {\n http_request = new ActiveXObject(\"Msxml2.XMLHTTP\");\n } catch (e) {\n try {\n http_request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n } catch (e) {}\n }\n }\n if (!http_request) {\n alert('Cannot create XMLHTTP instance');\n return false;\n }\n\n http_request.onreadystatechange = alertContents;\n http_request.open('POST', url, true);\n http_request.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n http_request.setRequestHeader(\"Content-length\", parameters.length);\n http_request.setRequestHeader(\"Connection\", \"close\");\n http_request.send(parameters);\n"
},
{
"answer_id": 8938587,
"author": "WR10",
"author_id": 1134346,
"author_profile": "https://Stackoverflow.com/users/1134346",
"pm_score": 1,
"selected": false,
"text": " xmlhttp\n .send(\"files=\" + files.value + \"&tagcount=\"\n + tagcount.value);\n \"parameter1=\" + parameter1.value + \"¶meter2=\" + parameter2.value\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
177,835
|
<p>One of our unit tests is to populate properties within our business objects with random data.</p>
<p>These properties are of different intrinsic types and therefore we would like to use the power of generics to return data of the type you pass in. Something along the lines of:</p>
<pre><code>public static T GetData<T>()
</code></pre>
<p>How would you go about approaching this? Would a low level interface work? (IConvertible)</p>
|
[
{
"answer_id": 177847,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "public static T GetData<T>()\n{\n object factory;\n if (!factories.TryGet(typeof(T), out factory))\n {\n throw new ArgumentException(\"No factory for type \" + typeof(T).Name);\n }\n Func<T> factoryFunc = (Func<T>) factory;\n return factoryFunc();\n}\n"
},
{
"answer_id": 177851,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": true,
"text": "// Random int\nRandom r = new Random();\nreturn r.Next();\n\n// Random Guid\nreturn Guid.NewGuid();\n\n...\n switch(typeof(T))\n{\n case System.Int32:\n Random r = new Random();\n return (T)r.Next();\n case System.Guid:\n return (T)Guid.NewGuid();\n ...\n RandomGenerator.GetData<Guid>();\n...\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17540/"
] |
177,856
|
<p>I would like to be able to trap <kbd>Ctrl</kbd>+<kbd>C</kbd> in a C# console application so that I can carry out some cleanups before exiting. What is the best way of doing this?</p>
|
[
{
"answer_id": 929717,
"author": "Jonas",
"author_id": 16047,
"author_profile": "https://Stackoverflow.com/users/16047",
"pm_score": 8,
"selected": false,
"text": "public static void Main(string[] args)\n{\n Console.CancelKeyPress += delegate {\n // call methods to clean up\n };\n\n while (true) {}\n}\n class MainClass\n{\n private static bool keepRunning = true;\n\n public static void Main(string[] args)\n {\n Console.CancelKeyPress += delegate(object? sender, ConsoleCancelEventArgs e) {\n e.Cancel = true;\n MainClass.keepRunning = false;\n };\n \n while (MainClass.keepRunning) {\n // Do your work in here, in small chunks.\n // If you literally just want to wait until Ctrl+C,\n // not doing anything, see the answer using set-reset events.\n }\n Console.WriteLine(\"exited gracefully\");\n }\n}\n e.Cancel keepRunning"
},
{
"answer_id": 13899429,
"author": "Jonathon Reinhart",
"author_id": 119527,
"author_profile": "https://Stackoverflow.com/users/119527",
"pm_score": 7,
"selected": false,
"text": "bool ManualResetEvent static void Main(string[] args) {\n var exitEvent = new ManualResetEvent(false);\n\n Console.CancelKeyPress += (sender, eventArgs) => {\n eventArgs.Cancel = true;\n exitEvent.Set();\n };\n\n var server = new MyServer(); // example\n server.Run();\n\n exitEvent.WaitOne();\n server.Stop();\n}\n"
},
{
"answer_id": 22996552,
"author": "JJ_Coder4Hire",
"author_id": 1944063,
"author_profile": "https://Stackoverflow.com/users/1944063",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Threading;\n\nnamespace TestTrapCtrlC {\n public class Program {\n static bool exitSystem = false;\n\n #region Trap application termination\n [DllImport(\"Kernel32\")]\n private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);\n\n private delegate bool EventHandler(CtrlType sig);\n static EventHandler _handler;\n\n enum CtrlType {\n CTRL_C_EVENT = 0,\n CTRL_BREAK_EVENT = 1,\n CTRL_CLOSE_EVENT = 2,\n CTRL_LOGOFF_EVENT = 5,\n CTRL_SHUTDOWN_EVENT = 6\n }\n\n private static bool Handler(CtrlType sig) {\n Console.WriteLine(\"Exiting system due to external CTRL-C, or process kill, or shutdown\");\n\n //do your cleanup here\n Thread.Sleep(5000); //simulate some cleanup delay\n\n Console.WriteLine(\"Cleanup complete\");\n\n //allow main to run off\n exitSystem = true;\n\n //shutdown right away so there are no lingering threads\n Environment.Exit(-1);\n\n return true;\n }\n #endregion\n\n static void Main(string[] args) {\n // Some biolerplate to react to close window event, CTRL-C, kill, etc\n _handler += new EventHandler(Handler);\n SetConsoleCtrlHandler(_handler, true);\n\n //start your multi threaded program here\n Program p = new Program();\n p.Start();\n\n //hold the console so it doesn’t run off the end\n while (!exitSystem) {\n Thread.Sleep(500);\n }\n }\n\n public void Start() {\n // start a thread and start doing some processing\n Console.WriteLine(\"Thread started, processing..\");\n }\n }\n}\n"
},
{
"answer_id": 25118049,
"author": "hallo",
"author_id": 3906494,
"author_profile": "https://Stackoverflow.com/users/3906494",
"pm_score": 2,
"selected": false,
"text": "Console.TreatControlCAsInput = true;"
},
{
"answer_id": 28081265,
"author": "Paul",
"author_id": 3591916,
"author_profile": "https://Stackoverflow.com/users/3591916",
"pm_score": 3,
"selected": false,
"text": "namespace CancelSample\n{\n using System;\n using System.Threading;\n using System.Runtime.InteropServices;\n\n internal class Program\n {\n /// <summary>\n /// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process\n /// </summary>\n /// <param name=\"handler\">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>\n /// <param name=\"add\">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>\n /// <returns>If the function succeeds, the return value is true.</returns>\n [DllImport(\"Kernel32\")]\n private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);\n\n /// <summary>\n /// The console close handler delegate.\n /// </summary>\n /// <param name=\"closeReason\">\n /// The close reason.\n /// </param>\n /// <returns>\n /// True if cleanup is complete, false to run other registered close handlers.\n /// </returns>\n private delegate bool ConsoleCloseHandler(int closeReason);\n\n /// <summary>\n /// Event set when the process is terminated.\n /// </summary>\n private static readonly ManualResetEvent TerminationRequestedEvent;\n\n /// <summary>\n /// Event set when the process terminates.\n /// </summary>\n private static readonly ManualResetEvent TerminationCompletedEvent;\n\n /// <summary>\n /// Static constructor\n /// </summary>\n static Program()\n {\n // Do this initialization here to avoid polluting Main() with it\n // also this is a great place to initialize multiple static\n // variables.\n TerminationRequestedEvent = new ManualResetEvent(false);\n TerminationCompletedEvent = new ManualResetEvent(false);\n SetConsoleCtrlHandler(OnConsoleCloseEvent, true);\n }\n\n /// <summary>\n /// The main console entry point.\n /// </summary>\n /// <param name=\"args\">The commandline arguments.</param>\n private static void Main(string[] args)\n {\n // Wait for the termination event\n while (!TerminationRequestedEvent.WaitOne(0))\n {\n // Something to do while waiting\n Console.WriteLine(\"Work\");\n }\n\n // Sleep until termination\n TerminationRequestedEvent.WaitOne();\n\n // Print a message which represents the operation\n Console.WriteLine(\"Cleanup\");\n\n // Set this to terminate immediately (if not set, the OS will\n // eventually kill the process)\n TerminationCompletedEvent.Set();\n }\n\n /// <summary>\n /// Method called when the user presses Ctrl-C\n /// </summary>\n /// <param name=\"reason\">The close reason</param>\n private static bool OnConsoleCloseEvent(int reason)\n {\n // Signal termination\n TerminationRequestedEvent.Set();\n\n // Wait for cleanup\n TerminationCompletedEvent.WaitOne();\n\n // Don't run other handlers, just exit.\n return true;\n }\n }\n}\n"
},
{
"answer_id": 61643542,
"author": "Vaulter",
"author_id": 766644,
"author_profile": "https://Stackoverflow.com/users/766644",
"pm_score": 2,
"selected": false,
"text": "Host.RunAsync(ct) private static readonly CancellationTokenSource cts = new CancellationTokenSource();\n public static int Main(string[] args)\n {\n // For gracefull shutdown, trap unload event\n AppDomain.CurrentDomain.ProcessExit += (sender, e) =>\n {\n cts.Cancel();\n exitEvent.Wait();\n };\n\n Console.CancelKeyPress += (sender, e) =>\n {\n cts.Cancel();\n exitEvent.Wait();\n };\n\n host.RunAsync(cts);\n Console.WriteLine(\"Shutting down\");\n exitEvent.Set();\n return 0;\n }\n"
},
{
"answer_id": 69967357,
"author": "Alby",
"author_id": 3084793,
"author_profile": "https://Stackoverflow.com/users/3084793",
"pm_score": 2,
"selected": false,
"text": "CancellationTokenSource ctSource = new();\nCancellationToken ct = ctSource.Token;\n\nvoid ExitHandler()\n{\n // You can add any arbitrary global clean up\n Console.WriteLine(\"Exiting...\");\n ctSource.Cancel();\n}\n\n// Assign exit handler to be called when the process is terminated\n// or the user hits CTRL+C\nAppDomain.CurrentDomain.ProcessExit += (sender, args) => ExitHandler();\nConsole.CancelKeyPress += (sender, args) => ExitHandler();\n\n// Then you can use the cancellation token to check for exit:\nConsole.WriteLine(\"Ready to gracefully shut down!\");\nwhile (!ct.IsCancellationRequested)\n{\n Console.WriteLine($\"Exit not detected, waiting another 10s.\");\n Task.Delay(10000, ct).Wait(ct);\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
177,863
|
<p>I am using the next class (simplified for the sake of understandability) to download images in a struts web application.
It is working fine in every browser but firefox, which cuts names containing spaces. That it is to say: <strong>file with spaces.pdf</strong> gets downloaded in firefox as: <strong>file</strong> while in chrome, IE7 IE6 is downloaded as <strong>file with spaces.pdf</strong>.</p>
<pre><code>public class Download extends Action {
private static final int BUFFER_SIZE = 4096;
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
String filename = "file with spaces.pdf";
File file = ... // variable containing the file;
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(getMimeType(request, file));
response.setHeader("Content-Type", getMimeType(request, file));
response.setHeader("Content-Disposition","attachment; filename="+ filename);
InputStream is = new FileInputStream(file);
sendFile(is, response);
return null;
}
protected String getMimeType(HttpServletRequest request, File file) {
ServletContext application = super.servlet.getServletContext();
return application.getMimeType(file.getName());
}
protected void sendFile(InputStream is, HttpServletResponse response) throws IOException {
BufferedInputStream in = null;
try {
int count;
byte[] buffer = new byte[BUFFER_SIZE];
in = new BufferedInputStream(is);
ServletOutputStream out = response.getOutputStream();
while(-1 != (count = in.read(buffer)))
out.write(buffer, 0, count);
out.flush();
} catch (IOException ioe) {
System.err.println("IOException in Download::sendFile");
ioe.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}
}
}
</code></pre>
<p>Does anyone know about what is going on here? Note i am using firefox 3.0.3 under Windows Vista. </p>
|
[
{
"answer_id": 177880,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 6,
"selected": true,
"text": "response.setHeader(\"Content-Disposition\",\"attachment; filename=\\\"\" + filename + \"\\\"\");\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
177,867
|
<p>I need to copy data values from one element to another, but jQuery's clone() method doesn't clone the data. And I can't iterate over the data either:</p>
<pre><code>element.data().each
</code></pre>
<p>because <code>data()</code> is a function and not a jQuery object. It seems I have to keep a separate list of attribute names and reference those but that seems too hacky. So how can I do either of these:</p>
<p>a) Iterate over data items<br>
OR<br>
b) <code>clone()</code> an element with its data.</p>
|
[
{
"answer_id": 7805272,
"author": "simon",
"author_id": 76777,
"author_profile": "https://Stackoverflow.com/users/76777",
"pm_score": 1,
"selected": false,
"text": "\nfunction getOriginalElementData(domElementJQueryObject){\n var originalElementData = new Array();\n $.each(domElementJQueryObject.data(),function(name,value) {\n originalElementData.push({\"name\":name,\"value\":value});\n });\n\n return originalElementData;\n}\n \nfunction restoreOriginalElementData(domElementJQueryObject,originalElementData){\n for(var i=0;i<originalElementData.length;i++){\n domElementJQueryObject.data(originalElementData[i].name,originalElementData[i].value);\n }\n}\n"
},
{
"answer_id": 17020885,
"author": "DUzun",
"author_id": 1242333,
"author_profile": "https://Stackoverflow.com/users/1242333",
"pm_score": 2,
"selected": false,
"text": "$.each(element.data(), function (name, value) {\n // ... do something\n})\n $.each($.data(element), function (name, value) {\n // ... do something\n})\n"
},
{
"answer_id": 20074111,
"author": "Nexii Malthus",
"author_id": 938335,
"author_profile": "https://Stackoverflow.com/users/938335",
"pm_score": 5,
"selected": false,
"text": "$(destination).data( $(source).data() );\n Object.assign(destination.dataset, source.dataset);\n"
},
{
"answer_id": 26328722,
"author": "JasCav",
"author_id": 132528,
"author_profile": "https://Stackoverflow.com/users/132528",
"pm_score": 1,
"selected": false,
"text": "$.each(original.data(), function (name, value) {\n new.attr('data-' + name, JSON.stringify(value));\n});\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896/"
] |
177,883
|
<p>is it possible to include a servlet in a jsp page? if so how?</p>
|
[
{
"answer_id": 7805272,
"author": "simon",
"author_id": 76777,
"author_profile": "https://Stackoverflow.com/users/76777",
"pm_score": 1,
"selected": false,
"text": "\nfunction getOriginalElementData(domElementJQueryObject){\n var originalElementData = new Array();\n $.each(domElementJQueryObject.data(),function(name,value) {\n originalElementData.push({\"name\":name,\"value\":value});\n });\n\n return originalElementData;\n}\n \nfunction restoreOriginalElementData(domElementJQueryObject,originalElementData){\n for(var i=0;i<originalElementData.length;i++){\n domElementJQueryObject.data(originalElementData[i].name,originalElementData[i].value);\n }\n}\n"
},
{
"answer_id": 17020885,
"author": "DUzun",
"author_id": 1242333,
"author_profile": "https://Stackoverflow.com/users/1242333",
"pm_score": 2,
"selected": false,
"text": "$.each(element.data(), function (name, value) {\n // ... do something\n})\n $.each($.data(element), function (name, value) {\n // ... do something\n})\n"
},
{
"answer_id": 20074111,
"author": "Nexii Malthus",
"author_id": 938335,
"author_profile": "https://Stackoverflow.com/users/938335",
"pm_score": 5,
"selected": false,
"text": "$(destination).data( $(source).data() );\n Object.assign(destination.dataset, source.dataset);\n"
},
{
"answer_id": 26328722,
"author": "JasCav",
"author_id": 132528,
"author_profile": "https://Stackoverflow.com/users/132528",
"pm_score": 1,
"selected": false,
"text": "$.each(original.data(), function (name, value) {\n new.attr('data-' + name, JSON.stringify(value));\n});\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24481/"
] |
177,885
|
<p>I'm looking for a way to obtain offsets of data members of a C++ class which is of non-POD nature.</p>
<p>Here's why: </p>
<p>I'd like to store data in <a href="http://www.hdfgroup.org/HDF5/whatishdf5.html" rel="noreferrer">HDF5</a> format, which seems most suited for my kind of material (numerical simulation output), but it is perhaps a rather C-oriented library. I want to use it through the C++ interface, which would require me to declare storage types like so (following documentation from <a href="http://www.hdfgroup.org/HDF5/doc1.6/cpplus_RM/classH5_1_1CompType.html#a16" rel="noreferrer">here</a> and <a href="http://www.hdfgroup.org/HDF5/doc1.6/UG/11_Datatypes.html" rel="noreferrer">here</a> (section 4.3.2.1.1)): </p>
<pre><code>class example {
public:
double member_a;
int member_b;
} //class example
H5::CompType func_that_creates_example_CompType() {
H5::CompType ct;
ct.insertMember("a", HOFFSET(example, member_a), H5::PredType::NATIVE_DOUBLE);
ct.insertMember("b", HOFFSET(example, member_b), H5::PredType::NATIVE_INT);
return ct;
} //func_that_creates_example_CompType
</code></pre>
<p>where HOFFSET is a HDF-specific macro that uses offsetof.</p>
<p>The problem is of course, that as soon as the example-class becomes it little bit more featureful, it is no longer of POD-type, and so using offsetof will give undefined results.</p>
<p>The only workaround I can think of is to first export the data I want to store to a simpler struct, then pass that to HDF. That does however involve data copying, which is exactly what HDF is trying to avoid (and why they have this CompType which enables the library to reach into your objects to save their data to file).</p>
<p>So I was hoping you'd have better ideas. Ideally I'd be looking for a portable workaround for this problem, but if short of that you could give me an idea that works on x86 and x86_64 with GCC I'd already be immensely grateful.</p>
<p>----- appended later: -----</p>
<p>Greg Hewgill suggested below to store the data in a simple struct, then build the actual class by inheriting from that. For HDF specifically, I think that may not practically work. A more elaborate usage scenario than above:</p>
<pre><code>class base_pod {
public:
double member_a;
int member_b;
}; //class base_pod
class derived_non_pod : private base_pod {
public:
//the following method is only virtual to illustrate the problem
virtual double get_member_a() {return member_a; }
}; //class derived_non_pod
class that_uses_derived_non_pod {
public:
void whatever();
private:
derived_non_pod member_c;
}; //class that_uses_derived_non_pod
</code></pre>
<p>Now, when we're storing instances of the class that_uses_derived_non_pod, we cannot describe its memory layout as if it had a base_pod as member_c. This would get the offsets wrong because derived_non_pod adds funky stuff (like a virtual function table, I guess?).</p>
|
[
{
"answer_id": 177887,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "private derived_non_pod base_pod base_pod derived_non_pod"
},
{
"answer_id": 1234781,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 1,
"selected": false,
"text": "struct A\n{\n int i;\n};\n\nclass B: public A\n{\npublic:\n virtual void foo ()\n {\n }\n};\n\nint main ()\n{\n std::cout << offsetof (B, A::i) << std::endl;\n}\n struct A1 {\n int i;\n};\n\nstruct A2 {\n int j;\n};\n\nstruct A3 : public virtual A2 {\n};\n\nclass B: public A1, public A3 {\npublic:\n virtual void foo () {\n }\n};\n\ntemplate <typename MostDerived, typename C, typename M>\nptrdiff_t calcOffset (M C::* member)\n{\n MostDerived d;\n return reinterpret_cast<char*> (&(d.*member)) - reinterpret_cast<char*> (&d);\n}\n\nint main ()\n{\n B b;\n std::cout << calcOffset<B> (&A2::j) << \", \" \n << calcOffset<B> (&A1::i) << std::endl;\n}\n struct H5MemberDef\n{\n const char * member_name;\n ptrdiff_t offset;\n H5PredType h5_type;\n};\n\n\nclass B // ....\n{\npublic:\n\n // ...\n\n static H5memberDef memberDef[];\n};\n\nH5MemberDef B::memberDef[] = {\n { \"i\", calcOffset<B> (&A1::i), H5::PredType::NATIVE_INT }\n , { \"j\", calcOffset<B> (&A2::j), H5::PredType::NATIVE_INT }\n , { 0, 0, H5::PredType::NATIVE_INT }\n};\n H5::CompType func_that_creates_example_CompType(H5MemberDef * pDef) {\n H5::CompType ct;\n while (*pDef->member_name != 0)\n {\n ct.insertMember(pDef->member_name, pDef->offset, pDef->h5_type);\n ++pDef;\n }\n return ct;\n}\n"
},
{
"answer_id": 16270322,
"author": "Greg Slepak",
"author_id": 1781435,
"author_profile": "https://Stackoverflow.com/users/1781435",
"pm_score": -1,
"selected": false,
"text": "#define myOffset(Class,Member) ({Class o; (size_t)&(o.Member) - (size_t)&o;})\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25756/"
] |
177,910
|
<p>I've produced a python egg using setuptools and would like to access it's metadata at runtime. I currently got working this:</p>
<pre><code>import pkg_resources
dist = pkg_resources.get_distribution("my_project")
print(dist.version)
</code></pre>
<p>but this would probably work incorrectly if I had multiple versions of the same egg installed. And if I have both installed egg and development version, then running this code from development version would pick up version of the installed egg. </p>
<p>So, how do I get metadata for <em>my</em> egg not some random matching egg installed on my system? </p>
|
[
{
"answer_id": 177939,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": true,
"text": "my_project"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5821/"
] |
177,911
|
<p>I've got a WPF browser-like application with a few pages. When I switch between pages, I'd like to set the keyboard focus.</p>
<p>When a page is loaded the first time, this works by calling <code>Control.Focus()</code> in the constructor.</p>
<p>But when I switch between pages this does not work anymore - the focus is just on the first field, and ignores my attempts to change it to anything else :(</p>
<p>The pages have the attribute <code>KeepAlive=true</code> - it would be OK if that would keep the focus alive, too, but just setting the focus to the first field is annoying.</p>
<p>I tried to set the focus in the loaded event, but it did not work, too. It seems the default focus is set after reloading the page.</p>
<p>Is there any way to set the focus on entering a page the second time? <strong>When, how and where should I set the focus when switching between WPF pages in a browserlike application</strong>?</p>
|
[
{
"answer_id": 221884,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 1,
"selected": true,
"text": "myControl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, \n(System.Threading.SendOrPostCallback)delegate(object state) \n{ \n myControl.Focus(); \n});\n"
},
{
"answer_id": 4785145,
"author": "OrPaz",
"author_id": 388894,
"author_profile": "https://Stackoverflow.com/users/388894",
"pm_score": 2,
"selected": false,
"text": "EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent,\n new RoutedEventHandler(WindowLoaded));\n void WindowLoaded(object sender, RoutedEventArgs e)\n {\n var window = e.Source as Window;\n System.Threading.Thread.Sleep(100);\n window.Dispatcher.Invoke(\n new Action(() =>\n {\n window.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));\n\n }));\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7021/"
] |
177,927
|
<p>In JPA the Entities are nice annotated Plain Old Java Objects. But I have not found a good way to interact with them and the database.</p>
<p>In my current app, my basic design is always to have a sequence based id as primary key so I usually have to look up entities by other properties than PK.</p>
<p>And for each Entity I have a stateless EJB of </p>
<pre><code>@Stateless
public class MyEntApiBean implements MyEntApi {
@PersistenceContext(unitName = "xxx") @Inject EntityManager entityManager;
</code></pre>
<p>with query methods that all are some variation </p>
<pre><code>/**
* @return A List of all MyEnts that have some property
* @param someProp some property
*/
public List<MyEnt> getAllMyEntsFromProp(final String someProp) {
try {
final Query query = entityManager.createQuery("select me from MyEnt me where me.someProp = :someProp");
query.setParameter("someProp", someProp);
return query.getResultList();
} catch(final NoResultException nre) {
log.warn("No MyEnts found");
}
return new ArrayList<MyEnt>();
}
</code></pre>
<p>So:</p>
<ol>
<li><p>I really hate having these methods in an EJB because they seem to belong with the entities themselves, and the EJB local interfaces annoy the crap out of me.</p></li>
<li><p>I hate the duplication that I have in each method with "try, createQuery, getResultList,catch, log, return" (mostly a consequence of no closures or "with statement" or somesuch in Java).</p></li>
</ol>
<p>Does anyone have a suggestion for a better way to interact with the Entities and Database that addresses one or both of my issues?</p>
<p>I am currently thinking of doing some base methods with generics and reflection to get some generic query methods to reduce the duplication (issue 2) (I will put a prototype up for review later).</p>
<p>Thanks,
Anders</p>
|
[
{
"answer_id": 178744,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 2,
"selected": false,
"text": "@SuppressWarnings(\"unchecked\")\npublic List<MyEnt> getAllMyEntsFromProp(final String someProp) {\n return entityManager.createQuery(\"select me from MyEnt me where me.someProp = :someProp\")\n .setParameter(\"someProp\", someProp);\n .getResultList();\n}\n"
},
{
"answer_id": 1587422,
"author": "Aljoscha Rittner",
"author_id": 192278,
"author_profile": "https://Stackoverflow.com/users/192278",
"pm_score": 1,
"selected": false,
"text": "public class JPA {\n @SuppressWarnings (\"unchecked\")\n public static <T> T querySingle(\n EntityManager em, \n Class<T> clazz, \n String namedQuery, \n Pair... params) \n {\n Query q = em.createNamedQuery(namedQuery);\n for (Pair pair : params) {\n q.setParameter(pair.key, pair.value); \n }\n List<T> result = q.getResultList();\n if ( result.size() == 0 ) {\n return null;\n }\n if ( result.size() == 1 ) {\n return result.get(0);\n }\n throw new \n IllegalStateException(\n \"To many result rows for query: \" \n + namedQuery \n + \" where \" \n + Arrays.toString(params));\n }\n\n public static class Pair {\n String key;\n Object value;\n\n public static Pair param (String key, Object value) {\n return new Pair (key, value);\n }\n\n public Pair (String key, Object value) {\n this.key = key;\n this.value = value;\n }\n\n @Override\n public String toString() {\n return key + \"=\" + value;\n }\n }\n}\n import static org.sepix.JPA.*;\n...\n\nString id = ...\nCustomer customer = querySingle (em, Customer.class, \n \"Customer.findByID\", Pair.param (\"id\", id));\n String inquiryID = ...\nBoolean current = Boolean.TRUE;\nInquiry inq = querySingle (em, Inquiry.class, \n \"Inquiry.findCurrent\", \n Pair.param (\"inquiry\", inquiryID),\n Pair.param (\"current\", current));\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8805/"
] |
177,945
|
<p>I would like to create XML Schema for this chunk of xml, I would like to restrict the values of "name" attribute, so that in output document on and only one instance of day is allowed for each week day:</p>
<pre><code><a>
<day name="monday" />
<day name="tuesday" />
<day name="wednesday" />
</a>
</code></pre>
<p>I have tried to use this:</p>
<pre><code> <xs:complexType name="a">
<xs:sequence>
<xs:element name="day" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:attribute name="name" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="monday" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="day" minOccurs="1" maxOccurs="1">
<xs:complexType>
<xs:attribute name="name" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="tuesday" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</code></pre>
<p>but XML Schema validator in eclipse says error "Multiple elements with name 'day', with different types, appear in the model group.".</p>
<p>Is there any other way?</p>
|
[
{
"answer_id": 177954,
"author": "Micah",
"author_id": 17744,
"author_profile": "https://Stackoverflow.com/users/17744",
"pm_score": 0,
"selected": false,
"text": "<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n<xs:element name=\"a\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" name=\"day\">\n <xs:complexType>\n <xs:attribute name=\"atrib\" type=\"xs:string\" use=\"required\" />\n </xs:complexType>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n</xs:element>\n"
},
{
"answer_id": 178153,
"author": "Cyphus",
"author_id": 1150,
"author_profile": "https://Stackoverflow.com/users/1150",
"pm_score": 1,
"selected": false,
"text": "<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n <xs:complexType name=\"day\" />\n <xs:element name=\"a\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"monday\" maxOccurs=\"1\" minOccurs=\"0\" type=\"day\" />\n <xs:element name=\"tuesday\" maxOccurs=\"1\" minOccurs=\"0\" type=\"day\" />\n <xs:element name=\"wednesday\" maxOccurs=\"1\" minOccurs=\"0\" type=\"day\" />\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n"
},
{
"answer_id": 334323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\">\n <xs:element name=\"a\">\n <xs:complexType>\n <xs:sequence>\n <xs:element maxOccurs=\"unbounded\" ref=\"day\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n <xs:element name=\"day\">\n <xs:complexType>\n <xs:attribute name=\"name\" use=\"required\">\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"monday\"/>\n <xs:enumeration value=\"tuesday\"/>\n <xs:enumeration value=\"wednesday\"/>\n </xs:restriction>\n </xs:simpleType>\n </xs:attribute>\n </xs:complexType>\n </xs:element>\n</xs:schema>\n"
},
{
"answer_id": 2778201,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 3,
"selected": false,
"text": "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n elementFormDefault=\"qualified\">\n\n <xs:element name=\"a\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"day\" maxOccurs=\"7\" minOccurs=\"1\">\n <xs:complexType>\n <xs:attribute name=\"name\" use=\"required\">\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:pattern value=\"(mon|tues|wednes|thurs|fri|satur|sun)day\"/>\n </xs:restriction>\n </xs:simpleType>\n </xs:attribute>\n </xs:complexType>\n <xs:unique name=\"eachDayAtMostOnce\">\n <xs:selector xpath=\"day\"/>\n <xs:field xpath=\"@name\"/>\n </xs:unique>\n </xs:element>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n</xs:schema>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10560/"
] |
177,956
|
<p>What is the best way to convert an int or null to boolean value in an SQL query, such that:</p>
<ul>
<li>Any non-null value is <strong>TRUE</strong> in the results</li>
<li>Any null value is <strong>FALSE</strong> in the results</li>
</ul>
|
[
{
"answer_id": 177967,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 2,
"selected": false,
"text": "isnull(column - column + 1, 0) != 0\n"
},
{
"answer_id": 177978,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 3,
"selected": false,
"text": "SELECT \n CASE\n WHEN thevalue IS NULL THEN 0\n ELSE 1\n END AS newVal\nFROM .... (rest of select)\n"
},
{
"answer_id": 177984,
"author": "cvk",
"author_id": 25397,
"author_profile": "https://Stackoverflow.com/users/25397",
"pm_score": 5,
"selected": false,
"text": "select (column_name is not null) as result from table_name;\n"
},
{
"answer_id": 177987,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "SELECT \n CASE WHEN ValueColumn IS NULL THEN 'FALSE' ELSE 'TRUE' END BooleanOutput \nFROM \n table \n"
},
{
"answer_id": 178405,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 2,
"selected": false,
"text": "create function dbo.isNotNull(@a int)\nreturns bit\nas\nbegin\nreturn isnull(@a-@a+1,0)\nend\n select dbo.isNotNull(myIntColumn) from myTable\n"
},
{
"answer_id": 256589,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 1,
"selected": false,
"text": "SELECT DECODE( col, NULL, 0, 1) FROM ...\n"
},
{
"answer_id": 30342364,
"author": "PL_kolek",
"author_id": 2926014,
"author_profile": "https://Stackoverflow.com/users/2926014",
"pm_score": 0,
"selected": false,
"text": "SELECT NVL2(nullableColumn, 1, 0) FROM someTable\n NVL2(value, ifNotNull, ifNull) ifNotNull value ifNull"
},
{
"answer_id": 36559035,
"author": "David Castro",
"author_id": 3199531,
"author_profile": "https://Stackoverflow.com/users/3199531",
"pm_score": 1,
"selected": false,
"text": "SELECT IsDefault = CASE WHEN IsDefault = 1 THEN 'true' ELSE 'false' END\nFROM table\n"
},
{
"answer_id": 59251866,
"author": "Daniel Hudsky",
"author_id": 7952824,
"author_profile": "https://Stackoverflow.com/users/7952824",
"pm_score": -1,
"selected": false,
"text": "select count(*) as count, inventory,\nCASE WHEN inventory = 0 THEN 'empty' ELSE 'not empty' END as InventoryStatus\nfrom mytable group by count, inventory\n"
},
{
"answer_id": 72212871,
"author": "Go Man",
"author_id": 1661562,
"author_profile": "https://Stackoverflow.com/users/1661562",
"pm_score": 1,
"selected": false,
"text": "SELECT IIF(ISNULL(ColumnName<Nullable>, 'true')='false', 'true', 'false') ;\n\n\nSELECT IIF(ISNULL(Email, 'true')='false', 'true', 'false') from Employee ;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
177,964
|
<p>I have an application database and an aspnetdb database (generated from the ASP.Net 2.0 framework). I have restored both database from production onto my development environment but I am unable to log on with any of the users credentials that work on production.</p>
<p>So my question is is there anything that ties the aspnetdb database generated by ASP>NET 2.0 Framework to a specific machine?</p>
<p>If anyone has ever restored an aspnetdb database from one machine to another successfully please can they shed light on the variables that need to be the same in order to access all the previous users.</p>
<p>Many Thanks!</p>
<hr>
<p>Sure I have checked the connection string and double checked users and roles which I can confirm is working by being able to create new users on the development environment and log in with those credentials. </p>
<p>The problem is I am unable to logon with any of the user credentials I use on the live environment. This I feel is related to the difference in the machine.config files on both machines. If anyone knows a variable I should look for in the machine.config then I could make sure they are the same in both environments i.e both machines.</p>
|
[
{
"answer_id": 178132,
"author": "test",
"author_id": 21004,
"author_profile": "https://Stackoverflow.com/users/21004",
"pm_score": 0,
"selected": false,
"text": " <add assembly=\"System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A\"/>\n </assemblies>\n <buildProviders>\n <add extension=\".rdlc\" type=\"Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </buildProviders>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
] |
177,965
|
<p>I've got some code that uses the Component Categories manager to load all of the classes that implement a particular category.</p>
<p>Is there an easy way to get a description, path and version information from the loaded DLL or EXE?</p>
|
[
{
"answer_id": 180047,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": true,
"text": "HKEY_CLASSES_ROOT\\CLSID\\{xxxxxxxxx-yyyyy-zzzz-aaaa-bbbbbbbbbbbbbb REG_SZ REG_SZ"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8446/"
] |
177,970
|
<p>I need a select from table which does not have column that tells when row was inserted, only <code>timestamp</code> column (values like: 0x0000000000530278). Some data was imported to the table yesterday and now I need to find out what exactly was imported :(</p>
<p>Is there a way to do it using only <code>timestamp</code> info? <a href="http://www.sqlhacks.com/index.php/Dates/Timestamp" rel="noreferrer">Here</a> I found that:</p>
<ul>
<li>Timestamp is a 8 bytes sequential Hex number, that has nothing to do with neither the date nor the time.</li>
<li>To get the current value of timestamp, use: @@DBTS.</li>
</ul>
<p>Perhaps there is a way to find what was <code>timestamp</code> value around specific time? That would help to form a select. Or maybe there is a well known solution?</p>
|
[
{
"answer_id": 178122,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 2,
"selected": false,
"text": "0x00000000000007D1\n0x00000000000007D2\n0x00000000000007D3\n0x00000000000007D4\n0x00000000000007D5\n"
},
{
"answer_id": 43631416,
"author": "ildanny",
"author_id": 7924145,
"author_profile": "https://Stackoverflow.com/users/7924145",
"pm_score": 1,
"selected": false,
"text": "WITH TS \nAS\n(\nSELECT \n L1.LastDateUpdated, COALESCE(L2.LastDateUpdated, {TS '2099-12-31 00:00:00'}) as LastDateUpdatedTo,\n L1.[TIMESTAMP], L2.[TIMESTAMP] as [TIMESTAMPTo]\nFROM \n(\n SELECT L1.[LastDateUpdated]\n ,L1.[TIMESTAMP]\n ,ROW_NUMBER() OVER (ORDER BY L1.[LastDateUpdated]) ID\n FROM [Log] L1\n) L1\nleft join \n(\n SELECT L2.[LastDateUpdated]\n ,L2.[TIMESTAMP]\n ,ROW_NUMBER() OVER (ORDER BY L2.[LastDateUpdated]) ID\n FROM [Log] L2\n) L2 \n ON L1.ID = L2.ID - 1\n)\nSELECT TS.LastDateUpdated, TS.LastDateUpdatedTo, * from [Invoices]\n inner join TS ON [Invoices].Timestamp between TS.Timestamp and \nTS.TIMESTAMPTo\nORDER BY TS.TIMESTAMPTo DESC\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23436/"
] |
177,974
|
<p>How can I test sending email from my application without flooding my inbox? </p>
<p>Is there a way to tell IIS/ASP.NET how to deliver email to a local folder for inspection?</p>
|
[
{
"answer_id": 178072,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 6,
"selected": true,
"text": " <configuration> \n <system.net> \n <mailSettings> \n <smtp deliveryMethod=\"SpecifiedPickupDirectory\"> \n <specifiedPickupDirectory pickupDirectoryLocation=\"c:\\LocalDir\"/> \n </smtp> \n </mailSettings> \n </system.net>\n </configuration>\n SmtpClient var smtpClient = new SmtpClient();\nsmtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;\nvar emailPickupDirectory = HostingEnvironment.MapPath(\"~/EmailPickup\");\nif (!Directory.Exists(emailPickupDirectory)) { \n Directory.CreateDirectory(emailPickupDirectory)\n}\nsmtpClient.PickupDirectoryLocation = emailPickupDirectory;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/177974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10676/"
] |
178,016
|
<p>I'm trying to select a specific HTML element in a document, for firefox i just use:</p>
<pre><code>xpathobj = document.evaluate(xpath, document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null);
</code></pre>
<p>which works fine. However when I try the IE equivilent:</p>
<pre><code>xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(document);
xmlDoc.setProperty("SelectionLanguage", "XPath");
xpathobj = xmlDoc.selectNodes(xpath);
</code></pre>
<p>I get no object returned. So my question is there an easy way to use XPath to get to the element I want in IE?
The XPath I'm using looks like </p>
<pre><code>/HTML/BODY/DIV[9]/DIV[2]
</code></pre>
|
[
{
"answer_id": 181704,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 0,
"selected": false,
"text": "xmlDoc.load(document); \n xmlDoc.loadXML(document.body.outerHTML)\n"
},
{
"answer_id": 182471,
"author": "user11198",
"author_id": 11198,
"author_profile": "https://Stackoverflow.com/users/11198",
"pm_score": 1,
"selected": false,
"text": "//Specific to project, here i know that the body element will always have the id \"top\"\n//but otherwise the element that is passed in should be first element in the xpath \n//statement eg. /HTML/BODY/DIV the element passed in should be HTML\nif(!element){\n element = $(\"top\");\n var xpathArrayIndex = 3;\n} else {\n var xpathArrayIndex = 1;\n}\n//split the xpath statement up\nvar xpathArray = xpath.split(\"/\");\n\nvar carryOn = true; \nwhile(carryOn){\n decendents = element.childElements();\n //check to see if we are at the end of the xpath statement\n if(xpathArrayIndex == xpathArray.length){\n return element;\n }\n //if there is only one decendent make it the next element\n if(decendents.size() == 1) {\n element = decendents.first();\n } else {\n //otherwise search the decendents for the next element\n element = getXPathElementByIndex(decendents, xpathArray[xpathArrayIndex]);\n }\n xpathArrayIndex++;\n}\n var decendentsArray = decendents.toArray();\n//seperate the index from the element name\nvar temp = xpathSegment.split(\"[\");\nvar elementName = temp[0];\n//get the index as a number eg. \"9]\" to 9\nvar elementIndex = +temp[1].replace(\"]\", \"\");\n//the number of matching elements\nvar count = 0;\n\n//keeps track of the number of iterations\nvar i = 0;\nwhile(count != elementIndex) {\n //if the decendent's name matches the xpath element name increment the count\n if(decendentsArray[i].nodeName == elementName){\n count++;\n }\n i++;\n}\nvar element = decendentsArray[i - 1];\nreturn element;\n"
},
{
"answer_id": 3286890,
"author": "hyperion",
"author_id": 396392,
"author_profile": "https://Stackoverflow.com/users/396392",
"pm_score": 1,
"selected": false,
"text": "function getXPathElement(xpath, element){\nif(!element){\n element = document;\n}\nvar xpathArray = xpath.split(\"/\");\n\nelement = findXPathRoot(xpathArray[0],xpathArray[1],element);\n\nfor(var i=1; i<xpathArray.length; i++){\n if(xpathArray[i].toLowerCase()==\"html\"){\n continue;\n }\n if(!element){\n return element;\n }\n element = getXPathElementByIndex(element.childNodes,xpathArray[i]); \n}\nreturn element;\n}\n\n\nfunction findXPathRoot(rootPath,htmlPath,element){\nif(rootPath == \"\"&&htmlPath.toLowerCase() == \"html\"){\n return element.documentElement;\n}\nreturn document.getElementsByTagName(rootPath)[0];\n}\nfunction getXPathElementByIndex(decendents, xpathSegment){\n//seperate the index from the element name\nvar temp = xpathSegment.split(\"[\");\nvar elementName = temp[0];\n//get the index as a number eg. \"9]\" to 9\nif(temp[1]){\n var elementIndex = temp[1].replace(\"]\", \"\");\n}else{\n var elementIndex = 1;\n}\n//the number of matching elements\nvar count = 0;\nfor(var i=0;i < decendents.length; i++){\n if (decendents[i].nodeName.toLowerCase() == elementName.toLowerCase()) {\n count++;\n if(count==elementIndex){\n return decendents[i];\n }\n }\n}\nreturn null;\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11198/"
] |
178,026
|
<p>We noticed that lots of bugs in our software developed in C# (or Java) cause a NullReferenceException.</p>
<p>Is there a reason why "null" has even been included in the language?</p>
<p>After all, if there were no "null", I would have no bug, right?</p>
<p>In other words, what feature in the language couldn't work without null?</p>
|
[
{
"answer_id": 178090,
"author": "Julien Hoarau",
"author_id": 12248,
"author_profile": "https://Stackoverflow.com/users/12248",
"pm_score": 8,
"selected": true,
"text": "static string AcceptNotNullObject(object! s)\n{\n return s.ToString();\n}\n"
},
{
"answer_id": 178092,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "0x00 object NIL Nothing null unitialized-value not-found default-value undefined-value None<T>"
},
{
"answer_id": 178186,
"author": "Kimoz",
"author_id": 7753,
"author_profile": "https://Stackoverflow.com/users/7753",
"pm_score": 2,
"selected": false,
"text": "MyResource resource;\ntry\n{\n resource = new MyResource();\n //\n // Do some work\n //\n}\nfinally\n{\n if (resource != null)\n resource.Close();\n}\n"
},
{
"answer_id": 178202,
"author": "bltxd",
"author_id": 11892,
"author_profile": "https://Stackoverflow.com/users/11892",
"pm_score": 2,
"selected": false,
"text": "let counter = ref 0;;\nlet next_counter_value () = (counter := !counter + 1; !counter);;\n type distributed_computation_result = NotYetAvailable | Result of float;;\nlet print_result r = match r with\n | Result(f) -> Printf.printf \"result is %f\\n\" f\n | NotYetAvailable -> Printf.printf \"result not yet available\\n\";;\n"
},
{
"answer_id": 178545,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 1,
"selected": false,
"text": "class A {\n B fieldb;\n}\n\nclass B {\n A fielda;\n}\n\nA a = new A() // a.fieldb is null\nB b = new B() { fielda = a } // b.fielda isnt\na.fieldb = b // now it isnt null anymore\n"
},
{
"answer_id": 15012087,
"author": "Eldritch Conundrum",
"author_id": 278044,
"author_profile": "https://Stackoverflow.com/users/278044",
"pm_score": 0,
"selected": false,
"text": "null null null null null"
},
{
"answer_id": 22798029,
"author": "Kaz",
"author_id": 1250772,
"author_profile": "https://Stackoverflow.com/users/1250772",
"pm_score": 0,
"selected": false,
"text": "aobj.blist.first().method() blist blist.first() ListNode ListNode"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25781/"
] |
178,068
|
<p>When stepping a program in Delphi 7, the CPU window sometimes pops up and then steps through that instructions. I find this an annoyance as I wish to only step Pascal Code. </p>
<p>Does anyone know how to disable this CPU pop-up? </p>
<p><strong><em>I would not be sorry if this window never ever shows.</em></strong> </p>
<p>It did not happen on Delphi 5 which was my previous IDE that I used for Delphi. I do use the Step-Over button mostly and only step-into when wanting to get into detail of a used (pascal) unit.</p>
|
[
{
"answer_id": 271483,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 4,
"selected": true,
"text": "Run -> Run to Next Source Line"
},
{
"answer_id": 2114093,
"author": "Seth",
"author_id": 141203,
"author_profile": "https://Stackoverflow.com/users/141203",
"pm_score": 4,
"selected": false,
"text": "Tools->Options->Debugger Options->Codegear Debuggers General Ignore non-user breakpoints"
},
{
"answer_id": 4465036,
"author": "Milan",
"author_id": 545301,
"author_profile": "https://Stackoverflow.com/users/545301",
"pm_score": 2,
"selected": false,
"text": "HKEY_CURRENT_USER/software/Borland/Delphi/6.0/Debugging/Integrated Debugging = 0\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
178,070
|
<p>We're working on a rich client (written in Flex) that is connected to a Java backend, using both RMI and JMS. I was thinking about implementing the client in a DDD fashion so that it has Repositories for the CRUD operations on the domain objects.</p>
<p>The problem is however that all backend communication happens asynchronous and there is no way for me to force the client for waiting to continue untill it received a response. That means that, at a low level, I can call a method on a Remote Object and I get a AsyncToken as a return value. I can then listen to events on the asynctoken to see whether the call has passed or failed. This however breaks the main idea behind a repository, to hide the technical details from the client.</p>
<p>There might be 2 options I guess:</p>
<ol>
<li>have the methods on the repository return the asynctoken, which seems like a messy solution to me</li>
<li>have the methods return an empty collection (for a findAll for instance) that will get filled when the response is received.</li>
</ol>
<p>Both have pros and cons and I would like to get some input from you guys.</p>
<p>(taking this further, what would be good caching strategies? Dependind on the situation, I don't want the repository to call the server each time I request all entities from it. How would that affect the signature of the methods on the repository.)</p>
|
[
{
"answer_id": 221946,
"author": "Richard Szalay",
"author_id": 3603,
"author_profile": "https://Stackoverflow.com/users/3603",
"pm_score": 2,
"selected": false,
"text": "public class CompleteAsyncToken : AsyncToken\n{\n public function CompleteAsyncToken(data : Object)\n {\n super(data);\n }\n\n public override addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false) : void\n {\n super.addEventListener(type, listener, useCapture, priority, useWeakReference);\n\n if (type == Event.COMPLETE)\n {\n // Don't just execute listener as EventDispatcher is not that simple\n super.dispatchCompleteEvent();\n super.removeEventListener(type, listener);\n }\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17255/"
] |
178,114
|
<p>Is there any easier solution in porting a windows manual-reset event to pthread,
than a pthread conditional-variable + pthread mutex + a flag if event is set or unset?</p>
|
[
{
"answer_id": 178962,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": false,
"text": "pthread_cond__* pthread_cond_wait #include <pthread.h>\n#include <stdbool.h>\n\nstruct mrevent {\n pthread_mutex_t mutex;\n pthread_cond_t cond;\n bool triggered;\n};\n\nvoid mrevent_init(struct mrevent *ev) {\n pthread_mutex_init(&ev->mutex, 0);\n pthread_cond_init(&ev->cond, 0);\n ev->triggered = false;\n}\n\nvoid mrevent_trigger(struct mrevent *ev) {\n pthread_mutex_lock(&ev->mutex);\n ev->triggered = true;\n pthread_cond_signal(&ev->cond);\n pthread_mutex_unlock(&ev->mutex);\n}\n\nvoid mrevent_reset(struct mrevent *ev) {\n pthread_mutex_lock(&ev->mutex);\n ev->triggered = false;\n pthread_mutex_unlock(&ev->mutex);\n}\n\nvoid mrevent_wait(struct mrevent *ev) {\n pthread_mutex_lock(&ev->mutex);\n while (!ev->triggered)\n pthread_cond_wait(&ev->cond, &ev->mutex);\n pthread_mutex_unlock(&ev->mutex);\n}\n ev->mutex"
},
{
"answer_id": 9490158,
"author": "Vincent",
"author_id": 137511,
"author_profile": "https://Stackoverflow.com/users/137511",
"pm_score": 2,
"selected": false,
"text": "void LinuxEvent::wait()\n{\n pthread_mutex_lock(&mutex);\n\n int signalValue = signalCounter;\n\n while (!signaled && signalValue == signalCounter)\n {\n pthread_cond_wait(&condition, &mutex);\n }\n\n pthread_mutex_unlock(&mutex);\n}\n\nvoid LinuxEvent::signal()\n{\n pthread_mutex_lock(&mutex);\n\n signaled = true;\n signalCounter++;\n pthread_cond_broadcast(&condition);\n\n pthread_mutex_unlock(&mutex);\n}\n\nvoid LinuxEvent::reset()\n{\n pthread_mutex_lock(&mutex);\n signaled = false;\n pthread_mutex_unlock(&mutex);\n}\n"
},
{
"answer_id": 10116327,
"author": "lucho",
"author_id": 1327947,
"author_profile": "https://Stackoverflow.com/users/1327947",
"pm_score": 3,
"selected": false,
"text": "char buf[256]; // 256 is arbitrary\nwhile( read(pipe_out, buf, sizeof(buf)) == sizeof(buf));\n"
},
{
"answer_id": 11260894,
"author": "Angel Genchev",
"author_id": 1491030,
"author_profile": "https://Stackoverflow.com/users/1491030",
"pm_score": 3,
"selected": false,
"text": "WaitForMultipleObjects(...) WaitForMultipleObjects poll(...) select pselect epoll Futex futex_fd select poll epoll int pipefd[2];\nchar buf[256]; // 256 is arbitrary\nint r = pipe2(pipefd, O_NONBLOCK);\n\nvoid setEvent()\n{\n write(pipefd[1], &buf, 1); \n}\n\nvoid resetEvent() { while( read(pipefd[0], &buf, sizeof(buf)) > 0 ) {;} }\n\nvoid waitForEvent(int timeoutMS)\n{ \n struct pollfd fds[1];\n fds[0].fd = pipefd[0];\n fds[0].events = POLLRDNORM;\n poll(fds, 1, timeoutMS);\n}\n\n// finalize:\nclose(pipefd[0]);\nclose(pipefd[1]);\n"
},
{
"answer_id": 14460865,
"author": "Mahmoud Al-Qudsi",
"author_id": 17027,
"author_profile": "https://Stackoverflow.com/users/17027",
"pm_score": 2,
"selected": false,
"text": "WaitForSingleObject WaitForMultipleObject"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
178,128
|
<p>Let's say I have to implement a piece of T-SQL code that must return a table as result. I can implement a table-valued function or else a stored procedure that returns a set of rows. What should I use?</p>
<p>In short, what I want to know is: </p>
<p><strong>Which are the main differences between functions and stored procedures?</strong> What considerations do I have to take into account for using one or the other?</p>
|
[
{
"answer_id": 178150,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 3,
"selected": false,
"text": "SELECT function_name(field1) FROM table\n"
},
{
"answer_id": 228148,
"author": "6eorge Jetson",
"author_id": 23422,
"author_profile": "https://Stackoverflow.com/users/23422",
"pm_score": 2,
"selected": false,
"text": "SELECT *\nFROM dbo.tvfVeryLargeResultset1(@myVar1) tvf1\nINNER JOIN dbo.tvfVeryLargeResultset1(@myVar2) tvf2\n ON (tvf1.JoinId = tvf2.JoinId)\n"
},
{
"answer_id": 6840115,
"author": "Paul Grimshaw",
"author_id": 864763,
"author_profile": "https://Stackoverflow.com/users/864763",
"pm_score": 3,
"selected": false,
"text": "CREATE FUNCTION dbo.getSitePermissions(@RegionID int, @optPersonID int, optSiteID int)\nAS\nRETURN \n SELECT DISTINCT SiteID, PersonID\n FROM dbo.SiteViewPermissions\n WHERE (@optPersonID IS NULL OR @optPersonID = PersonID)\n AND (@optSiteID IS NULL OR @optSiteID = SiteID)\n AND @RegionID = RegionID\n SELECT * FROM dbo.getSitePermissions(@RegionID) WHERE SiteID = 1\n"
},
{
"answer_id": 15749579,
"author": "nathan1138",
"author_id": 2028133,
"author_profile": "https://Stackoverflow.com/users/2028133",
"pm_score": 3,
"selected": false,
"text": "WHERE HAVING SELECT JOIN JOIN"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] |
178,135
|
<p>I have a UserControl (Composite control) that can be shown as the following pseudo XAML code:</p>
<pre><code><UserControl>
<DockPanel>
<TextBox />
<Button />
</DockPanel>
</UserControl>
</code></pre>
<p>I use this custom control in a bunch of places and style some of them with a WPF Style. This style sets the Background property of the UserControl to a color. But this background color is drawn on UserControl's background surface, but I want it to be drawn only on TextBox control's background. This is what I get (Color=Red):</p>
<p><a href="http://img261.imageshack.us/img261/8600/62858047wi3.png" rel="nofollow noreferrer">alt text http://img261.imageshack.us/img261/8600/62858047wi3.png</a></p>
<p>If I bind the Background property of the UserControl to my TextBox control's background property, I get the following one:</p>
<p><a href="http://img111.imageshack.us/img111/1637/30765795kw5.png" rel="nofollow noreferrer">alt text http://img111.imageshack.us/img111/1637/30765795kw5.png</a></p>
<p>Now it also paints the background of the inner TextBox control but the Background color of the UserControl still exists. Are there any ways to remove that painting of UserControl's background?</p>
|
[
{
"answer_id": 178427,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 3,
"selected": false,
"text": "<UserControl x:Name=\"_root\" ...>\n ...\n <Button Background=\"{Binding ButtonBackground, ElementName=_root}\"/>\n</UserControl>\n TextBox"
},
{
"answer_id": 178655,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 1,
"selected": false,
"text": "<UserControl\n x:Class=\"StackOverflowQuestion.UserControl1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Height=\"300\"\n Width=\"300\"\n>\n <UserControl.Resources>\n <Style x:Key=\"textBoxStyle\" TargetType=\"{x:Type TextBox}\">\n <Setter Property=\"Background\" Value=\"Red\"/>\n </Style>\n </UserControl.Resources>\n <DockPanel>\n <TextBox Text=\"Test\" Style=\"{StaticResource textBoxStyle}\"/>\n <Button/>\n </DockPanel>\n</UserControl>\n <UserControl x:Name=\"_root\" ...>\n <TextBox Background=\"{Binding TextBoxBackground, ElementName=_root}\"/>\n <Button/>\n</UserControl>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39/"
] |
178,138
|
<p>I fear this is probably a bit of a dummy question, but it has me pretty stumped.</p>
<p>I'm looking for the simplest way possible to pass a method of an object into a procedure, so that the procedure can call the object's method (e.g. after a timeout, or maybe in a different thread). So basically I want to:</p>
<ul>
<li>Capture a reference to an object's method.</li>
<li>Pass that reference to a procedure.</li>
<li>Using that reference, call the object's method from the procedure.</li>
</ul>
<p>I figure I could achieve the same effect using interfaces, but I thought there was another way, since this "procedure of object" type declaration exists.</p>
<p>The following <em>doesn't</em> work, but might it help explain where I'm confused...?</p>
<pre><code>interface
TCallbackMethod = procedure of object;
TCallbackObject = class
procedure CallbackMethodImpl;
procedure SetupCallback;
end;
implementation
procedure CallbackTheCallback(const callbackMethod: TCallbackMethod);
begin
callbackMethod();
end;
procedure TCallbackObject.CallbackMethodImpl;
begin
// Do whatever.
end;
procedure TCallbackObject.SetupCallback;
begin
// following line doesn't compile - it fails with "E2036 Variable required"
CallbackTheCallback(@self.CallbackMethodImpl);
end;
</code></pre>
<p>(Once the question is answered I'll remove the above code unless it aids the explanation somehow.)</p>
|
[
{
"answer_id": 178174,
"author": "Roman Ganz",
"author_id": 17981,
"author_profile": "https://Stackoverflow.com/users/17981",
"pm_score": 5,
"selected": true,
"text": "procedure TCallbackObject.SetupCallback;\nbegin\n CallbackTheCallback(CallbackMethodImpl);\nend;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11961/"
] |
178,144
|
<p>Originally I thought to ask if there would be an easy way to provide an automatically managed last update field with MS Access.</p>
<p>After some googling I found following approach:</p>
<pre><code>Private Sub Form_Dirty(Cancel As Integer)
Me.Last_Update = Date()
End Sub
</code></pre>
<p>Which seems to do the job. I thought I'd share it with others too (and if somebody has some good points that should be considered, feel free to share them)</p>
|
[
{
"answer_id": 178170,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 2,
"selected": false,
"text": "CREATE TRIGGER [Table_stampUpdates] ON [dbo].[Table]\n FOR Update \nAS \nBEGIN \nUPDATE Table\nSET \nmodified_by = right(system_user, len(system_user) - charindex('\\', system_user)), modified_on = getdate() \nFROM Table inner join inserted on Table.PrimaryKey = Inserted.PrimaryKey\n END\n"
},
{
"answer_id": 178834,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 2,
"selected": false,
"text": "CHECK CREATE TABLE MyTable \n(\n key_col INTEGER NOT NULL UNIQUE, \n data_col INTEGER NOT NULL\n)\n;\nALTER TABLE MyTable ADD\n my_timestamp_col DATETIME \n DEFAULT NOW() \n NOT NULL\n;\nALTER TABLE MyTable ADD\n CONSTRAINT my_timestamp_col__must_be_current_timestamp\n CHECK (my_timestamp_col = NOW())\n;\n PROCEDURE SELECT PROC CREATE PROCEDURE MyProc \n(\n arg_key INTEGER, \n arg_new_data INTEGER\n)\nAS \nUPDATE MyTable\n SET data_col = arg_new_data, \n my_timestamp_col = NOW()\n WHERE key_col = arg_key\n;\nREVOKE UPDATE ON MyTable FROM PUBLIC\n;\nGRANT UPDATE ON MyProc TO PUBLIC\n;\n PROC PROC"
},
{
"answer_id": 74277151,
"author": "timbald",
"author_id": 20388639,
"author_profile": "https://Stackoverflow.com/users/20388639",
"pm_score": 0,
"selected": false,
"text": "CurrentProject.Connection.Execute \"ALTER TABLE TableName ADD CONSTRAINT NameOfConstraint CHECK (ExpressionToCheck);\"\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28482/"
] |
178,147
|
<p>I have an application in C# (2.0 running on XP embedded) that is communicating with a 'watchdog' that is implemented as a Windows Service. When the device boots, this service typically takes some time to start. I'd like to check, from my code, if the service is running. How can I accomplish this?</p>
|
[
{
"answer_id": 178162,
"author": "Carl",
"author_id": 951280,
"author_profile": "https://Stackoverflow.com/users/951280",
"pm_score": 10,
"selected": true,
"text": "System.ServiceProcess using System.ServiceProcess;\n\nServiceController sc = new ServiceController(SERVICENAME);\n\nswitch (sc.Status)\n{\n case ServiceControllerStatus.Running:\n return \"Running\";\n case ServiceControllerStatus.Stopped:\n return \"Stopped\";\n case ServiceControllerStatus.Paused:\n return \"Paused\";\n case ServiceControllerStatus.StopPending:\n return \"Stopping\";\n case ServiceControllerStatus.StartPending:\n return \"Starting\";\n default:\n return \"Status Changing\";\n}\n sc.WaitforStatus() sc.Refresh()"
},
{
"answer_id": 24381150,
"author": "rhatwar007",
"author_id": 3248226,
"author_profile": "https://Stackoverflow.com/users/3248226",
"pm_score": 4,
"selected": false,
"text": "ServiceController[] services = ServiceController.GetServices();\nforeach(ServiceController service in services)\n{\n Console.WriteLine(service.ServiceName+\"==\"+ service.Status);\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
] |
178,173
|
<p>I'd like to calculate the age of the messages in an Exchange mailbox to make sure they sit there for at least a minute before our program (C++, MAPI) processes them. This way the <a href="http://www.cloudmark.com/server/" rel="nofollow noreferrer">spam filter we use</a> should have enough time to do its job.</p>
<p>Because the time on the PC where our program runs might be different from the time used by the Exchange server, our program has to read the server time via MAPI. </p>
<p>Is there an elegant solution to it? One way I can think of is to modify some Item and immediately read its <em>PR_LAST_MODIFICATION_TIME</em>, but I'd like to avoid that.</p>
<p><strong>Edit:</strong><br>
Our program is a batch job that runs every 10 minutes and reads the journal mailbox.</p>
|
[
{
"answer_id": 178201,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "PR_MESSAGE_DELIVERY_TIME PR_MESSAGE_DELIVERY_TIME"
},
{
"answer_id": 181012,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 2,
"selected": true,
"text": "n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4097/"
] |
178,187
|
<p>I am designing a class for log entries of my mail server. I have parsed the log entries and created the class hierarchy. Now I need to save the in memory representation to the disk. I need to save it to multiple destinations like mysql and disk files. I am at a loss to find out the proper way to design the persistence mechanism. The challenges are:</p>
<ol>
<li><p>How to pass persistence
initialization information like
filename, db connection parameters
passed to them. The options I can
think of are all ugly for eg:</p>
<p>1.1 Constructor: it becomes ugly as I
add more persistence.</p>
<p>1.2 Method: Object.mysql_params(" "),
again butt ugly</p></li>
<li><p>"Correct" method name to call each
persistance mechanism: eg:
Object.save_mysql, Object.save_file,
or Object.save (mysql) and
Object.save(file)</p></li>
</ol>
<p>I am sure there is some pattern to solve this particular problem. I am using ruby as my language, with out any rails, ie pure ruby code. Any clue is much welcome.</p>
<p>raj</p>
|
[
{
"answer_id": 178504,
"author": "Jon Wood",
"author_id": 25258,
"author_profile": "https://Stackoverflow.com/users/25258",
"pm_score": 3,
"selected": true,
"text": "class Object\n cattr_accessor :store\n\n def save\n @@store.save(self)\n end\nend\n\nclass MySQLObjectStore\n def initialize(connection_string)\n # Connect to DB etc...\n end\n\n def save(obj)\n # Write to database\n end\nend\n\nstore = MySQLObjectStore.new(\"user:password@localhost/database\")\nObject.store = store\n\nobj = Object.new(foo)\nobj.save\n"
},
{
"answer_id": 178547,
"author": "Turp",
"author_id": 24856,
"author_profile": "https://Stackoverflow.com/users/24856",
"pm_score": 1,
"selected": false,
"text": "lw = FileLogWriter.new \"log_file.txt\"\nlw.Write(log)\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25453/"
] |
178,188
|
<p>So, bitfields. Specifically, large bitfields. I understand how to manipulate individual values in a bitfield, but how would I go about doing this on a large set, such as say:</p>
<pre><code>uint[] bitfield = new uint[4] { 0x0080000, 0x00FA3020, 0x00C8000, 0x0FF00D0 };
</code></pre>
<p>The specific problem I'm having is doing left and right shifts that carry through across the whole array. So for instance, if I did a <code>>> 4</code> on the above array, I'd end up with:</p>
<pre><code>uint[4] { 0x0008000, 0x000FA302, 0x000C800, 0x00FF00D };
</code></pre>
<p>Now, an (overly) simplistic algorithm here might look something like (this is me writting code on the fly):</p>
<pre><code>int shift = 4;
for (int i = 0; i <= shift; i++) {
for (int j = bitfield.GetUpperBound(0); j > 0; j--) {
bitfield[j] = bitfield[j] >> 1;
bitfield[j] = bitfield[j] + ((bitfield[j-1] & 1) << (sizeof(uint)*8));
}
bitfield[0] = bitfield[0] >> 1;
}
</code></pre>
<p>Is there anything built in that might ease working with this sort of data? </p>
|
[
{
"answer_id": 178623,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 0,
"selected": false,
"text": "public static class BitArrayExtensions\n{\n public static void DownShift(this BitArray bitArray, int places)\n {\n for (var i = 0; i < bitArray.Length; i++)\n {\n bitArray[i] = i + places < bitArray.Length && bitArray[i + places];\n }\n }\n\n public static void UpShift(this BitArray bitArray, int places)\n {\n for (var i = bitArray.Length - 1; i >= 0; i--)\n {\n bitArray[i] = i - places >= 0 && bitArray[i - places];\n }\n }\n}\n BitArray int uint BitArray BitArray int"
},
{
"answer_id": 179067,
"author": "Juan Pablo Califano",
"author_id": 24170,
"author_profile": "https://Stackoverflow.com/users/24170",
"pm_score": 1,
"selected": false,
"text": " public static void ShiftLeft(uint[] bitfield, int shift) {\n\n if(shift < 0 || shift > 31) {\n // handle error here\n return;\n }\n\n int len = bitfield.Length;\n int i = len - 1;\n uint prev = 0;\n\n while(i >= 0) {\n uint tmp = bitfield[i];\n bitfield[i] = bitfield[i] << shift;\n if(i < len - 1) {\n bitfield[i] |= (uint)(prev & (1 >> shift) - 1 ) >> (32 - shift);\n }\n prev = tmp;\n\n i--;\n }\n\n }\n\n public static void ShiftRight(uint[] bitfield, int shift) {\n\n if(shift < 0 || shift > 31) {\n // handle error here\n return;\n }\n int len = bitfield.Length;\n int i = 0;\n uint prev = 0;\n\n while(i < len) {\n uint tmp = bitfield[i];\n bitfield[i] = bitfield[i] >> shift;\n if(i > 0) {\n bitfield[i] |= (uint)(prev & (1 << shift) - 1 ) << (32 - shift);\n }\n prev = tmp;\n\n i++;\n }\n\n }\n public static void ShiftLeft(uint[] bitfield, int shift) {\n\n if(shift < 0) {\n // error\n return;\n } \n\n int intsShift = shift >> 5;\n\n if(intsShift > 0) {\n if(intsShift > bitfield.Length) {\n // error\n return;\n }\n\n for(int j=0;j < bitfield.Length;j++) {\n if(j > intsShift + 1) { \n bitfield[j] = 0;\n } else {\n bitfield[j] = bitfield[j+intsShift];\n }\n }\n\n BitSetUtils.ShiftLeft(bitfield,shift - intsShift * 32);\n return;\n }\n\n int len = bitfield.Length;\n int i = len - 1;\n uint prev = 0;\n\n while(i >= 0) {\n uint tmp = bitfield[i];\n bitfield[i] = bitfield[i] << shift;\n if(i < len - 1) {\n bitfield[i] |= (uint)(prev & (1 >> shift) - 1 ) >> (32 - shift);\n }\n prev = tmp;\n\n i--;\n }\n\n }\n\n public static void ShiftRight(uint[] bitfield, int shift) {\n\n if(shift < 0) {\n // error\n return;\n } \n\n int intsShift = shift >> 5;\n\n if(intsShift > 0) {\n if(intsShift > bitfield.Length) {\n // error\n return;\n }\n\n for(int j=bitfield.Length-1;j >= 0;j--) {\n if(j >= intsShift) { \n bitfield[j] = bitfield[j-intsShift];\n } else {\n bitfield[j] = 0;\n }\n }\n\n BitSetUtils.ShiftRight(bitfield,shift - intsShift * 32);\n return;\n }\n\n\n int len = bitfield.Length;\n int i = 0;\n uint prev = 0;\n\n while(i < len) {\n uint tmp = bitfield[i];\n bitfield[i] = bitfield[i] >> shift;\n if(i > 0) {\n bitfield[i] |= (uint)(prev & (1 << shift) - 1 ) << (32 - shift);\n }\n prev = tmp;\n\n i++;\n }\n\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
178,199
|
<p>In PHP I can name my array indices so that I may have something like:</p>
<pre><code>$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'),
1 => Array('id' => 2, 'name' => 'Dora The Explorer'));
</code></pre>
<p>Is this possible in Python?</p>
|
[
{
"answer_id": 178211,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 3,
"selected": false,
"text": "a = {\"id\": 1, \"name\":\"Sesame Street\"}\n"
},
{
"answer_id": 178213,
"author": "Michael Twomey",
"author_id": 995,
"author_profile": "https://Stackoverflow.com/users/995",
"pm_score": 7,
"selected": true,
"text": "shows = [\n {\"id\": 1, \"name\": \"Sesaeme Street\"},\n {\"id\": 2, \"name\": \"Dora The Explorer\"},\n]\n"
},
{
"answer_id": 178224,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 5,
"selected": false,
"text": "showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}] from operator import attrgetter\n\nshowlist.sort(key=attrgetter('id'))\n shows = {1: 'Sesame Street', 2:'Dora the Explorer'}\n"
},
{
"answer_id": 178668,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 4,
"selected": false,
"text": "import collections\nperson = collections.namedtuple('Person', 'id name age')\n\nme = person(id=1, age=1e15, name='Dan')\nyou = person(2, 'Somebody', 31.4159)\n\nassert me.age == me[2] # can access fields by either name or position\n"
},
{
"answer_id": 199271,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "def MyStruct(item1=0, item2=0, item3=0):\n \"\"\"Return a new Position tuple.\"\"\"\n class MyStruct(tuple):\n @property\n def item1(self):\n return self[0]\n @property\n def item2(self):\n return self[1]\n @property\n def item3(self):\n return self[2]\n try:\n # case where first argument a 3-tuple \n return MyStruct(item1)\n except:\n return MyStruct((item1, item2, item3))\n a = MyStruct(1,2,3)\n print a[0]==a.item1\n"
},
{
"answer_id": 39307547,
"author": "Sreekanth",
"author_id": 6338857,
"author_profile": "https://Stackoverflow.com/users/6338857",
"pm_score": 2,
"selected": false,
"text": "pandas Series book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],\n index=['Title', 'Author', 'Number of pages', 'Price'])\nprint book['Author']\n"
},
{
"answer_id": 62209288,
"author": "Joshna",
"author_id": 12157462,
"author_profile": "https://Stackoverflow.com/users/12157462",
"pm_score": 2,
"selected": false,
"text": "dictionary = {\"name\": \"python\", \"age\": 12}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
178,200
|
<p>I have the following JSP code, that protects my web page and displays it only to know IP's</p>
<pre><code>String ip_h = request.getRemoteAddr();
String host_h = request.getRemoteHost();
String iplist[] = new String[1];
iplist[0] = "127.0.0.1";
iplist[1] = "10.217.106.248";
int count = iplist.length;
boolean flag = false;
int zz = 0;
//return;
System.out.println(host_h);
while ( (flag==false) && ( zz < count) )
{
if (ip_h.equals(iplist[zz]) || host_h.equals(iplist[zz]) )
{
flag = true;
}
zz++;
}
</code></pre>
<p>However, I would to rather check for subnet ranges, i.e. all users belonging to 10.217.0.0/16 are allowed.</p>
<p>How do I do this?</p>
|
[
{
"answer_id": 178293,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 0,
"selected": false,
"text": "Subnet"
},
{
"answer_id": 178339,
"author": "Lazarin",
"author_id": 24124,
"author_profile": "https://Stackoverflow.com/users/24124",
"pm_score": 0,
"selected": false,
"text": "public class IPUtil\n{\n\n private static int[] split(String ip)\n {\n int[] result = new int[4];\n StringTokenizer st = new StringTokenizer(ip, \".\");\n for (int i = 0; i < 4; i++)\n {\n result[i] = Integer.parseInt(st.nextToken());\n }\n return result;\n }\n\n public static boolean matches(String visitorIpString, String ipString, String maskString)\n {\n int[] vip = split(visitorIpString);\n int[] ip = split(ipString);\n int[] mask = split(maskString);\n\n for (int i = 0; i < 4; i++)\n {\n if ((vip[i] & mask[i]) != ip[i])\n {\n return false;\n }\n }\n return true;\n }\n\n public static void main(String[] args)\n {\n\n String ip = \"192.168.12.0\";\n String mask = \"255.255.255.0\";\n String visitorIP = \"192.168.12.55\";\n\n System.out.println(matches(visitorIP, ip, mask));\n }\n}\n"
},
{
"answer_id": 178627,
"author": "skaffman",
"author_id": 21234,
"author_profile": "https://Stackoverflow.com/users/21234",
"pm_score": 2,
"selected": false,
"text": "import java.net.InetAddress;\nimport java.net.UnknownHostException;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.collections15.Predicate;\nimport org.apache.commons.lang.builder.EqualsBuilder;\nimport org.apache.commons.lang.builder.HashCodeBuilder;\n\n/**\n * I am a filter used to determine if a given IP Address is covered by the IP range specified in \n * the constructor. I accept IP ranges in the form of full single IP addresses, e.g. 10.1.0.23\n * or network/netmask pairs in CIDR format e.g. 10.1.0.0/16\n */\npublic class IpRangeFilter implements Predicate<InetAddress> {\n\n private final long network;\n private final long netmask;\n\n private final String ipRange;\n\n private static final Pattern PATTERN = Pattern.compile(\"((?:\\\\d|\\\\.)+)(?:/(\\\\d{1,2}))?\");\n\n public IpRangeFilter(String ipRange) throws UnknownHostException {\n Matcher matcher = PATTERN.matcher(ipRange);\n if (matcher.matches()) {\n String networkPart = matcher.group(1);\n String cidrPart = matcher.group(2);\n\n long netmask = 0;\n int cidr = cidrPart == null ? 32 : Integer.parseInt(cidrPart);\n for (int pos = 0; pos < 32; ++pos) {\n if (pos >= 32-cidr) {\n netmask |= (1L << pos);\n }\n }\n\n this.network = netmask & toMask(InetAddress.getByName(networkPart));\n this.netmask = netmask;\n this.ipRange = ipRange;\n\n } else {\n throw new IllegalArgumentException(\"Not a valid IP range: \" + ipRange);\n }\n }\n\n public String getIpRange() {\n return ipRange;\n }\n\n public boolean evaluate(InetAddress address) {\n return isInRange(address);\n }\n\n public boolean isInRange(InetAddress address) {\n return network == (toMask(address) & netmask);\n }\n\n /**\n * Convert the bytes in the InetAddress into a bit mask stored as a long.\n * We could use int's here, but java represents those in as signed numbers, which can be a pain \n * when debugging.\n * @see http://www.captain.at/howto-java-convert-binary-data.php\n */\n static long toMask(InetAddress address) {\n byte[] data = address.getAddress();\n long accum = 0;\n int idx = 3;\n for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) {\n accum |= ( (long)( data[idx] & 0xff ) ) << shiftBy;\n idx--;\n }\n return accum;\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
178,210
|
<p>We are building a multi-tenant website in ASP.NET, and we must let each customer configure their own security model. They must be able to define their own roles, and put users in those roles. What is the best way to do this?</p>
<p>There are tons of simple examples of page_load events that have code like:</p>
<pre><code> if (!user.InGroup("Admin")
Response.Redirect("/NoAccess.aspx");
</code></pre>
<p>But that hard codes the groups and permissions in the code. How can I make it user configurable?</p>
|
[
{
"answer_id": 178238,
"author": "ullmark",
"author_id": 23044,
"author_profile": "https://Stackoverflow.com/users/23044",
"pm_score": 0,
"selected": false,
"text": "foreach(var group in ThisPageConfiguration.AcceptedRoleNames)\nif (user.IsInRole(group))\n...\n"
},
{
"answer_id": 178295,
"author": "Turnkey",
"author_id": 13144,
"author_profile": "https://Stackoverflow.com/users/13144",
"pm_score": 3,
"selected": true,
"text": "Table \"Role\"\nRoleId, TenantId, Role\n\nTable \"PagePermissions\"\nPageId, RoleId\n\nTable \"UserRoles\"\nUserId, RoleId\n Select PageId FROM \nUserRoles UR INNER JOIN PagePermissions PP\nON UR.RoleId = PP.RoleID\nWHERE UR.Userid = @UserId AND PP.PageID = @PageId\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
178,215
|
<p>We are using log4j behind a selfmade wrapper. We plan to use much more features of it now. </p>
<p>Should we update to logback ?</p>
<p>(I mean the framework not a facade like SLF4J)</p>
|
[
{
"answer_id": 22115384,
"author": "Christian",
"author_id": 690771,
"author_profile": "https://Stackoverflow.com/users/690771",
"pm_score": 6,
"selected": false,
"text": "logger.debug(\"Temperature set to {}. Old temperature was {}.\", t, oldT);"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
178,216
|
<p>In Informix, how can I cast a <code>char(8)</code> type into a <code>money</code> type, so that I can compare it to another <code>money</code> type?</p>
<p>Using "<code>tblAid.amt::money as aid_amt</code>" did not work.
Using "<code>(tblAid.amt * 1) AS aid_amt</code>" did not work.</p>
|
[
{
"answer_id": 185890,
"author": "SKapsal",
"author_id": 24721,
"author_profile": "https://Stackoverflow.com/users/24721",
"pm_score": 4,
"selected": true,
"text": "select (disb_amt::NUMERIC) disb_amt from tmp_kygrants;\n"
},
{
"answer_id": 188635,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "SELECT some_column::MONEY FROM WhereEver;\n SELECT CAST(some_column AS MONEY(8,2)) FROM WhereEver;\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13832/"
] |
178,233
|
<p>Does anyone know how to use the credential cache or network credential to get the user's personal info from the Active Directory using C# or VB? I need to get personal info such as name, telephone ID and so on.</p>
|
[
{
"answer_id": 217013,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 1,
"selected": false,
"text": "DirectorySearcher ds = new DirectorySearcher(\"LDAP://DC=test,dc=com\");\nds.Filter = String.Format(\"&(samaccountname={0})(objectcategory=user)\",Environment.Username);\nds.PropertiesToLoad.Add(\"telephoneNumber\");\nds.PropertiesToLoad.Add(\"Name\");\n// add all properties here\nDirectoryEntry de = ds.FindOne();\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178233",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23491/"
] |
178,247
|
<p>I have minified my javascript and my css.</p>
<p>Now, Which is better?</p>
<pre><code><script type="text/javascript">
<?
$r = file_get_contents('min.js');
if($r) echo $r;
?>
</script>
</code></pre>
<p>OR</p>
<pre><code><script type="text/javascript" src="min.js"></script>
</code></pre>
<p>Same question for CSS.</p>
<p>If the answer is 'sometimes because browsers fetch files simultaneously?' Which browsers, and what are examples of the times in either scenario.</p>
|
[
{
"answer_id": 178269,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 6,
"selected": true,
"text": "<script type=\"text/javascript\" src=\"min.js\"></script>\n src <script type=\"text/javascript\" src=\"min.js?version=20081007134916\"></script>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
] |
178,255
|
<p>I'm talking about c# <del>3.5</del> 3.0.
I know how to do it when cache or ServiceProvider can have only one instance for the whole application. In this case ServiceProvider can look like this</p>
<pre><code>public static class Service<T>
{
public static T Value {get; set;}
}
</code></pre>
<p>and can be used for different types like this:</p>
<pre><code>Service<IDbConnection>.Value = new SqlConnection("...");
Service<IDesigner>.Value = ...;
//...
IDbCommand cmd = Service<IDbConnection>.Value.CreateCommand();
</code></pre>
<p>Static cache is also easy:</p>
<pre><code>public static class Cache<T>
{
private static Dictionary<int, T> cache = new Dictionary<int, T>();
public static void Add(int key, T value)
{
cache.Add(key, value);
}
public static T Find(int key)
{
return cache[key];
}
}
</code></pre>
<p>and can be used like this:</p>
<pre><code>Cache<string>.Add(1, "test");
Cache<DateTime>.Add(2, DateTime.Now);
//...
string found = Cache<string>.Find(1);
</code></pre>
<p><br>
<strong>My question is</strong>: how can I create similiar cache or service provider when I want to have 2 or more different instances of each. Here is example code, how I want to use service provider:</p>
<pre><code>ServiceProvider provider = new ServiceProvider();
provider.Add<IDbConnection>(new SqlConnection("..."));
provider.Add<IDesigner>(...);
//...
ServiceProvider provider1 = new ServiceProvider();
provider1.Add<IDbConnection>(new SqlConnection("..."));
//...
//...
IDbCommand cmd1 = provider.GetService<IDbConnection>().CreateCommand();
IDbCommand cmd2 = provider1.GetService<IDbConnection>().CreateCommand();
</code></pre>
<p>The only implementation that I have in my head is using <strong>casting which I want to avoid</strong>.</p>
<pre><code>public class ServiceProvider
{
private Dictionary<Type, object> services = new Dictionary<Type, object>();
public void Add<T>(T value)
{
services.Add(typeof(T), value);
}
public T GetService<T>()
{
return (T) services[typeof (T)];
}
}
</code></pre>
|
[
{
"answer_id": 186847,
"author": "James Hart",
"author_id": 5755,
"author_profile": "https://Stackoverflow.com/users/5755",
"pm_score": 1,
"selected": false,
"text": " public class TypeDictionary \n { \n private class InnerTypeDictionary<T>\n {\n static WeakDictionary<TypeDictionary, T> _innerDictionary = new WeakDictionary<TypeDictionary, T>();\n public static void Add(TypeDictionary dic, T value)\n {\n _innerDictionary.Add(dic, value);\n }\n\n public static T GetValue(TypeDictionary dic)\n {\n return _innerDictionary[dic];\n }\n }\n\n public void Add<T>(T value)\n {\n InnerTypeDictionary<T>.Add(this, value);\n }\n\n public T GetValue<T>()\n {\n return InnerTypeDictionary<T>.GetValue(this);\n }\n }\n System.Type"
},
{
"answer_id": 189329,
"author": "SeeR",
"author_id": 22569,
"author_profile": "https://Stackoverflow.com/users/22569",
"pm_score": 0,
"selected": false,
"text": "public class ServiceContainer : IDisposable\n{\n readonly IList<IService> services = new List<IService>();\n\n public void Add<T>(T service)\n {\n Add<T,T>(service);\n }\n\n public void Add<Key, T>(T service) where T : Key\n {\n services.Add(new Service<Key>(this, service));\n }\n\n public void Dispose()\n {\n foreach(var service in services)\n service.Remove(this);\n }\n\n ~ServiceContainer()\n {\n Dispose();\n }\n\n public T Get<T>()\n {\n return Service<T>.Get(this);\n }\n}\n\npublic interface IService\n{\n void Remove(object parent);\n}\n\npublic class Service<T> : IService\n{\n static readonly Dictionary<object, T> services = new Dictionary<object, T>();\n\n public Service(object parent, T service)\n {\n services.Add(parent, service);\n }\n\n public void Remove(object parent)\n {\n services.Remove(parent);\n }\n\n public static T Get(object parent)\n {\n return services[parent];\n }\n}\n Dictionary<WeakReference, T> services Dictionary<object, T> services Dictionary<WeakReference, WeakReference<T>> services\n"
},
{
"answer_id": 223299,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 0,
"selected": false,
"text": "var service = provider.GetService<MyService>();\nservice.DoSomething();\nservice.DoSomethingElse();\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22569/"
] |
178,257
|
<p>Huge files take forever to load and work with in vim, due to syntax-highlighting.</p>
<p>I'm looking for a way to limit size of highlighted files, such that files larger than (say) 10MB will be colorless.</p>
|
[
{
"answer_id": 559052,
"author": "Paul Oyster",
"author_id": 38193,
"author_profile": "https://Stackoverflow.com/users/38193",
"pm_score": 6,
"selected": true,
"text": "autocmd BufWinEnter * if line2byte(line(\"$\") + 1) > 1000000 | syntax clear | endif\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6984/"
] |
178,263
|
<p>I am testing a web app that writes cookies to subdomain.thisdomain.com and several subfolders within that. I'm looking for JavaScript that I can put into a bookmarklet that will delete all cookies under that subdomain, regardless of the folder in which they exist.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 179535,
"author": "Robert J. Walker",
"author_id": 4287,
"author_profile": "https://Stackoverflow.com/users/4287",
"pm_score": 6,
"selected": true,
"text": "javascript:new function(){var c=document.cookie.split(\";\");for(var i=0;i<c.length;i++){var e=c[i].indexOf(\"=\");var n=e>-1?c[i].substr(0,e):c[i];document.cookie=n+\"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";}}(); return void(0);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335036/"
] |
178,265
|
<p>Today at work we came across the following code (some of you might recognize it):</p>
<pre><code>#define GET_VAL( val, type ) \
{ \
ASSERT( ( pIP + sizeof(type) ) <= pMethodEnd ); \
val = ( *((type *&)(pIP))++ ); \
}
</code></pre>
<p>Basically we have a byte array and a pointer. The macro returns a reference to a variable of type and advance the pointer to the end of that variable.</p>
<p>It reminded me of the several times that I needed to "think like a parser" in order to understand C++ code.</p>
<p>Do you know of other code examples that caused you to stop and read it several times till you managed to grasp what it was suppose to do?</p>
|
[
{
"answer_id": 178308,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 2,
"selected": false,
"text": "ihi = y[0]>y[1] ? (inhi=1,0) : (inhi=0,1);\n"
},
{
"answer_id": 178361,
"author": "Ma99uS",
"author_id": 20390,
"author_profile": "https://Stackoverflow.com/users/20390",
"pm_score": 3,
"selected": false,
"text": "// a^=b^=a^=b; // int a and int b will be swapped\n// Technically undefined behavior as variable may only \n// be assined once within the same statement.\n// \n// But this can be written correctly like this.\n// Which still looks cool and unreadable ;-)\n\na^=b;\nb^=a;\na^=b;\n"
},
{
"answer_id": 178367,
"author": "Shimi Bandiel",
"author_id": 15100,
"author_profile": "https://Stackoverflow.com/users/15100",
"pm_score": -1,
"selected": false,
"text": "java.util.concurrent.ConcurrentHashMap return ((h << 7) - h + (h >>> 9) + (h >>> 17))\n"
},
{
"answer_id": 178446,
"author": "Martin Beckett",
"author_id": 10897,
"author_profile": "https://Stackoverflow.com/users/10897",
"pm_score": 5,
"selected": false,
"text": " assert((o-----o\n | !\n ! !\n ! !\n ! !\n o-----o ).area == ( o---------o\n | !\n ! !\n o---------o ).area );\n"
},
{
"answer_id": 178501,
"author": "mbeckish",
"author_id": 21727,
"author_profile": "https://Stackoverflow.com/users/21727",
"pm_score": 3,
"selected": false,
"text": "unsigned int reverse(register unsigned int x)\n{\n x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));\n x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));\n x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));\n x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));\n return((x >> 16) | (x << 16));\n}\n"
},
{
"answer_id": 178591,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 4,
"selected": false,
"text": "strcpy(to, from, count)\nchar *to, *from;\nint count;\n{\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n"
},
{
"answer_id": 179225,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 7,
"selected": true,
"text": "float InvSqrt (float x){\n float xhalf = 0.5f*x;\n int i = *(int*)&x;\n i = 0x5f3759df - (i>>1);\n x = *(float*)&i;\n x = x*(1.5f - xhalf*x*x);\n return x;\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11361/"
] |
178,320
|
<p>When you're passing variables through your site using GET requests, do you validate (regular expressions, filters, etc.) them before you use them?</p>
<p>Say you have the URL <a href="http://www.example.com/i=45&p=custform" rel="nofollow noreferrer">http://www.example.com/i=45&p=custform</a>. You know that "i" will always be an integer and "p" will always contain only letters and/or numbers. Is it worth the time to make sure that no one has attempted to manipulate the values and then resubmit the page?</p>
|
[
{
"answer_id": 178371,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "IsInt(i), IsString(p)"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1444511/"
] |
178,325
|
<p>How do I toggle the visibility of an element using <code>.hide()</code>, <code>.show()</code>, or <code>.toggle()</code>?</p>
<p>How do I test if an element is <code>visible</code> or <code>hidden</code>?</p>
|
[
{
"answer_id": 178344,
"author": "Mote",
"author_id": 24789,
"author_profile": "https://Stackoverflow.com/users/24789",
"pm_score": 10,
"selected": false,
"text": "if ( $(element).css('display') == 'none' || $(element).css(\"visibility\") == \"hidden\"){\n // 'element' is hidden\n}\n .is(\":hidden\") .is(\":visible\") <div id=\"div1\" style=\"display:none\">\n <div id=\"div2\" style=\"display:block\">Div2</div>\n</div>\n div2 :visible :visible"
},
{
"answer_id": 178386,
"author": "twernt",
"author_id": 18846,
"author_profile": "https://Stackoverflow.com/users/18846",
"pm_score": 11,
"selected": false,
"text": "hidden // Matches all elements that are hidden\n$('element:hidden')\n visible // Matches all elements that are visible\n$('element:visible')\n"
},
{
"answer_id": 178450,
"author": "Tsvetomir Tsonev",
"author_id": 25449,
"author_profile": "https://Stackoverflow.com/users/25449",
"pm_score": 14,
"selected": true,
"text": "// Checks CSS content for display:[none|block], ignores visibility:[true|false]\n$(element).is(\":visible\");\n\n// The same works with hidden\n$(element).is(\":hidden\");\n"
},
{
"answer_id": 1181809,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 8,
"selected": false,
"text": "filter(\":visible\") filter(\":hidden\") if if ($('#btnUpdate').is(\":visible\"))\n{\n $('#btnUpdate').animate({ width: \"toggle\" }); // Hide button\n}\n var button = $('#btnUpdate');\nif (button.is(\":visible\"))\n{\n button.animate({ width: \"toggle\" }); // Hide button\n}\n $('#btnUpdate').filter(\":visible\").animate({ width: \"toggle\" });\n"
},
{
"answer_id": 4685330,
"author": "user574889",
"author_id": 574889,
"author_profile": "https://Stackoverflow.com/users/574889",
"pm_score": 9,
"selected": false,
"text": ":visible :hidden var isVisible = $('#myDiv').is(':visible');\nvar isHidden = $('#myDiv').is(':hidden');\n :visible :hidden $('#myDiv:visible').animate({left: '+=200px'}, 'slow');\n"
},
{
"answer_id": 5423934,
"author": "aaronLile",
"author_id": 570371,
"author_profile": "https://Stackoverflow.com/users/570371",
"pm_score": 9,
"selected": false,
"text": "visibility: hidden :visible :hidden $(\".item\").each(function() {\n if ($(this).css(\"visibility\") == \"hidden\") {\n // handle non visible state\n } else {\n // handle visible state\n }\n});\n"
},
{
"answer_id": 6602427,
"author": "Abiy",
"author_id": 832338,
"author_profile": "https://Stackoverflow.com/users/832338",
"pm_score": 8,
"selected": false,
"text": "show() hide() if( $(this).css('display') == 'none' ){\n /* your code goes here */\n} else {\n /* alternate logic */\n}\n"
},
{
"answer_id": 8266879,
"author": "Pedro Rainho",
"author_id": 1020760,
"author_profile": "https://Stackoverflow.com/users/1020760",
"pm_score": 8,
"selected": false,
"text": ":visible display none type=\"hidden\" visibility: hidden opacity: 0 display != none .css(\"display\") == 'none' .css(\"visibility\") == \"hidden\" :visible :visible querySelectorAll() :visible .filter(\":visible\")"
},
{
"answer_id": 9131633,
"author": "David Levin",
"author_id": 571203,
"author_profile": "https://Stackoverflow.com/users/571203",
"pm_score": 7,
"selected": false,
"text": ".hide { display: none!important; } .addClass(\"hide\")/.removeClass(\"hide\") .hasClass(\"hide\") .toggle() .animate()"
},
{
"answer_id": 10264006,
"author": "Lucas",
"author_id": 1136709,
"author_profile": "https://Stackoverflow.com/users/1136709",
"pm_score": 7,
"selected": false,
"text": "if (!$('#thetagname').length)"
},
{
"answer_id": 10305968,
"author": "webvitaly",
"author_id": 713523,
"author_profile": "https://Stackoverflow.com/users/713523",
"pm_score": 8,
"selected": false,
"text": "display:none visibility:hidden opacity:0 display:none visibility:hidden opacity:0 if ($('.target').is(':hidden')) {\n $('.target').show();\n} else {\n $('.target').hide();\n}\nif ($('.target').is(':visible')) {\n $('.target').hide();\n} else {\n $('.target').show();\n}\n\nif ($('.target-visibility').css('visibility') == 'hidden') {\n $('.target-visibility').css({\n visibility: \"visible\",\n display: \"\"\n });\n} else {\n $('.target-visibility').css({\n visibility: \"hidden\",\n display: \"\"\n });\n}\n\nif ($('.target-visibility').css('opacity') == \"0\") {\n $('.target-visibility').css({\n opacity: \"1\",\n display: \"\"\n });\n} else {\n $('.target-visibility').css({\n opacity: \"0\",\n display: \"\"\n });\n}\n $('.click').click(function() {\n $('.target').toggle();\n});\n\n$('.click').click(function() {\n $('.target').slideToggle();\n});\n\n$('.click').click(function() {\n $('.target').fadeToggle();\n});\n"
},
{
"answer_id": 10720438,
"author": "ScoRpion",
"author_id": 995113,
"author_profile": "https://Stackoverflow.com/users/995113",
"pm_score": 7,
"selected": false,
"text": "hidden visible $('element:hidden')\n$('element:visible')\n $(element).is(\":visible\")\n"
},
{
"answer_id": 11015754,
"author": "Vaishu",
"author_id": 1041118,
"author_profile": "https://Stackoverflow.com/users/1041118",
"pm_score": 7,
"selected": false,
"text": "ebdiv style=\"display:none;\" $(document).ready(function(){\n $(\"#eb\").click(function(){\n $(\"#ebdiv\").toggle();\n }); \n});\n"
},
{
"answer_id": 11511035,
"author": "Matt Brock",
"author_id": 313969,
"author_profile": "https://Stackoverflow.com/users/313969",
"pm_score": 7,
"selected": false,
"text": "function isRendered(domObj) {\n if ((domObj.nodeType != 1) || (domObj == document.body)) {\n return true;\n }\n if (domObj.currentStyle && domObj.currentStyle[\"display\"] != \"none\" && domObj.currentStyle[\"visibility\"] != \"hidden\") {\n return isRendered(domObj.parentNode);\n } else if (window.getComputedStyle) {\n var cs = document.defaultView.getComputedStyle(domObj, null);\n if (cs.getPropertyValue(\"display\") != \"none\" && cs.getPropertyValue(\"visibility\") != \"hidden\") {\n return isRendered(domObj.parentNode);\n }\n }\n return false;\n}\n"
},
{
"answer_id": 11579654,
"author": "Maneesh Kumar",
"author_id": 1187233,
"author_profile": "https://Stackoverflow.com/users/1187233",
"pm_score": 7,
"selected": false,
"text": "expect($(\"#message_div\").css(\"display\")).toBe(\"none\");\n"
},
{
"answer_id": 14515952,
"author": "Code Spy",
"author_id": 1045296,
"author_profile": "https://Stackoverflow.com/users/1045296",
"pm_score": 7,
"selected": false,
"text": "$('#clickme').click(function() {\n $('#book').toggle('slow', function() {\n // Animation complete.\n alert($('#book').is(\":visible\")); //<--- TRUE if Visible False if Hidden\n });\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div id=\"clickme\">\n Click here\n</div>\n<img id=\"book\" src=\"https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png\" alt=\"\" width=\"300\"/>"
},
{
"answer_id": 16919498,
"author": "Matthias Wegtun",
"author_id": 1559329,
"author_profile": "https://Stackoverflow.com/users/1559329",
"pm_score": 6,
"selected": false,
"text": "! if ( !$('#book').is(':visible')) {\n alert('#book is not visible')\n}\n var $book = $('#book')\n\nif(!$book.is(':visible')) {\n alert('#book is not visible')\n}\n"
},
{
"answer_id": 17734054,
"author": "Ross Brasseaux",
"author_id": 1751792,
"author_profile": "https://Stackoverflow.com/users/1751792",
"pm_score": 6,
"selected": false,
"text": "Display"
},
{
"answer_id": 19628550,
"author": "Irfan DANISH",
"author_id": 1058406,
"author_profile": "https://Stackoverflow.com/users/1058406",
"pm_score": 6,
"selected": false,
"text": "$(document).ready(function() {\n if ($(\"#checkme:hidden\").length) {\n console.log('Hidden');\n }\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div id=\"checkme\" class=\"product\" style=\"display:none\">\n <span class=\"itemlist\"><!-- Shows Results for Fish --></span> Category:Fish\n <br>Product: Salmon Atlantic\n <br>Specie: Salmo salar\n <br>Form: Steaks\n</div>"
},
{
"answer_id": 19801208,
"author": "cssimsek",
"author_id": 2668568,
"author_profile": "https://Stackoverflow.com/users/2668568",
"pm_score": 5,
"selected": false,
"text": "$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });\n"
},
{
"answer_id": 19999134,
"author": "Gaurav",
"author_id": 2357391,
"author_profile": "https://Stackoverflow.com/users/2357391",
"pm_score": 5,
"selected": false,
"text": "if($('#postcode_div').is(':visible')) {\n if($('#postcode_text').val()=='') {\n $('#spanPost').text('\\u00a0');\n } else {\n $('#spanPost').text($('#postcode_text').val());\n}\n"
},
{
"answer_id": 21473745,
"author": "Premshankar Tiwari",
"author_id": 1938122,
"author_profile": "https://Stackoverflow.com/users/1938122",
"pm_score": 6,
"selected": false,
"text": "if ($(this).css(\"display\") == \"none\" || $(this).css(\"visibility\") == \"hidden\") {\n // The element is not visible\n} else {\n // The element is visible\n}\n $(this).is(\":visible\")"
},
{
"answer_id": 22506181,
"author": "Andron",
"author_id": 284602,
"author_profile": "https://Stackoverflow.com/users/284602",
"pm_score": 5,
"selected": false,
"text": "Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout function isElementReallyHidden (el) {\n return $(el).is(\":hidden\") || $(el).css(\"visibility\") == \"hidden\" || $(el).css('opacity') == 0;\n}\n\nvar booElementReallyShowed = !isElementReallyHidden(someEl);\n$(someEl).parents().each(function () {\n if (isElementReallyHidden(this)) {\n booElementReallyShowed = false;\n }\n});\n"
},
{
"answer_id": 22969337,
"author": "Aleko",
"author_id": 2274995,
"author_profile": "https://Stackoverflow.com/users/2274995",
"pm_score": 6,
"selected": false,
"text": "filter:alpha display:none visibility:hidden overflow:hidden display:none var is_visible = (function () {\n var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,\n y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,\n relative = !!((!x && !y) || !document.elementFromPoint(x, y));\n function inside(child, parent) {\n while(child){\n if (child === parent) return true;\n child = child.parentNode;\n }\n return false;\n };\n return function (elem) {\n if (\n document.hidden ||\n elem.offsetWidth==0 ||\n elem.offsetHeight==0 ||\n elem.style.visibility=='hidden' ||\n elem.style.display=='none' ||\n elem.style.opacity===0\n ) return false;\n var rect = elem.getBoundingClientRect();\n if (relative) {\n if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;\n } else if (\n !inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||\n (\n rect.top + elem.offsetHeight/2 < 0 ||\n rect.left + elem.offsetWidth/2 < 0 ||\n rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||\n rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)\n )\n ) return false;\n if (window.getComputedStyle || elem.currentStyle) {\n var el = elem,\n comp = null;\n while (el) {\n if (el === document) {break;} else if(!el.parentNode) return false;\n comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;\n if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;\n el = el.parentNode;\n }\n }\n return true;\n }\n})();\n is_visible(elem) // boolean\n"
},
{
"answer_id": 23027643,
"author": "Kareem",
"author_id": 2151420,
"author_profile": "https://Stackoverflow.com/users/2151420",
"pm_score": 5,
"selected": false,
"text": ".is(\":not(':hidden')\") /*if shown*/\n"
},
{
"answer_id": 23492646,
"author": "conceptdeluxe",
"author_id": 1510754,
"author_profile": "https://Stackoverflow.com/users/1510754",
"pm_score": 7,
"selected": false,
"text": ":hidden console.log($('.foo').is(':hidden')); // true\nconsole.log($('.bar').is(':hidden')); // false .foo {\n position: absolute;\n left: 10px;\n top: 10px;\n background: #ff0000;\n}\n\n.bar {\n position: absolute;\n left: 10px;\n top: 10px;\n width: 20px;\n height: 20px;\n background: #0000ff;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class=\"foo\">\n <div class=\"bar\"></div>\n</div> console.log($('.foo').is(':hidden')); // false\nconsole.log($('.bar').is(':hidden')); // false\n"
},
{
"answer_id": 25236348,
"author": "pixellabme",
"author_id": 3873204,
"author_profile": "https://Stackoverflow.com/users/3873204",
"pm_score": 5,
"selected": false,
"text": "if (this.hidden === false) {\n // Your code\n}\n is(':visible')"
},
{
"answer_id": 25466293,
"author": "RN Kushwaha",
"author_id": 2995263,
"author_profile": "https://Stackoverflow.com/users/2995263",
"pm_score": 5,
"selected": false,
"text": ".element{\n position: absolute;left:-9999; \n}\n"
},
{
"answer_id": 25575642,
"author": "V31",
"author_id": 2081982,
"author_profile": "https://Stackoverflow.com/users/2081982",
"pm_score": 5,
"selected": false,
"text": "function checkUIElementVisible(element) {\n return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));\n}\n"
},
{
"answer_id": 29491573,
"author": "Mathias Stavrou",
"author_id": 2808740,
"author_profile": "https://Stackoverflow.com/users/2808740",
"pm_score": 6,
"selected": false,
"text": "$(document).ready(function() {\n var visible = $('#tElement').is(':visible');\n\n if(visible) {\n alert(\"visible\");\n // Code\n }\n else\n {\n alert(\"hidden\");\n }\n}); <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script>\n\n<input type=\"text\" id=\"tElement\" style=\"display:block;\">Firstname</input>"
},
{
"answer_id": 29890170,
"author": "Roman Losev",
"author_id": 1602375,
"author_profile": "https://Stackoverflow.com/users/1602375",
"pm_score": 6,
"selected": false,
"text": "$(document).ready(function(){\n if(!$(\"#ablockercheck\").is(\":visible\"))\n $(\"#ablockermsg\").text(\"Please disable adblocker.\").show();\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class=\"ad-placement\" id=\"ablockercheck\"></div>\n<div id=\"ablockermsg\" style=\"display: none\"></div>"
},
{
"answer_id": 32068044,
"author": "Prabhagaran",
"author_id": 4796478,
"author_profile": "https://Stackoverflow.com/users/4796478",
"pm_score": 5,
"selected": false,
"text": "if($('#id_element').is(\":visible\")){\n alert('shown');\n}else{\n alert('hidden');\n}\n"
},
{
"answer_id": 32182004,
"author": "Sangeet Shah",
"author_id": 3539870,
"author_profile": "https://Stackoverflow.com/users/3539870",
"pm_score": 4,
"selected": false,
"text": " // using a pure CSS selector \n if ($('p:visible')) { \n alert('Paragraphs are visible (checked using a CSS selector) !'); \n }; \n \n // using jQuery's is() method \n if ($('p').is(':visible')) { \n alert('Paragraphs are visible (checked using is() method)!'); \n }; \n \n // using jQuery's filter() method \n if ($('p').filter(':visible')) { \n alert('Paragraphs are visible (checked using filter() method)!'); \n }; \n \n // you can use :hidden instead of :visible to reverse the logic and check if an element is hidden \n // if ($('p:hidden')) { \n // do something \n // }; "
},
{
"answer_id": 36179368,
"author": "cbertelegni",
"author_id": 2800900,
"author_profile": "https://Stackoverflow.com/users/2800900",
"pm_score": 2,
"selected": false,
"text": "if($(\"h1\").is(\":hidden\")){\n // your code..\n}\n"
},
{
"answer_id": 36397659,
"author": "Disapamok",
"author_id": 3994304,
"author_profile": "https://Stackoverflow.com/users/3994304",
"pm_score": 4,
"selected": false,
"text": "show $('#elementId').hasClass('show');\n show .show{ display: block; }\n"
},
{
"answer_id": 36561933,
"author": "Oriol",
"author_id": 2817112,
"author_profile": "https://Stackoverflow.com/users/2817112",
"pm_score": 4,
"selected": false,
"text": "jQuery.expr.pseudos.visible = function( elem ) {\n return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );\n};\n function isVisible(elem) {\n return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );\n};\n isVisible true"
},
{
"answer_id": 36982533,
"author": "Abrar Jahin",
"author_id": 2193439,
"author_profile": "https://Stackoverflow.com/users/2193439",
"pm_score": 4,
"selected": false,
"text": "$(element).is(':visible');\n $(document).ready(function()\n{\n $(\"#toggle\").click(function()\n {\n $(\"#content\").toggle();\n });\n\n $(\"#visiblity\").click(function()\n {\n if( $('#content').is(':visible') )\n {\n alert(\"visible\"); // Put your code for visibility\n }\n else\n {\n alert(\"hidden\");\n }\n });\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js\"></script>\n\n<p id=\"content\">This is a Content</p>\n\n<button id=\"toggle\">Toggle Content Visibility</button>\n<button id=\"visibility\">Check Visibility</button>"
},
{
"answer_id": 37561155,
"author": "lmcDevloper",
"author_id": 3303585,
"author_profile": "https://Stackoverflow.com/users/3303585",
"pm_score": 4,
"selected": false,
"text": "jQuery.fn.extend({\n isvisible: function() {\n //\n // This function call this: $(\"div\").isvisible()\n // Return true if the element is visible\n // Return false if the element is not visible for our eyes\n //\n if ( $(this).css('display') == 'none' ){\n console.log(\"this = \" + \"display:none\");\n return false;\n }\n else if( $(this).css('visibility') == 'hidden' ){\n console.log(\"this = \" + \"visibility:hidden\"); \n return false;\n }\n else if( $(this).css('opacity') == '0' ){\n console.log(\"this = \" + \"opacity:0\");\n return false;\n } \n else{\n console.log(\"this = \" + \"Is Visible\");\n return true;\n }\n } \n});\n"
},
{
"answer_id": 40438235,
"author": "No one",
"author_id": 4730999,
"author_profile": "https://Stackoverflow.com/users/4730999",
"pm_score": 4,
"selected": false,
"text": "hide() show() toggle() display: none visibility: \"hidden\"; var hiddenCssProps = {\ndisplay: \"none\",\nvisibility: \"hidden\"\n}\n var isHidden = false;\nfor(key in hiddenCssProps) {\n if($('#element').css(key) == hiddenCssProps[key]) {\n isHidden = true;\n }\n}\n"
},
{
"answer_id": 40904208,
"author": "Wolfack",
"author_id": 4482269,
"author_profile": "https://Stackoverflow.com/users/4482269",
"pm_score": 4,
"selected": false,
"text": "$( \"div:visible\" ).click(function() {\n $( this ).css( \"background\", \"yellow\" );\n});\n$( \"button\" ).click(function() {\n $( \"div:hidden\" ).show( \"fast\" );\n});\n"
},
{
"answer_id": 40991133,
"author": "Sky Yip",
"author_id": 4992983,
"author_profile": "https://Stackoverflow.com/users/4992983",
"pm_score": 4,
"selected": false,
"text": "if($('.element').is(':hidden')) {\n // Do something\n}\n"
},
{
"answer_id": 41117640,
"author": "Arun Karnawat",
"author_id": 3114253,
"author_profile": "https://Stackoverflow.com/users/3114253",
"pm_score": 4,
"selected": false,
"text": "<div id=\"content\">Content</div>\n<div id=\"content2\" style=\"display:none\">Content2</div>\n $('element:hidden') $('element:visible') $('element:hidden') Example:\n $('#content2:hidden').show();\n $('element:visible') Example:\n $('#content:visible').css('color', '#EEE');\n is() Example:\n $('#content').is(\":visible\").css('color', '#EEE');\n\n Or checking condition\n if ($('#content').is(\":visible\")) {\n // Perform action\n }\n"
},
{
"answer_id": 42896214,
"author": "Abdul Aziz Al Basyir",
"author_id": 8314878,
"author_profile": "https://Stackoverflow.com/users/8314878",
"pm_score": 3,
"selected": false,
"text": "$('element:visible')\n $('element:visible').show();\n"
},
{
"answer_id": 43014382,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 3,
"selected": false,
"text": "<html>\n<body>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js\"></script>\n<script>\n var vm = {\n IsDivVisible: ko.observable(true);\n }\n vm.toggle = function(data, event) {\n // Get current visibility state for the div\n var x = IsDivVisible();\n // Set it to the opposite\n IsDivVisible(!x);\n }\n ko.applyBinding(vm);\n</script>\n<div data-bind=\"visible: IsDivVisible\">Peekaboo!</div>\n<button data-bind=\"click: toggle\">Toggle the div's visibility</button>\n</body>\n</html>\n"
},
{
"answer_id": 43694490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$('someElement').on('click', function(){ $('elementToToggle').is(':visible')\n"
},
{
"answer_id": 43817534,
"author": "Alireza",
"author_id": 5423108,
"author_profile": "https://Stackoverflow.com/users/5423108",
"pm_score": 4,
"selected": false,
"text": "if (document.getElementById(\"element\").style.display === 'block') {\n // Your element is visible; do whatever you'd like\n}\n if ($(element).is(\":visible\")) {\n // Your element is visible, do whatever you'd like\n};\n css if ($(element).css('display') === 'block') {\n // Your element is visible, do whatever you'd like\n}\n if ($(this).css(\"display\") === \"block\" || $(this).css(\"visibility\") === \"visible\") {\n // Your element is visible, do whatever you'd like\n}\n"
},
{
"answer_id": 45574894,
"author": "Antoine Auffray",
"author_id": 4547217,
"author_profile": "https://Stackoverflow.com/users/4547217",
"pm_score": 3,
"selected": false,
"text": "display visibility if ($('#invisible').css('display') == 'none') {\n // This means the HTML element with ID 'invisible' has its 'display' attribute set to 'none'\n}\n"
},
{
"answer_id": 46422283,
"author": "Disapamok",
"author_id": 3994304,
"author_profile": "https://Stackoverflow.com/users/3994304",
"pm_score": 2,
"selected": false,
"text": ".show{ display :block; }\n toggleClass() addClass() removeClass(); jQuery('#myID').toggleClass('show') show show show jQuery('#myID').hasClass('show'); #myID show show"
},
{
"answer_id": 47946881,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "isHidden = function(element){\n return (element.style.display === \"none\");\n};\n\nif(isHidden($(\"element\")) == true){\n // Something\n}\n"
},
{
"answer_id": 51584576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "event element $('div').each(function(){\n if($(this).css('display') === 'none'){\n $(this).css({'display':'block'});\n }\n});\n $('input').each(function(){\n if($(this).attr('type') === 'hidden'){\n $(this).attr('type', 'text');\n }\n});\n"
},
{
"answer_id": 51851876,
"author": "Profesor08",
"author_id": 3654943,
"author_profile": "https://Stackoverflow.com/users/3654943",
"pm_score": 3,
"selected": false,
"text": "width height 0 $element.width() === 0 && $element.height() === 0 element.clientWidth === 0 && element.clientHeight === 0 element.offsetWidth === 0 && element.offsetHeight === 0"
},
{
"answer_id": 52291985,
"author": "Muhammad",
"author_id": 1966247,
"author_profile": "https://Stackoverflow.com/users/1966247",
"pm_score": 3,
"selected": false,
"text": "$(function(){\n $(\"#showHide\").click(function(){\n var btn = $(this);\n $(\"#content\").toggle(function () {\n btn.text($(this).css(\"display\") === 'none' ? \"Show\" : \"Hide\");\n });\n });\n }); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n\n<button id=\"showHide\">Hide</button>\n<div id=\"content\">\n <h2>Some content</h2>\n <p>\n What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.\n </p>\n</div>"
},
{
"answer_id": 52743191,
"author": "L Y E S - C H I O U K H",
"author_id": 9317830,
"author_profile": "https://Stackoverflow.com/users/9317830",
"pm_score": 4,
"selected": false,
"text": "<script>\nif ($(\"#myelement\").is(\":visible\")){alert (\"#myelement is visible\");}\nif ($(\"#myelement\").is(\":hidden\")){alert (\"#myelement is hidden\"); }\n</script>\n $(\"#myelement div:visible\").each( function() {\n //Do something\n});\n jQuery.expr.filters.visible = function( elem ) {\n return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );\n};\n jQuery.expr.filters.offscreen = function(el) {\n var rect = el.getBoundingClientRect();\n return (\n (rect.x + rect.width) < 0 \n || (rect.y + rect.height) < 0\n || (rect.x > window.innerWidth || rect.y > window.innerHeight)\n );\n};\n // Returns all elements that are offscreen\n$(':offscreen');\n\n// Boolean returned if element is offscreen\n$('div').is(':offscreen');\n"
},
{
"answer_id": 56556127,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "content.style.display != 'none'\n function toggle() {\n $(content).toggle();\n let visible= content.style.display != 'none'\n console.log('visible:', visible);\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\n<button onclick=\"toggle()\">Show/hide</button>\n<div id=\"content\">ABC</div>"
},
{
"answer_id": 57092600,
"author": "Aravinda Meewalaarachchi",
"author_id": 3590237,
"author_profile": "https://Stackoverflow.com/users/3590237",
"pm_score": 2,
"selected": false,
"text": "is() <script>\n ($(\"#myelement\").is(\":visible\"))? alert(\"#myelement is visible\") : alert(\"#myelement is hidden\");\n</script>\n"
},
{
"answer_id": 59261903,
"author": "Ankush Kumar",
"author_id": 12489279,
"author_profile": "https://Stackoverflow.com/users/12489279",
"pm_score": 1,
"selected": false,
"text": "// You can also do this...\n\n $(\"button\").click(function(){\n // show hide paragraph on button click\n $(\"p\").toggle(\"slow\", function(){\n // check paragraph once toggle effect is completed\n if($(\"p\").is(\":visible\")){\n alert(\"The paragraph is visible.\");\n } else{\n alert(\"The paragraph is hidden.\");\n }\n });\n });\n"
},
{
"answer_id": 60242555,
"author": "Brane",
"author_id": 3850805,
"author_profile": "https://Stackoverflow.com/users/3850805",
"pm_score": 3,
"selected": false,
"text": "false function checkVisible(e) {\n if (!(e instanceof Element)) throw Error('not an Element');\n const elementStyle = getComputedStyle(e);\n if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false;\n if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height +\n e.getBoundingClientRect().width === 0) {\n return false;\n }\n const elemCenter = {\n x: e.getBoundingClientRect().left + e.offsetWidth / 2,\n y: e.getBoundingClientRect().top + e.offsetHeight / 2\n };\n if (elemCenter.x < 0 || elemCenter.y < 0) return false;\n if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;\n if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;\n let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);\n do {\n if (pointContainer === e) return true;\n } while (pointContainer = pointContainer.parentNode);\n return false;\n}\n"
},
{
"answer_id": 63700797,
"author": "Mojtaba Nava",
"author_id": 10116812,
"author_profile": "https://Stackoverflow.com/users/10116812",
"pm_score": 1,
"selected": false,
"text": " hideShow(){\n $(\"#accordionZiarat\").hide();\n // Checks CSS content for display:[none|block], ignores visibility:[true|false]\n if ($(\"#accordionZiarat\").is(\":visible\")) {\n $(\"#accordionZiarat\").hide();\n }\n\n \n else if ($(\"#accordionZiarat\").is(\":hidden\")) {\n $(\"#accordionZiarat\").show();\n }\n\n else{\n\n }\n"
},
{
"answer_id": 64021369,
"author": "Hasee Amarathunga",
"author_id": 7484853,
"author_profile": "https://Stackoverflow.com/users/7484853",
"pm_score": 3,
"selected": false,
"text": "$('element:hidden')\n $('element:visible')\n"
},
{
"answer_id": 65844339,
"author": "centralhubb.com",
"author_id": 1001342,
"author_profile": "https://Stackoverflow.com/users/1001342",
"pm_score": 0,
"selected": false,
"text": "if($(element).is(\":visible\")) {\n console.log('element is visible');\n} else {\n console.log('element is not visible');\n}\n"
},
{
"answer_id": 70433410,
"author": "Vicky P",
"author_id": 14186457,
"author_profile": "https://Stackoverflow.com/users/14186457",
"pm_score": 3,
"selected": false,
"text": "if($('.selector').is(':visible')){\n // element is visible\n}else{\n // element is hidden\n}\n if($('.selector:visible')){\n // element is visible\n}else{\n // element is hidden\n}\n"
},
{
"answer_id": 70470760,
"author": "udorb b",
"author_id": 4493560,
"author_profile": "https://Stackoverflow.com/users/4493560",
"pm_score": -1,
"selected": false,
"text": "if (!$('#ele').hasClass('d-none')) {\n $('#ele').addClass('d-none'); //hide \n\n }\n\n\n \n"
},
{
"answer_id": 70595690,
"author": "Enrico König",
"author_id": 16711980,
"author_profile": "https://Stackoverflow.com/users/16711980",
"pm_score": 2,
"selected": false,
"text": "function checkUIElementVisible(element) {\n return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));\n}\n"
},
{
"answer_id": 72112111,
"author": "Sahil Thummar",
"author_id": 14229690,
"author_profile": "https://Stackoverflow.com/users/14229690",
"pm_score": 3,
"selected": false,
"text": "function checkVisibility() {\n // check if element is hidden or not and return true false\n console.log($('#element').is(':hidden'));\n\n // check if element is visible or not and return true false\n console.log($('#element').is(':visible'));\n\n if ( $('#element').css('display') == 'none' || $('#element').css(\"visibility\") == \"hidden\"){\n console.log('element is hidden');\n } else {\n console.log('element is visibile');\n }\n}\n\ncheckVisibility()\n$('#toggle').click(function() {\n $('#element').toggle()\n checkVisibility()\n}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<button id='toggle'>Toggle</button>\n<div style='display:none' id='element'>\n <h1>Hello</h1>\n <p>it's visible</p>\n</div>"
},
{
"answer_id": 72772615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$(document).ready(function() {\n var view = $(this).is(':visible');\n\n if(view) {\n alert(\"view\");\n // Code\n }\n else\n {\n alert(\"hidden\");\n }\n});\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
178,326
|
<p>I have an MFC app which I have been working on for a few weeks now, I want to manually set the dimensions of the main frame when it is loaded, can someone give me a hand with this, specifically where to put the code as well?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 178349,
"author": "IanW",
"author_id": 3875,
"author_profile": "https://Stackoverflow.com/users/3875",
"pm_score": 2,
"selected": false,
"text": "CRect rect;\nSystemParametersInfo(SPI_GETWORKAREA,0,&rect,0);\nscreen_x_size=rect.Width(); \nscreen_y_size=rect.Height();\n ::SetWindowPos(m_hWnd,HWND_TOPMOST,0,0,main_x_size,main_y_size,SWP_NOZORDER); \n main_x_size main_y_size"
},
{
"answer_id": 178388,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 2,
"selected": false,
"text": "BOOL CMyWindow::PreCreateWindow(CREATESTRUCT& cs)\n{\n cs.cy = 640; // width\n cs.cx = 480; // height\n cs.y = 0; // top position\n cs.x = 0; // left position\n // don't forget to call base class version, suppose you derived you window from CWnd\n return CWnd::PreCreateWindow(cs);\n}"
},
{
"answer_id": 178443,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 5,
"selected": true,
"text": "SetWindowPos() CMainFrame::OnCreate() CWinApp InitInstance pMainFrame->ShowWindow() pMainFrame->SetWindowPos()"
},
{
"answer_id": 62502419,
"author": "Vũ Đức Vĩ",
"author_id": 12445824,
"author_profile": "https://Stackoverflow.com/users/12445824",
"pm_score": 0,
"selected": false,
"text": "CRect rect;\nSystemParametersInfo(SPI_GETWORKAREA, 0, &rect, 0);\nleft = -3, right = 3;\nrect.top = 100;\nrect.bottom = 500;\nrect.left = 100;\nrect.right = 800;\n//or use\nCRect cr;\ncr.SetRect(POINT{ 100,100 }, POINT{ 500,800 });\nMoveWindow(rect);\n"
},
{
"answer_id": 71404246,
"author": "Zrn-dev",
"author_id": 14265581,
"author_profile": "https://Stackoverflow.com/users/14265581",
"pm_score": -1,
"selected": false,
"text": "BOOL YourProjectApp::InitInstance()\n{\n :\n :\n m_pMainWnd->MoveWindow(0, 0, 1900, 1000); // add this line for fixing the default size of mainWindow\n m_pMainWnd->ShowWindow(SW_SHOW);\n m_pMainWnd->UpdateWindow();\n return TRUE;\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
178,328
|
<p>In PHP, function parameters can be passed by reference by prepending an ampersand to the parameter in the function declaration, like so:</p>
<pre><code>function foo(&$bar)
{
// ...
}
</code></pre>
<p>Now, I am aware that this is <i>not</i> designed to improve performance, but to allow functions to change variables that are normally out of their scope.</p>
<p>Instead, PHP seems to use Copy On Write to avoid copying objects (and maybe also arrays) until they are changed. So, for functions that do not change their parameters, the effect should be the same as if you had passed them by reference.</p>
<p>However, I was wondering if the Copy On Write logic maybe is shortcircuited on pass-by-reference and whether that has any performance impact.</p>
<p><i>ETA: To be sure, I assume that it's not faster, and I am well aware that this is not what references are for. So I think my own guesses are quite good, I'm just looking for an answer from someone who really knows what's definitely happening under the hood. In five years of PHP development, I've always found it hard to get quality information on PHP internals short from reading the source.</i></p>
|
[
{
"answer_id": 3845530,
"author": "ikary",
"author_id": 464550,
"author_profile": "https://Stackoverflow.com/users/464550",
"pm_score": 7,
"selected": false,
"text": "pass by value: 0.12065005 seconds\npass by reference: 1.52171397 seconds\n pass by value: 1.52223396 seconds\npass by reference: 1.52388787 seconds\n"
},
{
"answer_id": 6577819,
"author": "Petah",
"author_id": 268074,
"author_profile": "https://Stackoverflow.com/users/268074",
"pm_score": 5,
"selected": false,
"text": "$large_array = array_fill(PHP_INT_MAX / 2, 1000, 'a');\n$small_array = array('this', 'is', 'a', 'small', 'array');\n$large_object = (object)$large_array;\n$large_string = str_repeat('a', 100000);\n$small_string = 'this is a small string';\n$value = PHP_INT_MAX / 2;\n function pass_by_ref(&$var) {\n}\n\nfunction pass_by_val($var) {\n}\n"
},
{
"answer_id": 24975733,
"author": "Melsi",
"author_id": 642173,
"author_profile": "https://Stackoverflow.com/users/642173",
"pm_score": 1,
"selected": false,
"text": "<?PHP\n$r = array();\n\nfor($i=0; $i<500;$i++){\n$r[]=5;\n}\n\nfunction a($r){\n$r[0]=1;\n}\nfunction b(&$r){\n$r[0]=1;\n}\n\n$start = microtime(true);\nfor($i=0;$i<9999;$i++){\n //a($r);\n b($r);\n}\n$end = microtime(true);\n\necho $end-$start;\n?>\n"
},
{
"answer_id": 48861538,
"author": "Bob Ray",
"author_id": 1716090,
"author_profile": "https://Stackoverflow.com/users/1716090",
"pm_score": 2,
"selected": false,
"text": "**Pass by Value Test Code:**\n\n$originalString=''; // 1000 pseudo-random digits\n\nfunction replace($string) {\n return str_replace('1', 'x',$string);\n}\n$output = '';\n/* set start time */\n$mtime = microtime();\n$mtime = explode(\" \", $mtime);\n$mtime = $mtime[1] + $mtime[0];\n$tstart = $mtime;\nset_time_limit(0);\n\nfor ($i = 0; $i < 10; $i++ ) {\n for ($j = 0; $j < 1000000; $j++) {\n $string = $originalString;\n $string = replace($string);\n }\n}\n\n/* report how long it took */\n$mtime = microtime();\n$mtime = explode(\" \", $mtime);\n$mtime = $mtime[1] + $mtime[0];\n$tend = $mtime;\n$totalTime = ($tend - $tstart);\n$totalTime = sprintf(\"%2.4f s\", $totalTime);\n$output .= \"\\n\" . 'Total Time' .\n ': ' . $totalTime;\n$output .= \"\\n\" . $string;\necho $output;\n function replace(&$string) {\n $string = str_replace('1', 'x',$string);\n}\n/* ... */\nreplace($string);\n PHP 5\n Value: 14.1007\n Reference: 11.5564\n\nPHP 7\n Value: 3.0799\n Reference: 2.9489\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
] |
178,333
|
<p>Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability.</p>
<p>For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that:</p>
<pre><code>public interface IFirst { void FirstMethod(); }
public interface ISecond { void SecondMethod(); }
public class First:IFirst
{
public void FirstMethod() { Console.WriteLine("First"); }
}
public class Second:ISecond
{
public void SecondMethod() { Console.WriteLine("Second"); }
}
public class FirstAndSecond: IFirst, ISecond
{
First first = new First();
Second second = new Second();
public void FirstMethod() { first.FirstMethod(); }
public void SecondMethod() { second.SecondMethod(); }
}
</code></pre>
<p>Every time I add a method to one of the interfaces I need to change the class <em>FirstAndSecond</em> as well.</p>
<p>Is there a way to inject multiple existing classes into one new class like it is possible in C++?</p>
<p>Maybe there is a solution using some kind of code generation?</p>
<p>Or it may look like this (imaginary c# syntax):</p>
<pre><code>public class FirstAndSecond: IFirst from First, ISecond from Second
{ }
</code></pre>
<p>So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces.</p>
<hr />
<h3>EDIT</h3>
<p>Maybe it would be better to consider a practical example:</p>
<p>You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers.</p>
<p>As far as I know you currently have two ways to do this:</p>
<ol>
<li><p>Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond.</p>
</li>
<li><p>Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet).</p>
</li>
</ol>
<p>In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class.</p>
<p>To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass.</p>
|
[
{
"answer_id": 178368,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 8,
"selected": false,
"text": "ISteerable SteeringWheel IBrakable BrakePedal public interface ISteerable { SteeringWheel wheel { get; set; } }\n\npublic interface IBrakable { BrakePedal brake { get; set; } }\n\npublic class Vehicle : ISteerable, IBrakable\n{\n public SteeringWheel wheel { get; set; }\n\n public BrakePedal brake { get; set; }\n\n public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }\n}\n\npublic static class SteeringExtensions\n{\n public static void SteerLeft(this ISteerable vehicle)\n {\n vehicle.wheel.SteerLeft();\n }\n}\n\npublic static class BrakeExtensions\n{\n public static void Stop(this IBrakable vehicle)\n {\n vehicle.brake.ApplyUntilStop();\n }\n}\n\n\npublic class Main\n{\n Vehicle myCar = new Vehicle();\n\n public void main()\n {\n myCar.SteerLeft();\n myCar.Stop();\n }\n}\n"
},
{
"answer_id": 178413,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "public interface IFirst {}\npublic interface ISecond {}\n\npublic class FirstAndSecond : IFirst, ISecond\n{\n}\n\npublic static MultipleInheritenceExtensions\n{\n public static void First(this IFirst theFirst)\n {\n Console.WriteLine(\"First\");\n }\n\n public static void Second(this ISecond theSecond)\n {\n Console.WriteLine(\"Second\");\n }\n}\n public void Test()\n{\n FirstAndSecond fas = new FirstAndSecond();\n fas.First();\n fas.Second();\n}\n"
},
{
"answer_id": 6002552,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 4,
"selected": false,
"text": "using NRoles;\n\npublic interface IFirst { void FirstMethod(); }\npublic interface ISecond { void SecondMethod(); }\n\npublic class RFirst : IFirst, Role {\n public void FirstMethod() { Console.WriteLine(\"First\"); }\n}\n\npublic class RSecond : ISecond, Role {\n public void SecondMethod() { Console.WriteLine(\"Second\"); }\n}\n\npublic class FirstAndSecond : Does<RFirst>, Does<RSecond> { }\n var fas = new FirstAndSecond();\nfas.As<RFirst>().FirstMethod();\nfas.As<RSecond>().SecondMethod();\n var fas = new FirstAndSecond();\nfas.FirstMethod();\nfas.SecondMethod();\n"
},
{
"answer_id": 9906675,
"author": "ariel",
"author_id": 1254236,
"author_profile": "https://Stackoverflow.com/users/1254236",
"pm_score": 0,
"selected": false,
"text": "class a {}\nclass b : a {}\nclass c : b {}\n"
},
{
"answer_id": 21145535,
"author": "Yogi",
"author_id": 1171842,
"author_profile": "https://Stackoverflow.com/users/1171842",
"pm_score": 1,
"selected": false,
"text": " namespace OOP\n {\n class Program\n {\n static void Main(string[] args)\n {\n Child somechild = new Child();\n somechild.DoHomeWork();\n somechild.CheckingAround();\n Console.ReadLine();\n }\n }\n\n public class Father \n {\n public Father() { }\n public void Work()\n {\n Console.WriteLine(\"working...\");\n }\n public void Moonlight()\n {\n Console.WriteLine(\"moonlighting...\");\n }\n }\n\n\n public class Mother \n {\n public Mother() { }\n public void Cook()\n {\n Console.WriteLine(\"cooking...\");\n }\n public void Clean()\n {\n Console.WriteLine(\"cleaning...\");\n }\n }\n\n\n public class Child \n {\n public Father MyFather { get; set; }\n public Mother MyMother { get; set; }\n\n public Child()\n {\n MyFather = new Father();\n MyMother = new Mother();\n }\n\n public void GoToSchool()\n {\n Console.WriteLine(\"go to school...\");\n }\n public void DoHomeWork()\n {\n Console.WriteLine(\"doing homework...\");\n }\n public void CheckingAround()\n {\n MyFather.Work();\n MyMother.Cook();\n }\n }\n\n\n }\n"
},
{
"answer_id": 33081879,
"author": "grek40",
"author_id": 5265292,
"author_profile": "https://Stackoverflow.com/users/5265292",
"pm_score": 0,
"selected": false,
"text": "IFirst ISecond First Second FirstAndSecond IFirst First Second BaseClass BaseClass BaseClass First Second class First : IFirst {\n private BaseClass ContainerInstance;\n First(BaseClass container) { ContainerInstance = container; }\n public void FirstMethod() { Console.WriteLine(\"First\"); ContainerInstance.DoStuff(); } \n}\n...\n BaseClass First Second class BaseClass {\n protected void DoStuff();\n}\n\nabstract class First : IFirst {\n public void FirstMethod() { DoStuff(); DoSubClassStuff(); }\n protected abstract void DoStuff(); // base class reference in MI\n protected abstract void DoSubClassStuff(); // sub class responsibility\n}\n First class FirstAndSecond : BaseClass, IFirst, ISecond {\n // link interface\n private class PartFirst : First {\n private FirstAndSecond ContainerInstance;\n public PartFirst(FirstAndSecond container) {\n ContainerInstance = container;\n }\n // forwarded references to emulate access as it would be with MI\n protected override void DoStuff() { ContainerInstance.DoStuff(); }\n protected override void DoSubClassStuff() { ContainerInstance.DoSubClassStuff(); }\n }\n private IFirst partFirstInstance; // composition object\n public FirstMethod() { partFirstInstance.FirstMethod(); } // forwarded implementation\n public FirstAndSecond() {\n partFirstInstance = new PartFirst(this); // composition in constructor\n }\n // same stuff for Second\n //...\n // implementation of DoSubClassStuff\n private void DoSubClassStuff() { Console.WriteLine(\"Private method accessed\"); }\n}\n"
},
{
"answer_id": 42341929,
"author": "William Jockusch",
"author_id": 246568,
"author_profile": "https://Stackoverflow.com/users/246568",
"pm_score": 2,
"selected": false,
"text": "public interface IPerson {\n int GetAge();\n string GetName();\n}\n\npublic interface IGetPerson {\n IPerson GetPerson();\n}\n\npublic static class IGetPersonAdditions {\n public static int GetAgeViaPerson(this IGetPerson getPerson) { // I prefer to have the \"ViaPerson\" in the name in case the object has another Age property.\n IPerson person = getPerson.GetPersion();\n return person.GetAge();\n }\n public static string GetNameViaPerson(this IGetPerson getPerson) {\n return getPerson.GetPerson().GetName();\n }\n}\n\npublic class Person: IPerson, IGetPerson {\n private int Age {get;set;}\n private string Name {get;set;}\n public IPerson GetPerson() {\n return this;\n }\n public int GetAge() { return Age; }\n public string GetName() { return Name; }\n}\n"
},
{
"answer_id": 53288366,
"author": "Ludmil Tinkov",
"author_id": 519553,
"author_profile": "https://Stackoverflow.com/users/519553",
"pm_score": 2,
"selected": false,
"text": "interface ILogger\n{\n void Log(LogLevel level, string message);\n void Log(Exception ex) => Log(LogLevel.Error, ex.ToString()); // New overload\n}\n\nclass ConsoleLogger : ILogger\n{\n public void Log(LogLevel level, string message) { ... }\n // Log(Exception) gets default implementation\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
] |
178,396
|
<p>OK, another road bump in my current project.</p>
<p>I have never had form elements in <strong>both</strong> my master and content pages, I tend to have all the forms in the content where relevant.</p>
<p>In the current project however, we have a page where they want both. <strong>A login form at the top right, and a questions form in the content.</strong></p>
<p>Having tried to get this in, I have run in to the issue of ASP.NET moaning about the need for a single form element in a master page. TBH, I really dont get why this is a requirement on ASP.NET's part, but hey ho.</p>
<p><strong>Does anyone know if/how I can get the master and content pages to contain form elements that work independantly?</strong></p>
<p>If not, can you offer advice on how to proceed to get the desired look/functionality?</p>
|
[
{
"answer_id": 178525,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 2,
"selected": false,
"text": "asp:ContentPlaceHolder asp:Content asp:Content Page.Master"
},
{
"answer_id": 240608,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 5,
"selected": true,
"text": "<form runat=\"server\" id=\"aspNetForm\"...> </form>"
},
{
"answer_id": 304984,
"author": "Steve Davies",
"author_id": 24209,
"author_profile": "https://Stackoverflow.com/users/24209",
"pm_score": 0,
"selected": false,
"text": "<iframe id=\"login\" src=\"login.aspx\" frameborder=\"0\" enableviewstate=\"false\" scrolling=\"no\" runat=\"server\"></iframe>\n"
},
{
"answer_id": 14295870,
"author": "John Saunders",
"author_id": 76337,
"author_profile": "https://Stackoverflow.com/users/76337",
"pm_score": 2,
"selected": false,
"text": "<%@ Master Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Site - Copy.Master.cs\" Inherits=\"WebApplication1.Site1Master\" %>\n<!DOCTYPE html>\n<html>\n <head runat=\"server\">\n <title>This is a title</title>\n <asp:ContentPlaceHolder runat=\"server\" ID=\"HeadContent\" />\n </head>\n <body>\n <form runat=\"server\">\n <header>\n <div class=\"content-wrapper\">\n <div class=\"float-right\">\n <section id=\"login\">\n <asp:LoginView runat=\"server\" ViewStateMode=\"Disabled\">\n <AnonymousTemplate>\n <asp:ContentPlaceHolder runat=\"server\" ID=\"AnonContent\" />\n </AnonymousTemplate>\n <LoggedInTemplate>\n <asp:ContentPlaceHolder runat=\"server\" ID=\"LoggedInContent\" />\n </LoggedInTemplate>\n </asp:LoginView>\n </section>\n </div>\n </div>\n </header>\n <div id=\"body\">\n <asp:ContentPlaceHolder runat=\"server\" ID=\"FeaturedContent\" />\n <section class=\"content-wrapper main-content clear-fix\">\n <asp:ContentPlaceHolder runat=\"server\" ID=\"MainContent\" />\n </section>\n </div>\n </form>\n</body>\n</html>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
178,398
|
<p>Generally, MVC frameeworks have a structure that looks something like:</p>
<pre><code>/models
/views
/controllers
/utils
</code></pre>
<p>However, in a web application suite, I've decided that clumping all models, views, and controllers together probably wouldn't be the best for clarity, unless I treated the system as one application instead of an application suite. However, some things tie every "application" together, like the notion of users and user roles.</p>
<p>So I have three possible solutions:</p>
<p>(1) Do what I don't really want to do, and keep every model, view, and controller together, regardless of which app it belongs to. This is treating the suite as a single application, since they are tied together by several common threads, including users.</p>
<p>(2) Group the code by application.</p>
<pre><code>/app1
/models
/views
/controllers
/utils
/app2
/models
/views
/controllers
/utils
</code></pre>
<p>(3) Group the code by type, letting utility code be shared among all of the applications.</p>
<pre><code>/models
/app1
/app2
/views
/app1
/app2
/controllers
/app1
/app2
/utils
</code></pre>
<p>Is there an option I missed? What would be the most logical scheme for future developers? I personally prefer 2 and 3, but perhaps most people would expect 1.</p>
|
[
{
"answer_id": 178436,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 3,
"selected": false,
"text": "/app1\n /models\n /views\n /controllers\n /utils\n/app2\n /models\n /views\n /controllers\n /utils\n/common\n /models\n /views\n /utils\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
178,401
|
<p>Can MySql 5.0 views use tables that are located on another server? What is the syntax for creating such a view?</p>
|
[
{
"answer_id": 178438,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 0,
"selected": false,
"text": "USE localhost.myDB;\n\nSELECT * FROM host2.db.tableName; \n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17583/"
] |
178,407
|
<p>Say I have the following:</p>
<pre><code><ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
</code></pre>
<p>How would I select all the child elements after the first one using jQuery? So I can achieve something like:</p>
<pre><code><ul>
<li>First item</li>
<li class="something">Second item</li>
<li class="something">Third item</li>
</ul>
</code></pre>
|
[
{
"answer_id": 178422,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "$(\"li\").slice(1).addClass(\"something\");\n"
},
{
"answer_id": 178425,
"author": "twernt",
"author_id": 18846,
"author_profile": "https://Stackoverflow.com/users/18846",
"pm_score": 8,
"selected": true,
"text": "$(\"li:not(:first-child)\").addClass(\"something\");\n"
},
{
"answer_id": 178435,
"author": "Chris Canal",
"author_id": 5802,
"author_profile": "https://Stackoverflow.com/users/5802",
"pm_score": 1,
"selected": false,
"text": "$('.certificateList input:checkbox:gt(0)')\n"
},
{
"answer_id": 178445,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 2,
"selected": false,
"text": "$('ul :not(:first-child)').addClass('something');\n"
},
{
"answer_id": 178498,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 3,
"selected": false,
"text": "\n$('ul li+li')\n"
},
{
"answer_id": 178723,
"author": "ignu",
"author_id": 24616,
"author_profile": "https://Stackoverflow.com/users/24616",
"pm_score": 2,
"selected": false,
"text": "$(\"li:gt(0)\").addClass(\"something\");\n"
},
{
"answer_id": 187027,
"author": "twernt",
"author_id": 18846,
"author_profile": "https://Stackoverflow.com/users/18846",
"pm_score": 5,
"selected": false,
"text": "$(\"li\").slice(1).addClass(\"something\");\n $(\"li:gt(0)\").addClass(\"something\");\n $(\"li:not(:first-child)\").addClass(\"something\");\n $(\"ul li+li\").addClass(\"something\");\n"
},
{
"answer_id": 50445137,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$('li').not(':first').addClass('something');\n var firstElement = $('li').first();\n$('li').not(firstElement).addClass('something');\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5802/"
] |
178,434
|
<p>Objective-C has no namespaces; it's much like C, everything is within one global namespace. Common practice is to prefix classes with initials, e.g. if you are working at IBM, you could prefix them with "IBM"; if you work for Microsoft, you could use "MS"; and so on. Sometimes the initials refer to the project, e.g. Adium prefixes classes with "AI" (as there is no company behind it of that you could take the initials). Apple prefixes classes with NS and says this prefix is reserved for Apple only.</p>
<p>So far so well. But appending 2 to 4 letters to a class name in front is a very, very limited namespace. E.g. MS or AI could have an entirely different meanings (AI could be Artificial Intelligence for example) and some other developer might decide to use them and create an equally named class. <em>Bang</em>, namespace collision.</p>
<p>Okay, if this is a collision between one of your own classes and one of an external framework you are using, you can easily change the naming of your class, no big deal. <strong>But what if you use two external frameworks, both frameworks that you don't have the source to and that you can't change?</strong> Your application links with both of them and you get name conflicts. How would you go about solving these? What is the best way to work around them in such a way that you can still use both classes?</p>
<p>In C you can work around these by not linking directly to the library, instead you load the library at runtime, using dlopen(), then find the symbol you are looking for using dlsym() and assign it to a global symbol (that you can name any way you like) and then access it through this global symbol. E.g. if you have a conflict because some C library has a function named open(), you could define a variable named myOpen and have it point to the open() function of the library, thus when you want to use the system open(), you just use open() and when you want to use the other one, you access it via the myOpen identifier.</p>
<p>Is something similar possible in Objective-C and if not, is there any other clever, tricky solution you can use resolve namespace conflicts? Any ideas?</p>
<hr />
<h3>Update:</h3>
<p>Just to clarify this: answers that suggest how to avoid namespace collisions in advance or how to create a better namespace are certainly welcome; however, I will not accept them as <strong>the answer</strong> since they don't solve my problem. I have two libraries and their class names collide. I can't change them; I don't have the source of either one. The collision is already there and tips on how it could have been avoided in advance won't help anymore. I can forward them to the developers of these frameworks and hope they choose a better namespace in the future, but for the time being I'm searching a solution to work with the frameworks right now within a single application. Any solutions to make this possible?</p>
|
[
{
"answer_id": 180674,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 7,
"selected": false,
"text": "@compatibility_alias @compatibility_alias @interface COM_WHATEVER_ClassName : NSObject\n@end\n\n@compatibility_alias ClassName COM_WHATEVER_ClassName\n// now ClassName is an alias for COM_WHATEVER_ClassName\n\n@implementation ClassName //OK\n//blah\n@end\n\nClassName *myClass; //OK\n @compatibility_alias COM_WHATEVER_ClassName @compatibility_alias NSClassFromString(ClassName) nil NSClassFromString(COM_WHATERVER_ClassName) ibtool"
},
{
"answer_id": 10670578,
"author": "wcochran",
"author_id": 398461,
"author_profile": "https://Stackoverflow.com/users/398461",
"pm_score": 0,
"selected": false,
"text": "cc foo.o -ldog bar.o -lcat\n foo.o bar.o rat libdog foo.o rat libcat bar.o rat"
},
{
"answer_id": 14390853,
"author": "MaddTheSane",
"author_id": 1975001,
"author_profile": "https://Stackoverflow.com/users/1975001",
"pm_score": -1,
"selected": false,
"text": "NSBundle"
},
{
"answer_id": 20789839,
"author": "Michael Chinen",
"author_id": 333841,
"author_profile": "https://Stackoverflow.com/users/333841",
"pm_score": 2,
"selected": false,
"text": "@compatibility_alias @compatibility_alias NewAliasClass OriginalClass;\n @class @compatibility_alias"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15809/"
] |
178,456
|
<p>Is it better to do this:</p>
<pre><code>try
{
...
}
catch (Exception ex)
{
...
throw;
}
</code></pre>
<p>Or this:</p>
<pre><code>try
{
...
}
catch (Exception ex)
{
...
throw ex;
}
</code></pre>
<p>Do they do the same thing? Is one better than the other?</p>
|
[
{
"answer_id": 178464,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 11,
"selected": true,
"text": "throw;\n throw ex throw ex try\n{\n methodInfo.Invoke(...);\n}\ncatch (System.Reflection.TargetInvocationException e)\n{\n System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(e.InnerException).Throw();\n throw; // just to inform the compiler that the flow never leaves the block\n}\n"
},
{
"answer_id": 178486,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 7,
"selected": false,
"text": "try\n{\n}\ncatch (Exception ex)\n{\n ...\n throw new Exception (\"Add more context here\", ex)\n}\n"
},
{
"answer_id": 178489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "static string ReadAFile(string fileName) {\n string result = string.Empty;\n try {\n result = File.ReadAllLines(fileName);\n } catch(Exception ex) {\n throw; // This will show ReadAllLines in the stack trace\n throw ex; // This will show ReadAFile in the stack trace\n }\n"
},
{
"answer_id": 411750,
"author": "Perry Tribolet",
"author_id": 5668,
"author_profile": "https://Stackoverflow.com/users/5668",
"pm_score": 2,
"selected": false,
"text": " void TrySuspectMethod()\n {\n try\n {\n SuspectMethod();\n }\n#if DEBUG\n catch\n {\n //Don't log error, let developer see\n //original stack trace easily\n throw;\n#else\n catch (Exception ex)\n {\n //Log error for developers and then\n //throw a error with a user-oriented message\n throw new Exception(String.Format\n (\"Dear user, sorry but: {0}\", ex.Message));\n#endif\n }\n }\n"
},
{
"answer_id": 4631411,
"author": "James",
"author_id": 56753,
"author_profile": "https://Stackoverflow.com/users/56753",
"pm_score": 2,
"selected": false,
"text": "void testExceptionHandling()\n{\n try\n {\n throw new ArithmeticException(\"illegal expression\");\n }\n catch (Exception ex)\n {\n throw;\n }\n finally\n {\n System.Diagnostics.Debug.WriteLine(\"finally called.\");\n }\n}\n"
},
{
"answer_id": 11933410,
"author": "Jon Hanna",
"author_id": 400547,
"author_profile": "https://Stackoverflow.com/users/400547",
"pm_score": 4,
"selected": false,
"text": "throw DistinctList<T> List<T> ICollection<T>.CopyTo CopyTo ICollection<T>.CopyTo List<T> DistinctList<T> public CopyTo(T[] array, int arrayIndex)\n{\n if(array == null)\n throw new ArgumentNullException(\"array\");\n if(arrayIndex < 0)\n throw new ArgumentOutOfRangeException(\"arrayIndex\", \"Array Index must be zero or greater.\");\n if(Count > array.Length + arrayIndex)\n throw new ArgumentException(\"Not enough room in array to copy elements starting at index given.\");\n _innerList.CopyTo(array, arrayIndex);\n}\n CopyTo _innerList.CopyTo(array, arrayIndex) public CopyTo(T[] array, int arrayIndex)\n{\n try\n {\n _innerList.CopyTo(array, arrayIndex);\n }\n catch(ArgumentNullException ane)\n {\n throw new ArgumentNullException(\"array\", ane);\n }\n catch(ArgumentOutOfRangeException aore)\n {\n throw new ArgumentOutOfRangeException(\"Array Index must be zero or greater.\", aore);\n }\n catch(ArgumentException ae)\n {\n throw new ArgumentException(\"Not enough room in array to copy elements starting at index given.\", ae);\n }\n}\n ArgumentNullException _innerList.CopyTo ArgumentNullException public CopyTo(T[] array, int arrayIndex)\n{\n try\n {\n _innerList.CopyTo(array, arrayIndex);\n }\n catch(ArgumentException ae)\n {\n throw ae;\n }\n}\n ArgumentException throw; FileStream XmlTextReader AtomFileReader FileNotFoundException XmlException public CopyTo(T[] array, int arrayIndex)\n{\n try\n {\n _innerList.CopyTo(array, arrayIndex);\n }\n catch(ArgumentException ae)\n {\n throw ae;\n }\n catch(Exception ex)\n {\n //we weren't expecting this, there must be a bug in our code that put\n //us into an invalid state, and subsequently let this exception happen.\n LogException(ex);\n throw;\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
178,458
|
<p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
|
[
{
"answer_id": 178582,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "PYTHONPATH PYTHONPATH @set Part1=c:\\blah\\blah\\blah\n@set Part2=c:\\some\\other\\path\n@set that=g:\\shared\\stuff\nset PYTHONPATH=%part1%;%part2%;%that%\n PYTHONPATH"
},
{
"answer_id": 178603,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 1,
"selected": false,
"text": "ihooks __import__"
},
{
"answer_id": 178829,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 0,
"selected": false,
"text": "globals() impp.py value = 5\n >>> import impp\n>>> print globals().keys()\n>>> def printVal():\n>>> print impp.value\n['printVal', '__builtins__', '__file__', 'impp', '__name__', '__doc__']\n impp printVal impp >>> printVal()\n5\n impp globals() >>> del globals()['impp']\n>>> print globals().keys()\n['printVal', '__builtins__', '__file__', '__name__', '__doc__']\n printVal() >>> printVal()\nTraceback (most recent call last):\n File \"test_imp.py\", line 13, in <module>\n printVal()\n File \"test_imp.py\", line 5, in printVal\n print impp.value\nNameError: global name 'impp' is not defined\n __main__ if __name__ == '__main__':\n del globals()['impp']\n unittest.main()\n"
},
{
"answer_id": 179057,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 0,
"selected": false,
"text": "sys.modules"
},
{
"answer_id": 179531,
"author": "DzinX",
"author_id": 18745,
"author_profile": "https://Stackoverflow.com/users/18745",
"pm_score": 4,
"selected": true,
"text": "__import__ class ImportWrapper(object):\n def __init__(self, real_import):\n self.real_import = real_import\n\n def wrapper(self, wantedModules):\n def inner(moduleName, *args, **kwargs):\n if moduleName in wantedModules:\n print \"IMPORTING MODULE\", moduleName\n self.real_import(*args, **kwargs)\n else:\n print \"NOT IMPORTING MODULE\", moduleName\n return inner\n\n def mock_import(self, moduleName, wantedModules):\n __builtins__.__import__ = self.wrapper(wantedModules)\n try:\n __import__(moduleName, globals(), locals(), [], -1)\n finally:\n __builtins__.__import__ = self.real_import\n import myModule wrapper = ImportWrapper(__import__)\nwrapper.mock_import('myModule', [])\n mock_import"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12126/"
] |
178,462
|
<p>I'm trying to setup an Apache/PHP/Postgresql server locally on my machine. I'm using Windows vista business 32bit. I tried to install everything manually (one thing at a time, apache, postgresql and php (all the latest stable releases)) and after I get everything up and running.</p>
<p>Whenever I try to run a script on my machine, I get a "What do you want to do with the *.php file?" dialog. The dialog is the browser's open/save dialog</p>
<p>I'm just trying to get the output of phpinfo() to make sure everything is up and running...</p>
<p>I already tried to mess around a bit with the Apache conf file, but since I don't know much about what I'm doing, I reinstalled everything again and the problem is still there. I kinda get the feeling it must have something to do with the PHP thingy isn't correctly installed.</p>
<p>When i try to get the output of phpinfo as in:</p>
<pre><code><pre><?php
phpinfo();
?></pre>
</code></pre>
<p>I get the browser's "Open/Save" dialog for the *.php file.</p>
|
[
{
"answer_id": 178487,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "LoadModule php5_module \"c:/php/php5apache2_2.dll\"\nAddType application/x-httpd-php .php\nPHPIniDir \"c:/php\"\n C:\\Program Files\\Apache Group\\Apache2\\conf\\httpd.conf"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24098/"
] |
178,473
|
<p>I have three TextBox controls on the page</p>
<pre><code><asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="1">
<asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="2">
<asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True"
OnTextChanged="TextBox_TextChanged" TabIndex="3">
</code></pre>
<p>and an event handler</p>
<pre><code>protected void TextBox_TextChanged(object sender, EventArgs e)
{
WebControl changed_control = (WebControl)sender;
var next_controls = from WebControl control in changed_control.Parent.Controls
where control.TabIndex > changed_control.TabIndex
orderby control.TabIndex
select control;
next_controls.DefaultIfEmpty(changed_control).First().Focus();
}
</code></pre>
<p>The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see <a href="https://stackoverflow.com/questions/173810/autopostback-with-textbox-loses-focus-question-made-clearer">Little JB's problem</a>). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl. </p>
<p>I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!</p>
|
[
{
"answer_id": 178507,
"author": "Paul Nearney",
"author_id": 24071,
"author_profile": "https://Stackoverflow.com/users/24071",
"pm_score": 1,
"selected": false,
"text": "var nextcontrols = from WebControl control in \n Changed_control.Parent.Controls.OfType<TextBox>()... etc\n"
},
{
"answer_id": 178518,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 4,
"selected": true,
"text": "from control in changed_control\n .Parent\n .Controls\n .OfType<WebControl>()\n"
},
{
"answer_id": 178522,
"author": "Dan Goldstein",
"author_id": 23427,
"author_profile": "https://Stackoverflow.com/users/23427",
"pm_score": 0,
"selected": false,
"text": "where control.TabIndex > changed_control.TabIndex && control is WebControl"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
178,479
|
<p>What are the best workarounds for using a SQL <code>IN</code> clause with instances of <code>java.sql.PreparedStatement</code>, which is not supported for multiple values due to SQL injection attack security issues: One <code>?</code> placeholder represents one value, rather than a list of values.</p>
<p>Consider the following SQL statement:</p>
<pre><code>SELECT my_column FROM my_table where search_column IN (?)
</code></pre>
<p>Using <code>preparedStatement.setString( 1, "'A', 'B', 'C'" );</code> is essentially a non-working attempt at a workaround of the reasons for using <code>?</code> in the first place. </p>
<p>What workarounds are available?</p>
|
[
{
"answer_id": 178517,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "PreparedStatement ? OR ?"
},
{
"answer_id": 178635,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 1,
"selected": false,
"text": "select my_column from my_table where instr(?, ','||search_column||',') > 0\n ps.setString(1, \",A,B,C,\"); \n"
},
{
"answer_id": 178650,
"author": "Carl Smotricz",
"author_id": 172211,
"author_profile": "https://Stackoverflow.com/users/172211",
"pm_score": 0,
"selected": false,
"text": "... WHERE tab.col = ? OR tab.col = ? OR tab.col = ?\n"
},
{
"answer_id": 180872,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 3,
"selected": false,
"text": "select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )\n"
},
{
"answer_id": 189347,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 4,
"selected": false,
"text": "while( i < param.size() ) {\n ps.setString(i+1,param.get(i));\n i++;\n}\n\nwhile( i < MAX_PARAMS ) {\n ps.setNull(i+1,Types.VARCHAR);\n i++;\n}\n"
},
{
"answer_id": 189399,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 9,
"selected": true,
"text": "SELECT my_column FROM my_table WHERE search_column = ? SELECT my_column FROM my_table WHERE search_column IN (?,?,?) SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ... UNION ALL WHERE search_column IN (?,?,?) SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6) x = ANY(y) PreparedStatement.setArray setArray query=SELECT * FROM table t WHERE t.column IN (?)\n sql = any( sql, count );\n /**\n * Converts a SQL statement containing exactly one IN clause to an IN clause\n * using multiple comma-delimited parameters.\n *\n * @param sql The SQL statement string with one IN clause.\n * @param params The number of parameters the SQL statement requires.\n * @return The SQL statement with (?) replaced with multiple parameter\n * placeholders.\n */\npublic static String any(String sql, final int params) {\n // Create a comma-delimited list based on the number of parameters.\n final StringBuilder sb = new StringBuilder(\n String.join(\", \", Collections.nCopies(possibleValue.size(), \"?\")));\n\n // For more than 1 parameter, replace the single parameter with\n // multiple parameter placeholders.\n if (sb.length() > 1) {\n sql = sql.replace(\"(?)\", \"(\" + sb + \")\");\n }\n\n // Return the modified comma-delimited list of parameters.\n return sql;\n}\n = ? IN (?) any"
},
{
"answer_id": 1914440,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "public void myQuery(List<String> items, int other) {\n ...\n String q4in = generateQsForIn(items.size());\n String sql = \"select * from stuff where foo in ( \" + q4in + \" ) and bar = ?\";\n PreparedStatement ps = connection.prepareStatement(sql);\n int i = 1;\n for (String item : items) {\n ps.setString(i++, item);\n }\n ps.setInt(i++, other);\n ResultSet rs = ps.executeQuery();\n ...\n}\n\nprivate String generateQsForIn(int numQs) {\n String items = \"\";\n for (int i = 0; i < numQs; i++) {\n if (i != 0) items += \", \";\n items += \"?\";\n }\n return items;\n}\n"
},
{
"answer_id": 5104833,
"author": "Javier Ibanez",
"author_id": 632332,
"author_profile": "https://Stackoverflow.com/users/632332",
"pm_score": 3,
"selected": false,
"text": "create or replace type split_tbl as table of varchar(32767);\n/\n\ncreate or replace function split\n(\n p_list varchar2,\n p_del varchar2 := ','\n) return split_tbl pipelined\nis\n l_idx pls_integer;\n l_list varchar2(32767) := p_list;\n l_value varchar2(32767);\nbegin\n loop\n l_idx := instr(l_list,p_del);\n if l_idx > 0 then\n pipe row(substr(l_list,1,l_idx-1));\n l_list := substr(l_list,l_idx+length(p_del));\n else\n pipe row(l_list);\n exit;\n end if;\n end loop;\n return;\nend split;\n/\n select * from table(split('one,two,three'))\n one\n two\n three\n\nselect * from TABLE1 where COL1 in (select * from table(split('value1,value2')))\n value1 AAA\n value2 BBB\n \"select * from TABLE where COL in (select * from table(split(?)))\"\n"
},
{
"answer_id": 10240302,
"author": "Boris",
"author_id": 1345608,
"author_profile": "https://Stackoverflow.com/users/1345608",
"pm_score": 7,
"selected": false,
"text": "final PreparedStatement statement = connection.prepareStatement(\n \"SELECT my_column FROM my_table where search_column = ANY (?)\"\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(\"text\", values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n final PreparedStatement statement = connection.prepareStatement(\n \"SELECT my_column FROM my_table \" + \n \"where search_column IN (SELECT * FROM unnest(?))\"\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(\"text\", values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n"
},
{
"answer_id": 18422316,
"author": "kapil das",
"author_id": 2041542,
"author_profile": "https://Stackoverflow.com/users/2041542",
"pm_score": 1,
"selected": false,
"text": "SELECT my_column FROM my_table where search_column IN (?)\n select id, name from users where id in (?, ?, ?)\n preparedStatement.setString( 1, 'A');\npreparedStatement.setString( 2,'B');\npreparedStatement.setString( 3, 'C');\n"
},
{
"answer_id": 21361828,
"author": "Pankaj",
"author_id": 926520,
"author_profile": "https://Stackoverflow.com/users/926520",
"pm_score": 0,
"selected": false,
"text": " int i = 1;\n for(; i <=ids.length; i++){\n ps.setInt(i, ids[i-1]);\n }\n\n //set null for remaining ones\n for(; i<=PARAM_SIZE;i++){\n ps.setNull(i, java.sql.Types.INTEGER);\n }\n"
},
{
"answer_id": 27738214,
"author": "Vasili",
"author_id": 446098,
"author_profile": "https://Stackoverflow.com/users/446098",
"pm_score": 0,
"selected": false,
"text": "select * from my_table where REGEXP_LIKE (search_column, 'value1|value2')\n"
},
{
"answer_id": 29062027,
"author": "bnsk",
"author_id": 1666429,
"author_profile": "https://Stackoverflow.com/users/1666429",
"pm_score": 0,
"selected": false,
"text": " select * from TABLE_A where ATTR IN (PARAM);\n String param1 = \"X\";\n String param2 = \"Y\";\n String param1 = param1.append(\",\").append(param2);\n String query = query.replaceFirst(\"PARAM\",param1); where we have the value of query as \n\n query = \"select * from TABLE_A where ATTR IN (PARAM)\";\n"
},
{
"answer_id": 29397855,
"author": "epeleg",
"author_id": 25412,
"author_profile": "https://Stackoverflow.com/users/25412",
"pm_score": 0,
"selected": false,
"text": "query=\"select f1,f2 from t1 where f3=? and f2 in (\" + sListOfIds + \");\";\n"
},
{
"answer_id": 29739504,
"author": "dwjohnston",
"author_id": 1068446,
"author_profile": "https://Stackoverflow.com/users/1068446",
"pm_score": 2,
"selected": false,
"text": "/*usage:\n\nUtil u = new Util(500); //500 items per bracket. \nString sqlBefore = \"select * from myTable where (\";\nList<Integer> values = new ArrayList<Integer>(Arrays.asList(1,2,4,5)); \nstring sqlAfter = \") and foo = 'bar'\"; \n\nPreparedStatement ps = u.prepareStatements(sqlBefore, values, sqlAfter, connection, \"someId\");\n*/\n\n\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Util {\n\n private int numValuesInClause;\n\n public Util(int numValuesInClause) {\n super();\n this.numValuesInClause = numValuesInClause;\n }\n\n public int getNumValuesInClause() {\n return numValuesInClause;\n }\n\n public void setNumValuesInClause(int numValuesInClause) {\n this.numValuesInClause = numValuesInClause;\n }\n\n /** Split a given list into a list of lists for the given size of numValuesInClause*/\n public List<List<Integer>> splitList(\n List<Integer> values) {\n\n\n List<List<Integer>> newList = new ArrayList<List<Integer>>(); \n while (values.size() > numValuesInClause) {\n List<Integer> sublist = values.subList(0,numValuesInClause);\n List<Integer> values2 = values.subList(numValuesInClause, values.size()); \n values = values2; \n\n newList.add( sublist);\n }\n newList.add(values);\n\n return newList;\n }\n\n /**\n * Generates a series of split out in clause statements. \n * @param sqlBefore \"\"select * from dual where (\"\n * @param values [1,2,3,4,5,6,7,8,9,10]\n * @param \"sqlAfter ) and id = 5\"\n * @return \"select * from dual where (id in (1,2,3) or id in (4,5,6) or id in (7,8,9) or id in (10)\"\n */\n public String genInClauseSql(String sqlBefore, List<Integer> values,\n String sqlAfter, String identifier) \n {\n List<List<Integer>> newLists = splitList(values);\n String stmt = sqlBefore;\n\n /* now generate the in clause for each list */\n int j = 0; /* keep track of list:newLists index */\n for (List<Integer> list : newLists) {\n stmt = stmt + identifier +\" in (\";\n StringBuilder innerBuilder = new StringBuilder();\n\n for (int i = 0; i < list.size(); i++) {\n innerBuilder.append(\"?,\");\n }\n\n\n\n String inClause = innerBuilder.deleteCharAt(\n innerBuilder.length() - 1).toString();\n\n stmt = stmt + inClause;\n stmt = stmt + \")\";\n\n\n if (++j < newLists.size()) {\n stmt = stmt + \" OR \";\n }\n\n }\n\n stmt = stmt + sqlAfter;\n return stmt;\n }\n\n /**\n * Method to convert your SQL and a list of ID into a safe prepared\n * statements\n * \n * @throws SQLException\n */\n public PreparedStatement prepareStatements(String sqlBefore,\n ArrayList<Integer> values, String sqlAfter, Connection c, String identifier)\n throws SQLException {\n\n /* First split our potentially big list into lots of lists */\n String stmt = genInClauseSql(sqlBefore, values, sqlAfter, identifier);\n PreparedStatement ps = c.prepareStatement(stmt);\n\n int i = 1;\n for (int val : values)\n {\n\n ps.setInt(i++, val);\n\n }\n return ps;\n\n }\n\n}\n"
},
{
"answer_id": 30573323,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 2,
"selected": false,
"text": "SELECT my_column FROM my_table where search_column IN (select COLUMN_VALUE from table(?))\n IN"
},
{
"answer_id": 35459827,
"author": "Gee Bee",
"author_id": 5903395,
"author_profile": "https://Stackoverflow.com/users/5903395",
"pm_score": 3,
"selected": false,
"text": "function getCustomers(in_customerIdList clob) return sys_refcursor is \nbegin\n aux_in_list.parse(in_customerIdList);\n open res for\n select * \n from customer c,\n in_list v\n where c.customer_id=v.token;\n return res;\nend;\n create or replace view in_list\nas\nselect\n trim( substr (txt,\n instr (txt, ',', 1, level ) + 1,\n instr (txt, ',', 1, level+1)\n - instr (txt, ',', 1, level) -1 ) ) as token\n from (select ','||aux_in_list.getpayload||',' txt from dual)\nconnect by level <= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1\n"
},
{
"answer_id": 36491947,
"author": "m.sabouri",
"author_id": 3353334,
"author_profile": "https://Stackoverflow.com/users/3353334",
"pm_score": 3,
"selected": false,
"text": " String inParenthesis = \"(?\";\n for(int i = 1;i < myList.size();i++) {\n inParenthesis += \", ?\";\n }\n inParenthesis += \")\";\n\n try(PreparedStatement statement = SQLite.connection.prepareStatement(\n String.format(\"UPDATE table SET value='WINNER' WHERE startTime=? AND name=? AND traderIdx=? AND someValue IN %s\", inParenthesis))) {\n int x = 1;\n statement.setLong(x++, race.startTime);\n statement.setString(x++, race.name);\n statement.setInt(x++, traderIdx);\n\n for(String str : race.betFair.winners) {\n statement.setString(x++, str);\n }\n\n int effected = statement.executeUpdate();\n }\n"
},
{
"answer_id": 37734734,
"author": "Panky031",
"author_id": 5882929,
"author_profile": "https://Stackoverflow.com/users/5882929",
"pm_score": 2,
"selected": false,
"text": "PreparedStatement statement = connection.prepareStatement(\"Select * from emp where field in (?)\");\nArray array = statement.getConnection().createArrayOf(\"VARCHAR\", new Object[]{\"E1\", \"E2\",\"E3\"});\nstatement.setArray(1, array);\nResultSet rs = statement.executeQuery();\n"
},
{
"answer_id": 41988063,
"author": "smooth_smoothie",
"author_id": 373466,
"author_profile": "https://Stackoverflow.com/users/373466",
"pm_score": -1,
"selected": false,
"text": " var s1 = \" SELECT \"\n\n + \"FROM table t \"\n\n + \" where t.field in \";\n\n var s3 = '(';\n\n for(var i =0;i<searchTerms.length;i++)\n {\n if(i+1 == searchTerms.length)\n {\n s3 = s3+'?)';\n }\n else\n {\n s3 = s3+'?, ' ;\n }\n }\n var query = s1+s3;\n\n var pstmt = connection.prepareStatement(query);\n\n for(var i =0;i<searchTerms.length;i++)\n {\n pstmt.setString(i+1, searchTerms[i]);\n }\n SearchTerms"
},
{
"answer_id": 44422748,
"author": "pedram bashiri",
"author_id": 2695227,
"author_profile": "https://Stackoverflow.com/users/2695227",
"pm_score": 0,
"selected": false,
"text": "String query = \"SELECT my_column FROM my_table where search_column IN ($searchColumns)\";\nquery = query.replace(\"$searchColumns\", \"'A', 'B', 'C'\");\nStatement stmt = connection.createStatement();\nboolean hasResults = stmt.execute(query);\ndo {\n if (hasResults)\n return stmt.getResultSet();\n\n hasResults = stmt.getMoreResults();\n\n} while (hasResults || stmt.getUpdateCount() != -1);\n"
},
{
"answer_id": 49035778,
"author": "Raheel",
"author_id": 1033305,
"author_profile": "https://Stackoverflow.com/users/1033305",
"pm_score": 1,
"selected": false,
"text": "String baseQuery =\"SELECT my_column FROM my_table where search_column IN (%s)\"\n\nString markersString = inputArray.stream().map(e -> \"?\").collect(joining(\",\"));\nString sqlQuery = String.format(baseSQL, markersString);\n\n//Now create Prepared Statement and use loop to Set entries\nint index=1;\n\nfor (String input : inputArray) {\n preparedStatement.setString(index++, input);\n}\n"
},
{
"answer_id": 50085176,
"author": "Gurwinder Singh",
"author_id": 6348498,
"author_profile": "https://Stackoverflow.com/users/6348498",
"pm_score": 4,
"selected": false,
"text": "Collections.nCopies String.join List<String> params = getParams();\nString placeHolders = String.join(\",\", Collections.nCopies(params.size(), \"?\"));\nString sql = \"select * from your_table where some_column in (\" + placeHolders + \")\";\ntry ( Connection connection = getConnection();\n PreparedStatement ps = connection.prepareStatement(sql)) {\n int i = 1;\n for (String param : params) {\n ps.setString(i++, param);\n }\n /*\n * Execute query/do stuff\n */\n}\n"
},
{
"answer_id": 54140112,
"author": "Joel Fouse",
"author_id": 1899071,
"author_profile": "https://Stackoverflow.com/users/1899071",
"pm_score": 1,
"selected": false,
"text": "select column from table\nwhere search_column = any (string_to_array('foo,blah,abc', ',')::text[]);\n select column from table\nwhere search_column = any (string_to_array($1, ',')::text[]);\n select column from table\nwhere search_column like any (string_to_array('foo%,blah%,abc%', ',')::text[]);\n"
},
{
"answer_id": 59746690,
"author": "Nikita Shah",
"author_id": 1039367,
"author_profile": "https://Stackoverflow.com/users/1039367",
"pm_score": -1,
"selected": false,
"text": "public class SqlHelper\n{\n public static final ArrayList<String>platformList = new ArrayList<>(Arrays.asList(\"iOS\",\"Android\",\"Windows\",\"Mac\"));\n\n public static final String testQuery = \"select * from devices where platform_nm in (:PLATFORM_NAME)\";\n}\n public class Test extends NamedParameterJdbcDaoSupport\npublic List<SampleModelClass> runQuery()\n{\n //define rowMapper to insert in object of SampleClass\n final Map<String,Object> map = new HashMap<>();\n map.put(\"PLATFORM_LIST\",DeviceDataSyncQueryConstants.platformList);\n return getNamedParameterJdbcTemplate().query(SqlHelper.testQuery, map, rowMapper)\n}\n"
},
{
"answer_id": 67209550,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 1,
"selected": false,
"text": "IN IN IN"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15816/"
] |
178,482
|
<p>For a school project, I need to create a way to create personnalized queries based on end-user choices.<br />
Since the user can choose basically any fields from any combination of tables, I need to find a way to map the tables in order to make a join and not have extraneous data (This may lead to incoherent reports, but we're willing to live with that).</p>
<p>For up to two tables, I already managed to design an algorithm that works fine. However, when I add another table, I can't find a way to path through my database. All tables available for the personnalized reports can be linked together so it really all falls down to finding which path to use.</p>
|
[
{
"answer_id": 178517,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "PreparedStatement ? OR ?"
},
{
"answer_id": 178635,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 1,
"selected": false,
"text": "select my_column from my_table where instr(?, ','||search_column||',') > 0\n ps.setString(1, \",A,B,C,\"); \n"
},
{
"answer_id": 178650,
"author": "Carl Smotricz",
"author_id": 172211,
"author_profile": "https://Stackoverflow.com/users/172211",
"pm_score": 0,
"selected": false,
"text": "... WHERE tab.col = ? OR tab.col = ? OR tab.col = ?\n"
},
{
"answer_id": 180872,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 3,
"selected": false,
"text": "select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )\n"
},
{
"answer_id": 189347,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 4,
"selected": false,
"text": "while( i < param.size() ) {\n ps.setString(i+1,param.get(i));\n i++;\n}\n\nwhile( i < MAX_PARAMS ) {\n ps.setNull(i+1,Types.VARCHAR);\n i++;\n}\n"
},
{
"answer_id": 189399,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 9,
"selected": true,
"text": "SELECT my_column FROM my_table WHERE search_column = ? SELECT my_column FROM my_table WHERE search_column IN (?,?,?) SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ... UNION ALL WHERE search_column IN (?,?,?) SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6) x = ANY(y) PreparedStatement.setArray setArray query=SELECT * FROM table t WHERE t.column IN (?)\n sql = any( sql, count );\n /**\n * Converts a SQL statement containing exactly one IN clause to an IN clause\n * using multiple comma-delimited parameters.\n *\n * @param sql The SQL statement string with one IN clause.\n * @param params The number of parameters the SQL statement requires.\n * @return The SQL statement with (?) replaced with multiple parameter\n * placeholders.\n */\npublic static String any(String sql, final int params) {\n // Create a comma-delimited list based on the number of parameters.\n final StringBuilder sb = new StringBuilder(\n String.join(\", \", Collections.nCopies(possibleValue.size(), \"?\")));\n\n // For more than 1 parameter, replace the single parameter with\n // multiple parameter placeholders.\n if (sb.length() > 1) {\n sql = sql.replace(\"(?)\", \"(\" + sb + \")\");\n }\n\n // Return the modified comma-delimited list of parameters.\n return sql;\n}\n = ? IN (?) any"
},
{
"answer_id": 1914440,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "public void myQuery(List<String> items, int other) {\n ...\n String q4in = generateQsForIn(items.size());\n String sql = \"select * from stuff where foo in ( \" + q4in + \" ) and bar = ?\";\n PreparedStatement ps = connection.prepareStatement(sql);\n int i = 1;\n for (String item : items) {\n ps.setString(i++, item);\n }\n ps.setInt(i++, other);\n ResultSet rs = ps.executeQuery();\n ...\n}\n\nprivate String generateQsForIn(int numQs) {\n String items = \"\";\n for (int i = 0; i < numQs; i++) {\n if (i != 0) items += \", \";\n items += \"?\";\n }\n return items;\n}\n"
},
{
"answer_id": 5104833,
"author": "Javier Ibanez",
"author_id": 632332,
"author_profile": "https://Stackoverflow.com/users/632332",
"pm_score": 3,
"selected": false,
"text": "create or replace type split_tbl as table of varchar(32767);\n/\n\ncreate or replace function split\n(\n p_list varchar2,\n p_del varchar2 := ','\n) return split_tbl pipelined\nis\n l_idx pls_integer;\n l_list varchar2(32767) := p_list;\n l_value varchar2(32767);\nbegin\n loop\n l_idx := instr(l_list,p_del);\n if l_idx > 0 then\n pipe row(substr(l_list,1,l_idx-1));\n l_list := substr(l_list,l_idx+length(p_del));\n else\n pipe row(l_list);\n exit;\n end if;\n end loop;\n return;\nend split;\n/\n select * from table(split('one,two,three'))\n one\n two\n three\n\nselect * from TABLE1 where COL1 in (select * from table(split('value1,value2')))\n value1 AAA\n value2 BBB\n \"select * from TABLE where COL in (select * from table(split(?)))\"\n"
},
{
"answer_id": 10240302,
"author": "Boris",
"author_id": 1345608,
"author_profile": "https://Stackoverflow.com/users/1345608",
"pm_score": 7,
"selected": false,
"text": "final PreparedStatement statement = connection.prepareStatement(\n \"SELECT my_column FROM my_table where search_column = ANY (?)\"\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(\"text\", values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n final PreparedStatement statement = connection.prepareStatement(\n \"SELECT my_column FROM my_table \" + \n \"where search_column IN (SELECT * FROM unnest(?))\"\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(\"text\", values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n"
},
{
"answer_id": 18422316,
"author": "kapil das",
"author_id": 2041542,
"author_profile": "https://Stackoverflow.com/users/2041542",
"pm_score": 1,
"selected": false,
"text": "SELECT my_column FROM my_table where search_column IN (?)\n select id, name from users where id in (?, ?, ?)\n preparedStatement.setString( 1, 'A');\npreparedStatement.setString( 2,'B');\npreparedStatement.setString( 3, 'C');\n"
},
{
"answer_id": 21361828,
"author": "Pankaj",
"author_id": 926520,
"author_profile": "https://Stackoverflow.com/users/926520",
"pm_score": 0,
"selected": false,
"text": " int i = 1;\n for(; i <=ids.length; i++){\n ps.setInt(i, ids[i-1]);\n }\n\n //set null for remaining ones\n for(; i<=PARAM_SIZE;i++){\n ps.setNull(i, java.sql.Types.INTEGER);\n }\n"
},
{
"answer_id": 27738214,
"author": "Vasili",
"author_id": 446098,
"author_profile": "https://Stackoverflow.com/users/446098",
"pm_score": 0,
"selected": false,
"text": "select * from my_table where REGEXP_LIKE (search_column, 'value1|value2')\n"
},
{
"answer_id": 29062027,
"author": "bnsk",
"author_id": 1666429,
"author_profile": "https://Stackoverflow.com/users/1666429",
"pm_score": 0,
"selected": false,
"text": " select * from TABLE_A where ATTR IN (PARAM);\n String param1 = \"X\";\n String param2 = \"Y\";\n String param1 = param1.append(\",\").append(param2);\n String query = query.replaceFirst(\"PARAM\",param1); where we have the value of query as \n\n query = \"select * from TABLE_A where ATTR IN (PARAM)\";\n"
},
{
"answer_id": 29397855,
"author": "epeleg",
"author_id": 25412,
"author_profile": "https://Stackoverflow.com/users/25412",
"pm_score": 0,
"selected": false,
"text": "query=\"select f1,f2 from t1 where f3=? and f2 in (\" + sListOfIds + \");\";\n"
},
{
"answer_id": 29739504,
"author": "dwjohnston",
"author_id": 1068446,
"author_profile": "https://Stackoverflow.com/users/1068446",
"pm_score": 2,
"selected": false,
"text": "/*usage:\n\nUtil u = new Util(500); //500 items per bracket. \nString sqlBefore = \"select * from myTable where (\";\nList<Integer> values = new ArrayList<Integer>(Arrays.asList(1,2,4,5)); \nstring sqlAfter = \") and foo = 'bar'\"; \n\nPreparedStatement ps = u.prepareStatements(sqlBefore, values, sqlAfter, connection, \"someId\");\n*/\n\n\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Util {\n\n private int numValuesInClause;\n\n public Util(int numValuesInClause) {\n super();\n this.numValuesInClause = numValuesInClause;\n }\n\n public int getNumValuesInClause() {\n return numValuesInClause;\n }\n\n public void setNumValuesInClause(int numValuesInClause) {\n this.numValuesInClause = numValuesInClause;\n }\n\n /** Split a given list into a list of lists for the given size of numValuesInClause*/\n public List<List<Integer>> splitList(\n List<Integer> values) {\n\n\n List<List<Integer>> newList = new ArrayList<List<Integer>>(); \n while (values.size() > numValuesInClause) {\n List<Integer> sublist = values.subList(0,numValuesInClause);\n List<Integer> values2 = values.subList(numValuesInClause, values.size()); \n values = values2; \n\n newList.add( sublist);\n }\n newList.add(values);\n\n return newList;\n }\n\n /**\n * Generates a series of split out in clause statements. \n * @param sqlBefore \"\"select * from dual where (\"\n * @param values [1,2,3,4,5,6,7,8,9,10]\n * @param \"sqlAfter ) and id = 5\"\n * @return \"select * from dual where (id in (1,2,3) or id in (4,5,6) or id in (7,8,9) or id in (10)\"\n */\n public String genInClauseSql(String sqlBefore, List<Integer> values,\n String sqlAfter, String identifier) \n {\n List<List<Integer>> newLists = splitList(values);\n String stmt = sqlBefore;\n\n /* now generate the in clause for each list */\n int j = 0; /* keep track of list:newLists index */\n for (List<Integer> list : newLists) {\n stmt = stmt + identifier +\" in (\";\n StringBuilder innerBuilder = new StringBuilder();\n\n for (int i = 0; i < list.size(); i++) {\n innerBuilder.append(\"?,\");\n }\n\n\n\n String inClause = innerBuilder.deleteCharAt(\n innerBuilder.length() - 1).toString();\n\n stmt = stmt + inClause;\n stmt = stmt + \")\";\n\n\n if (++j < newLists.size()) {\n stmt = stmt + \" OR \";\n }\n\n }\n\n stmt = stmt + sqlAfter;\n return stmt;\n }\n\n /**\n * Method to convert your SQL and a list of ID into a safe prepared\n * statements\n * \n * @throws SQLException\n */\n public PreparedStatement prepareStatements(String sqlBefore,\n ArrayList<Integer> values, String sqlAfter, Connection c, String identifier)\n throws SQLException {\n\n /* First split our potentially big list into lots of lists */\n String stmt = genInClauseSql(sqlBefore, values, sqlAfter, identifier);\n PreparedStatement ps = c.prepareStatement(stmt);\n\n int i = 1;\n for (int val : values)\n {\n\n ps.setInt(i++, val);\n\n }\n return ps;\n\n }\n\n}\n"
},
{
"answer_id": 30573323,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 2,
"selected": false,
"text": "SELECT my_column FROM my_table where search_column IN (select COLUMN_VALUE from table(?))\n IN"
},
{
"answer_id": 35459827,
"author": "Gee Bee",
"author_id": 5903395,
"author_profile": "https://Stackoverflow.com/users/5903395",
"pm_score": 3,
"selected": false,
"text": "function getCustomers(in_customerIdList clob) return sys_refcursor is \nbegin\n aux_in_list.parse(in_customerIdList);\n open res for\n select * \n from customer c,\n in_list v\n where c.customer_id=v.token;\n return res;\nend;\n create or replace view in_list\nas\nselect\n trim( substr (txt,\n instr (txt, ',', 1, level ) + 1,\n instr (txt, ',', 1, level+1)\n - instr (txt, ',', 1, level) -1 ) ) as token\n from (select ','||aux_in_list.getpayload||',' txt from dual)\nconnect by level <= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1\n"
},
{
"answer_id": 36491947,
"author": "m.sabouri",
"author_id": 3353334,
"author_profile": "https://Stackoverflow.com/users/3353334",
"pm_score": 3,
"selected": false,
"text": " String inParenthesis = \"(?\";\n for(int i = 1;i < myList.size();i++) {\n inParenthesis += \", ?\";\n }\n inParenthesis += \")\";\n\n try(PreparedStatement statement = SQLite.connection.prepareStatement(\n String.format(\"UPDATE table SET value='WINNER' WHERE startTime=? AND name=? AND traderIdx=? AND someValue IN %s\", inParenthesis))) {\n int x = 1;\n statement.setLong(x++, race.startTime);\n statement.setString(x++, race.name);\n statement.setInt(x++, traderIdx);\n\n for(String str : race.betFair.winners) {\n statement.setString(x++, str);\n }\n\n int effected = statement.executeUpdate();\n }\n"
},
{
"answer_id": 37734734,
"author": "Panky031",
"author_id": 5882929,
"author_profile": "https://Stackoverflow.com/users/5882929",
"pm_score": 2,
"selected": false,
"text": "PreparedStatement statement = connection.prepareStatement(\"Select * from emp where field in (?)\");\nArray array = statement.getConnection().createArrayOf(\"VARCHAR\", new Object[]{\"E1\", \"E2\",\"E3\"});\nstatement.setArray(1, array);\nResultSet rs = statement.executeQuery();\n"
},
{
"answer_id": 41988063,
"author": "smooth_smoothie",
"author_id": 373466,
"author_profile": "https://Stackoverflow.com/users/373466",
"pm_score": -1,
"selected": false,
"text": " var s1 = \" SELECT \"\n\n + \"FROM table t \"\n\n + \" where t.field in \";\n\n var s3 = '(';\n\n for(var i =0;i<searchTerms.length;i++)\n {\n if(i+1 == searchTerms.length)\n {\n s3 = s3+'?)';\n }\n else\n {\n s3 = s3+'?, ' ;\n }\n }\n var query = s1+s3;\n\n var pstmt = connection.prepareStatement(query);\n\n for(var i =0;i<searchTerms.length;i++)\n {\n pstmt.setString(i+1, searchTerms[i]);\n }\n SearchTerms"
},
{
"answer_id": 44422748,
"author": "pedram bashiri",
"author_id": 2695227,
"author_profile": "https://Stackoverflow.com/users/2695227",
"pm_score": 0,
"selected": false,
"text": "String query = \"SELECT my_column FROM my_table where search_column IN ($searchColumns)\";\nquery = query.replace(\"$searchColumns\", \"'A', 'B', 'C'\");\nStatement stmt = connection.createStatement();\nboolean hasResults = stmt.execute(query);\ndo {\n if (hasResults)\n return stmt.getResultSet();\n\n hasResults = stmt.getMoreResults();\n\n} while (hasResults || stmt.getUpdateCount() != -1);\n"
},
{
"answer_id": 49035778,
"author": "Raheel",
"author_id": 1033305,
"author_profile": "https://Stackoverflow.com/users/1033305",
"pm_score": 1,
"selected": false,
"text": "String baseQuery =\"SELECT my_column FROM my_table where search_column IN (%s)\"\n\nString markersString = inputArray.stream().map(e -> \"?\").collect(joining(\",\"));\nString sqlQuery = String.format(baseSQL, markersString);\n\n//Now create Prepared Statement and use loop to Set entries\nint index=1;\n\nfor (String input : inputArray) {\n preparedStatement.setString(index++, input);\n}\n"
},
{
"answer_id": 50085176,
"author": "Gurwinder Singh",
"author_id": 6348498,
"author_profile": "https://Stackoverflow.com/users/6348498",
"pm_score": 4,
"selected": false,
"text": "Collections.nCopies String.join List<String> params = getParams();\nString placeHolders = String.join(\",\", Collections.nCopies(params.size(), \"?\"));\nString sql = \"select * from your_table where some_column in (\" + placeHolders + \")\";\ntry ( Connection connection = getConnection();\n PreparedStatement ps = connection.prepareStatement(sql)) {\n int i = 1;\n for (String param : params) {\n ps.setString(i++, param);\n }\n /*\n * Execute query/do stuff\n */\n}\n"
},
{
"answer_id": 54140112,
"author": "Joel Fouse",
"author_id": 1899071,
"author_profile": "https://Stackoverflow.com/users/1899071",
"pm_score": 1,
"selected": false,
"text": "select column from table\nwhere search_column = any (string_to_array('foo,blah,abc', ',')::text[]);\n select column from table\nwhere search_column = any (string_to_array($1, ',')::text[]);\n select column from table\nwhere search_column like any (string_to_array('foo%,blah%,abc%', ',')::text[]);\n"
},
{
"answer_id": 59746690,
"author": "Nikita Shah",
"author_id": 1039367,
"author_profile": "https://Stackoverflow.com/users/1039367",
"pm_score": -1,
"selected": false,
"text": "public class SqlHelper\n{\n public static final ArrayList<String>platformList = new ArrayList<>(Arrays.asList(\"iOS\",\"Android\",\"Windows\",\"Mac\"));\n\n public static final String testQuery = \"select * from devices where platform_nm in (:PLATFORM_NAME)\";\n}\n public class Test extends NamedParameterJdbcDaoSupport\npublic List<SampleModelClass> runQuery()\n{\n //define rowMapper to insert in object of SampleClass\n final Map<String,Object> map = new HashMap<>();\n map.put(\"PLATFORM_LIST\",DeviceDataSyncQueryConstants.platformList);\n return getNamedParameterJdbcTemplate().query(SqlHelper.testQuery, map, rowMapper)\n}\n"
},
{
"answer_id": 67209550,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 1,
"selected": false,
"text": "IN IN IN"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25818/"
] |
178,516
|
<p>Answers to a recent post (Any chances to imitate times() Ruby method in C#?) use the <b>=></b> operator in the usage examples. What does this operator do? I can't locate it in my C# book, and it is hard to search for symbols like this online. (I couldn't find it.)</p>
|
[
{
"answer_id": 178529,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "MyControl.OnMouseDown += (sender, e) =>\n{\n // Do something in the mouse down event\n};\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19274/"
] |
178,519
|
<p>I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?</p>
|
[
{
"answer_id": 178534,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "/system\n/css\n/js\n/img\n site_url(url) site_url('css/file.css')"
},
{
"answer_id": 180835,
"author": "Click Online Design",
"author_id": 25695,
"author_profile": "https://Stackoverflow.com/users/25695",
"pm_score": 1,
"selected": false,
"text": "<?=base_url()?> <link href=\"<?=base_url()?>/css/style.css\" rel=\"stylesheet\" type=\"text/css\" />\n"
},
{
"answer_id": 11805029,
"author": "Jordan Arseno",
"author_id": 568884,
"author_profile": "https://Stackoverflow.com/users/568884",
"pm_score": 3,
"selected": false,
"text": "application system system public_html (www) projekt public_html (www) CISYSTEM 202 210 /CISYSTEM\n /202\n /210\n /another_CI_version\n/projekt_application\n /models\n /views\n /controllers\n /private_assets\n/public_html\n /projekt\n index.php\n .htaccess\n css\n img\n js\n lib\n index.php index.php $system_path = 'system'; $system_path = '../../CISYSTEM/210'; $application_folder = 'application'; $application_folder = '../../projekt_application'; site_url() site_url() <base> <base href=\"<?= site_url();?>\"> <head> <a href='controllername/functionname'>Some Action</a>"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16511/"
] |
178,524
|
<p>I recently read this Phil Haack post (<a href="http://haacked.com/archive/2007/06/13/the-most-useful-.net-utility-classes-developers-tend-to-reinvent.aspx" rel="nofollow noreferrer">The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse</a>) from last year, and thought I'd see if anyone has any additions to the list.</p>
|
[
{
"answer_id": 178544,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 5,
"selected": false,
"text": "return \"£\" & iSomeValue\n return String.Format (\"{0:c}\", iSomeValue)\n"
},
{
"answer_id": 178552,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "String.IsNullOrEmpty()"
},
{
"answer_id": 178587,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 3,
"selected": false,
"text": "input.StartsWith(\"stuff\") Regex.IsMatch(input, @\"^stuff\")"
},
{
"answer_id": 178607,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 5,
"selected": false,
"text": "Path.GetFileNameWithoutExtension(string path)\n Path.GetTempFileName()\n"
},
{
"answer_id": 178647,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 4,
"selected": false,
"text": "IO.Path.DirectorySeparatorChar\n"
},
{
"answer_id": 178659,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 3,
"selected": false,
"text": "using System.IO;\n\nFile.Exists(FileNamePath)\n\nDirectory.Exists(strDirPath)\n\nFile.Move(currentLocation, newLocation);\n\nFile.Delete(fileToDelete);\n\nDirectory.CreateDirectory(directory)\n\nSystem.IO.FileStream file = System.IO.File.Create(fullFilePath);\n"
},
{
"answer_id": 178683,
"author": "torial",
"author_id": 13990,
"author_profile": "https://Stackoverflow.com/users/13990",
"pm_score": 3,
"selected": false,
"text": "System.IO.File.ReadAllText System.IO.File.WriteAllText"
},
{
"answer_id": 178691,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 6,
"selected": false,
"text": "string path = basePath + \"\\\\\" + fileName;\n string path = Path.Combine(basePath, fileName);\n byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine\n File.ReadAllText() File.ReadAllLines()"
},
{
"answer_id": 178786,
"author": "Peter Walke",
"author_id": 12497,
"author_profile": "https://Stackoverflow.com/users/12497",
"pm_score": 4,
"selected": false,
"text": "string directory =\nEnvironment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n"
},
{
"answer_id": 178804,
"author": "Johnno Nolan",
"author_id": 1116,
"author_profile": "https://Stackoverflow.com/users/1116",
"pm_score": 5,
"selected": false,
"text": "System.Diagnostics.Stopwatch"
},
{
"answer_id": 179270,
"author": "Romain Verdier",
"author_id": 4687,
"author_profile": "https://Stackoverflow.com/users/4687",
"pm_score": 4,
"selected": false,
"text": "Environment.NewLine\n"
},
{
"answer_id": 180079,
"author": "Bobby Ortiz",
"author_id": 25843,
"author_profile": "https://Stackoverflow.com/users/25843",
"pm_score": 4,
"selected": false,
"text": " WebClient wc = new WebClient();\n wc.DownloadFile(sourceURLAddress, destFileName);\n"
},
{
"answer_id": 180533,
"author": "Ed Ball",
"author_id": 23818,
"author_profile": "https://Stackoverflow.com/users/23818",
"pm_score": 4,
"selected": false,
"text": "Path.GetRandomFileName()\n"
},
{
"answer_id": 417347,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 3,
"selected": false,
"text": "Any<T>() & All<T>() if( myCollection.Any( x => x.IsSomething ) )\n //...\n\nbool allValid = myCollection.All( \n x => x.IsValid );\n ToList<T>(), ToArray<T>(), ToDictionary<T>() var newDict = myCollection.ToDictionary(\n x => x.Name,\n x => x.Value );\n First<T>(), FirstOrDefault<T>() return dbAccessor.GetFromTable( id ).\n FirstOrDefault();\n Where<T>() //instead of\nforeach( Type item in myCollection )\n if( item.IsValid )\n //do stuff\n\n//you can also do\nforeach( var item in myCollection.Where( x => x.IsValid ) )\n //do stuff\n\n//note only a simple sample - the logic could be a lot more complex\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6624/"
] |
178,530
|
<p>In our web-app we use PHP5.2.6 + PDO to connect to a SQL Server 2005 database and store Russian texts.</p>
<p>Database collation is <code>Cyrillic_General_CI_AS</code>, table collation is <code>Cyrillic_General_CI_AS</code>, column type is <code>NVARCHAR(MAX)</code>.</p>
<p>We tried connecting to a database using two following schemes, both causing different problems.</p>
<ol>
<li><p><em>PDO mssql:</em></p>
<pre><code>$dbh = new PDO ('mssql:host='.$mssql_server.';dbname='.$mssql_db, $mssql_login, $mssql_pwd);
</code></pre>
<p>in which case a result of a simple query like that:</p>
<pre><code>SELECT field1 FROM tbl1 WHERE id=1
</code></pre>
<p>shows <code>field1</code> data truncated to 255 bytes.</p></li>
<li><p><em>PDO odbc:</em> </p>
<pre><code>$dbh = new PDO ('odbc:DSN=myDSN;UID='.$mssql_login.';PWD='.$mssql_pwd);
</code></pre>
<p>in which case a result of the same query shows full not truncated data but with question marks instead of Russian symbols. </p></li>
</ol>
<hr>
<p>Notes:</p>
<ul>
<li>In the SQL Management Studio data is not truncated and Russian symbols are displayed properly as well.</li>
<li>We have Windows 2003 Enterprise Edition SP2</li>
</ul>
<p>So what should we choose as a connection method and how to fix corresponding issues?</p>
|
[
{
"answer_id": 197395,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "SET NAMES \"charset\" Cyrillic_General_CI_AS"
},
{
"answer_id": 2344628,
"author": "Liam Morland",
"author_id": 282357,
"author_profile": "https://Stackoverflow.com/users/282357",
"pm_score": 1,
"selected": false,
"text": "$_ = iconv('Windows-1252', 'UTF-8', $_);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6647/"
] |
178,532
|
<p>I have a rather large and complex set of programs to port from VC8 to VC9. One of the modules has a number of layered typedefs, which cause the compiler to generate a C4503 warning (decorated name truncated). The generated LIB file will not properly link to other modules in the project. VC8 had no trouble with this, leading me to conclude that either the decoration process has changed to generate even longer names, or the internal limit for the length of a decorated name has decreased. What's the best way to get over this?</p>
<p>For legacy code reasons, the MSDN suggestion of replacing typedefs with structs is not practical.</p>
<p>The typedefs in question are (sanitized code): </p>
<pre><code>enum Type{
TYPE_COUNT,
TYPE_VALUE
};
typedef MyVector< Container*, CriticalSectionLock > Containers;
typedef MyVector< MyClassType*, CriticalSectionLock >::const_iterator const_iterator_type;
typedef MyVector< stl::pair< string, Type > >::const_iterator const_iterator_def;
typedef MyVector< Container** >::const_iterator const_iterator_container;
typedef MyVector< stl::pair < MyBase*, MyVector< stl::pair< Container**, Containers* > > > >::const_iterator const_iterator;
</code></pre>
|
[
{
"answer_id": 218959,
"author": "Howard Lee Harkness",
"author_id": 25823,
"author_profile": "https://Stackoverflow.com/users/25823",
"pm_score": 2,
"selected": false,
"text": "enum Type{\n TYPE_COUNT,\n TYPE_VALUE\n };\n\n struct Containers \n {\n MyVector<Container*, CriticalSectionLock > Element;\n Containers(int num, Container* elem):Element(num, elem){}\n Containers(){}\n };\n typedef MyVector< MyClassType*, CriticalSectionLock >::const_iterator const_iterator_type;\n typedef MyVector< stl::pair< string, Type > >::const_iterator const_iterator_def;\n typedef MyVector< Container** >::const_iterator const_iterator_container;\n typedef MyVector< stl::pair < MyBase*, MyVector< stl::pair< Container**, Containers* > > > >::const_iterator const_iterator;\n"
},
{
"answer_id": 381173,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "#pragma warning(disable:xxx).\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25823/"
] |
178,539
|
<p>How can I round a decimal number (floating point) to the nearest integer? </p>
<p>e.g.</p>
<pre><code>1.2 = 1
1.7 = 2
</code></pre>
|
[
{
"answer_id": 178550,
"author": "EvdB",
"author_id": 5349,
"author_profile": "https://Stackoverflow.com/users/5349",
"pm_score": 6,
"selected": false,
"text": "use Math::Round;\nmy $rounded = round( $float );\n my $rounded = sprintf \"%.0f\", $float;\n"
},
{
"answer_id": 178551,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 9,
"selected": true,
"text": "perldoc -q round int() 0 sprintf() printf() printf(\"%.3f\", 3.1415926535); # prints 3.142\n POSIX ceil() floor() use POSIX;\n $ceil = ceil(3.5); # 4\n $floor = floor(3.5); # 3\n Math::Complex Math::Trig Math::Complex for ($i = 0; $i < 1.01; $i += 0.05) { printf \"%.1f \",$i}\n\n 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7\n 0.8 0.8 0.9 0.9 1.0 1.0\n 2**31"
},
{
"answer_id": 178576,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 3,
"selected": false,
"text": "int() sprintf() printf() printf(\"%.3f\",3.1415926535);\n # prints 3.142\n POSIX ceil() floor() use POSIX;\n$ceil = ceil(3.5); # 4\n$floor = floor(3.5); # 3\n Math::Complex Math::Trig Math::Complex for ($i = 0; $i < 1.01; $i += 0.05)\n{\n printf \"%.1f \",$i\n}\n\n0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0\n"
},
{
"answer_id": 179086,
"author": "Kyle",
"author_id": 2237619,
"author_profile": "https://Stackoverflow.com/users/2237619",
"pm_score": 6,
"selected": false,
"text": "foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {\n printf \"$i -> %.0f\\n\", $i;\n}\n__END__\n0.5 -> 0\n1.5 -> 2\n2.5 -> 2\n3.5 -> 4\n"
},
{
"answer_id": 1272301,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "cat table |\n perl -ne '/\\d+\\s+(\\d+)\\s+(\\S+)/ && print \"\".**int**(log($1)/log(2)).\"\\t$2\\n\";' \n"
},
{
"answer_id": 1274692,
"author": "RET",
"author_id": 14750,
"author_profile": "https://Stackoverflow.com/users/14750",
"pm_score": 7,
"selected": false,
"text": "my $rounded = int($float + 0.5); $float my $rounded = int($float + $float/abs($float*2 || 1));"
},
{
"answer_id": 4503906,
"author": "David Beckman",
"author_id": 127054,
"author_profile": "https://Stackoverflow.com/users/127054",
"pm_score": 1,
"selected": false,
"text": "sprintf() sprintf() floor($value + 0.5) use strict;\n use warnings;\n use POSIX;\n\n my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);\n my $total1 = 0.00;\n my $total2 = 0;\n my $total3 = 0;\n my $total4 = 0.00;\n my $total5 = 0;\n my $value1;\n my $value2;\n my $value3;\n my $value4;\n my $value5;\n\n foreach $value1 (@values)\n {\n $value2 = $value1;\n $value3 = $value1;\n $value4 = $value1;\n $value5 = $value1;\n\n $total1 += $value1;\n\n $total2 += sprintf('%d', $value2 * 100);\n\n $value3 = sprintf('%1.2f', $value3);\n $value3 =~ s/\\.//;\n $total3 += $value3;\n\n $total4 += $value4;\n\n $total5 += floor(($value5 * 100.0) + 0.5);\n }\n\n $total1 *= 100;\n $total4 = floor(($total4 * 100.0) + 0.5);\n\n print '$total1: '.sprintf('%011d', $total1).\"\\n\";\n print '$total2: '.sprintf('%011d', $total2).\"\\n\";\n print '$total3: '.sprintf('%011d', $total3).\"\\n\";\n print '$total4: '.sprintf('%011d', $total4).\"\\n\";\n print '$total5: '.sprintf('%011d', $total5).\"\\n\";\n\n exit(0);\n\n #$total1: 00000044179\n #$total2: 00000044179\n #$total3: 00000044180\n #$total4: 00000044180\n #$total5: 00000044180\n floor($value + 0.5) int($value + 0.5) POSIX"
},
{
"answer_id": 6336201,
"author": "activealexaoki",
"author_id": 796622,
"author_profile": "https://Stackoverflow.com/users/796622",
"pm_score": 2,
"selected": false,
"text": "$x[0] = 1.2;\n$x[1] = 1.7;\n\nforeach (@x){\n print $_.' = '.( ( ($_-int($_))<0.5) ? int($_) : int($_)+1 );\n print \"\\n\";\n}\n"
},
{
"answer_id": 7154435,
"author": "matt",
"author_id": 906753,
"author_profile": "https://Stackoverflow.com/users/906753",
"pm_score": 1,
"selected": false,
"text": "printf - printf %d %f int + 0.5 my $var = -9.1;\nmy $tmpRounded = int( abs($var) + 0.5));\nmy $finalRounded = $var >= 0 ? 0 + $tmpRounded : 0 - $tmpRounded;\n"
},
{
"answer_id": 8064429,
"author": "Akvel",
"author_id": 442050,
"author_profile": "https://Stackoverflow.com/users/442050",
"pm_score": 0,
"selected": false,
"text": "if ($value =~ m/\\d\\..*5$/){\n $format =~ /.*(\\d)f$/;\n if (defined $1){\n my $coef = \"0.\" . \"0\" x $1 . \"05\"; \n $value = $value + $coef; \n }\n}\n\n$value = sprintf( \"$format\", $value );\n"
},
{
"answer_id": 25810334,
"author": "seacoder",
"author_id": 3428701,
"author_profile": "https://Stackoverflow.com/users/3428701",
"pm_score": 2,
"selected": false,
"text": "sub round ()\n{\n my ($x, $pow10) = @_;\n my $a = 10 ** $pow10;\n\n return (int($x / $a + (($x < 0) ? -0.5 : 0.5)) * $a);\n}\n"
},
{
"answer_id": 39668498,
"author": "HoldOffHunger",
"author_id": 2430549,
"author_profile": "https://Stackoverflow.com/users/2430549",
"pm_score": 1,
"selected": false,
"text": "my $rounded = floor($float + 0.1); \n"
},
{
"answer_id": 59225239,
"author": "Jarett Lloyd",
"author_id": 4612801,
"author_profile": "https://Stackoverflow.com/users/4612801",
"pm_score": 0,
"selected": false,
"text": "sub asDollars($) {\n my ($cost) = @_;\n my $rv = 0;\n\n my $negative = 0;\n if ($cost =~ /^-/) {\n $negative = 1;\n $cost =~ s/^-//;\n }\n\n my @cost = split(/\\./, $cost);\n\n # let's get the first 3 digits of $cost[1]\n my ($digit1, $digit2, $digit3) = split(\"\", $cost[1]);\n # now, is $digit3 >= 5?\n # if yes, plus one to $digit2.\n # is $digit2 > 9 now?\n # if yes, $digit2 = 0, $digit1++\n # is $digit1 > 9 now??\n # if yes, $digit1 = 0, $cost[0]++\n if ($digit3 >= 5) {\n $digit3 = 0;\n $digit2++;\n if ($digit2 > 9) {\n $digit2 = 0;\n $digit1++;\n if ($digit1 > 9) {\n $digit1 = 0;\n $cost[0]++;\n }\n }\n }\n $cost[1] = $digit1 . $digit2;\n if ($digit1 ne \"0\" and $cost[1] < 10) { $cost[1] .= \"0\"; }\n\n # and pretty up the left of decimal\n if ($cost[0] > 999) { $cost[0] = commafied($cost[0]); }\n\n $rv = join(\".\", @cost);\n\n if ($negative) { $rv = \"-\" . $rv; }\n\n return $rv;\n}\n\nsub commafied($) {\n #*\n # to insert commas before every 3rd number (from the right)\n # positive or negative numbers\n #*\n my ($num) = @_; # the number to insert commas into!\n\n my $negative = 0;\n if ($num =~ /^-/) {\n $negative = 1;\n $num =~ s/^-//;\n }\n $num =~ s/^(0)*//; # strip LEADING zeros from given number!\n $num =~ s/0/-/g; # convert zeros to dashes because ... computers!\n\n if ($num) {\n my @digits = reverse split(\"\", $num);\n $num = \"\";\n\n for (my $i = 0; $i < @digits; $i += 3) {\n $num .= $digits[$i];\n if ($digits[$i+1]) { $num .= $digits[$i+1]; }\n if ($digits[$i+2]) { $num .= $digits[$i+2]; }\n if ($i < (@digits - 3)) { $num .= \",\"; }\n if ($i >= @digits) { last; }\n }\n\n #$num =~ s/,$//;\n $num = join(\"\", reverse split(\"\", $num));\n $num =~ s/-/0/g;\n }\n\n if ($negative) { $num = \"-\" . $num; }\n\n return $num; # a number with commas added\n #usage: my $prettyNum = commafied(1234567890);\n}\n"
},
{
"answer_id": 67497204,
"author": "A1rPun",
"author_id": 1449624,
"author_profile": "https://Stackoverflow.com/users/1449624",
"pm_score": 0,
"selected": false,
"text": "Math::BigFloat use Math::BigFloat;\n\nprint Math::BigFloat->new(1.2)->bfround(1); ## 1\nprint Math::BigFloat->new(1.7)->bfround(1); ## 2\n use Math::BigFloat;\n\nsub round {\n Math::BigFloat->new(shift)->bfround(1);\n}\n\nprint round(1.2); ## 1\nprint round(1.7); ## 2\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12850/"
] |
178,561
|
<p>I have the following VB.net interface that I need to port to C#. C# does not allow enumerations in interfaces. How can I port this without changing code that uses this interface?</p>
<pre><code>Public Interface MyInterface
Enum MyEnum
Yes = 0
No = 1
Maybe = 2
End Enum
ReadOnly Property Number() As MyEnum
End Interface
</code></pre>
|
[
{
"answer_id": 178573,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": false,
"text": "public enum MyEnum\n{\n Yes = 0,\n No = 1,\n Maybe = 2\n}\n\npublic interface IMyInterface\n{\n MyEnum Number { get; }\n}\n"
},
{
"answer_id": 178677,
"author": "Jeremy Frey",
"author_id": 13412,
"author_profile": "https://Stackoverflow.com/users/13412",
"pm_score": 5,
"selected": true,
"text": "class TestClass3 : TestInterfaces.MyInterface\n{\n\n TestInterfaces.MyInterface.MyEnum TestInterfaces.MyInterface.Number\n {\n get { throw new Exception(\"The method or operation is not implemented.\"); }\n }\n\n}\n class TestClass2 : IMyInterface\n{\n\n MyEnum IMyInterface.Number\n {\n get { throw new Exception(\"The method or operation is not implemented.\"); }\n }\n\n}\n .class public interface abstract auto ansi MyInterface\n .class auto ansi sealed nested public MyEnum\n extends [mscorlib]System.Enum\n .field public static literal valuetype TestInterfaces.MyInterface/MyEnum No = int32(1)\n\n .field public specialname rtspecialname int32 value__\n\n .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Yes = int32(0)\n\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25825/"
] |
178,572
|
<p>A large international company deploys a new web and MOTO (Mail Order and Telephone Order) handling system. Among other things you are tasked to design format for both order and customer identification numbers.</p>
<p>What would be the best format in your opinion? Please list any assumptions and considerations.</p>
<hr>
<p><strong>Accepted Answer</strong></p>
<p>Michael Haren's answer selected due to the most up votes, but please do read other answers and comments as they make Michael's answer more complete.</p>
|
[
{
"answer_id": 178706,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 3,
"selected": false,
"text": "ddmmyyyy-####-####\n ####-####-####-####-####\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22088/"
] |
178,578
|
<p>I'm using Webbrowser control to login to HTTPS site with "untrusted certificate".
but I get popup such standart window "Security Alert" about untrusted certificate:</p>
<p><img src="https://i.stack.imgur.com/U01dp.jpg" alt="Security Alert window"></p>
<p>I have to find this window by title and send it <kbd>Alt</kbd>+<kbd>Y</kbd> to press <em>Yes</em>:</p>
<pre><code>int iHandle = NativeWin32.FindWindow(null, "Security Alert");
NativeWin32.SetForegroundWindow(iHandle);
System.Windows.Forms.SendKeys.Send("Y%");
</code></pre>
<p>but user can see a flickering of this window.</p>
<p>How can I ignore this alert?<br>
Or disable this "untrusted certificate" check in Webbrowser control?</p>
|
[
{
"answer_id": 178595,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 3,
"selected": true,
"text": "public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)\n{\n return true;\n}\n\nServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);\n"
},
{
"answer_id": 35363019,
"author": "VCody",
"author_id": 4298559,
"author_profile": "https://Stackoverflow.com/users/4298559",
"pm_score": 1,
"selected": false,
"text": " private void Browser_Navigating_1(object sender, NavigatingCancelEventArgs e)\n {\n HideScriptErrors(Browser,true);\n\n }\n\n public void HideScriptErrors(WebBrowser wb, bool Hide)\n {\n\n FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField(\"_axIWebBrowser2\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (fiComWebBrowser == null) return;\n object objComWebBrowser = fiComWebBrowser.GetValue(wb);\n\n if (objComWebBrowser == null) return;\n\n objComWebBrowser.GetType().InvokeMember(\n \"Silent\", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });\n\n }\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25826/"
] |
178,580
|
<p>We are trying to bind a Linux machine (debian 4.0) to W2k3 AD. We have configured kerberos properly so that we can get TGTs. And users authenticate properly. However, PAM seems to be the sticky wicket. For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell. The default environment is configured properly and PAM even creates the Homedir properly. As a reference we were loosely following:</p>
<p><a href="https://help.ubuntu.com/community/ActiveDirectoryHowto" rel="nofollow noreferrer">https://help.ubuntu.com/community/ActiveDirectoryHowto</a></p>
|
[
{
"answer_id": 181906,
"author": "Pontus",
"author_id": 23483,
"author_profile": "https://Stackoverflow.com/users/23483",
"pm_score": 1,
"selected": false,
"text": "getent passwd avalidusername\n"
},
{
"answer_id": 296169,
"author": "csexton",
"author_id": 19839,
"author_profile": "https://Stackoverflow.com/users/19839",
"pm_score": 0,
"selected": false,
"text": "$ sudo apt-get update\n$ sudo apt-get install likewise-open\n $ sudo domainjoin-cli join domain.local Administrator\n$ sudo update-rc.d likewise-open defaults\n$ sudo /etc/init.d/likewise-open start\n $ sudo visudo\n %DOMAIN\\\\linux_admin ALL=(ALL) ALL\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
178,600
|
<p>The project is ASP.NET 2.0, I have never been able to reproduce this myself, but I get emails informing me it happens to clients many times a week, often a few times in a row.</p>
<p>Here is the full error:</p>
<p>Exception Details: </p>
<blockquote>
<p>Microsoft.Reporting.WebForms.AspNetSessionExpiredException: ASP.NET session has expired</p>
</blockquote>
<p>Stack Trace: </p>
<blockquote>
<p>[AspNetSessionExpiredException: ASP.NET session has expired]
at Microsoft.Reporting.WebForms.ReportDataOperation..ctor()
at Microsoft.Reporting.WebForms.HttpHandler.GetHandler()
at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Session Objects:75de8e1d65ff40d1ba666d940af5b118: Microsoft.Reporting.WebForms.ReportHierarchy
5210064be1fa4d6abf5dd5e56b262974: Microsoft.Reporting.WebForms.ReportHierarchy</p>
</blockquote>
|
[
{
"answer_id": 178812,
"author": "Jon Adams",
"author_id": 2291,
"author_profile": "https://Stackoverflow.com/users/2291",
"pm_score": 5,
"selected": true,
"text": "protected void Application_Error(object sender, EventArgs e)\n{\n Exception exc = Server.GetLastError().GetBaseException();\n if (exc is Microsoft.Reporting.WebForms.AspNetSessionExpiredException)\n {\n Server.ClearError();\n Response.Redirect(FormsAuthentication.LoginUrl + \"?ReturnUrl=\" + HttpUtility.UrlEncode(Request.Url.PathAndQuery), true);\n }\n}\n"
},
{
"answer_id": 240230,
"author": "DrCamel",
"author_id": 4168,
"author_profile": "https://Stackoverflow.com/users/4168",
"pm_score": 2,
"selected": false,
"text": "<system.web><sessionState mode=\"InProc\" timeout=\"60\" /></system.web>\n"
},
{
"answer_id": 9615607,
"author": "Ron Chong",
"author_id": 1256689,
"author_profile": "https://Stackoverflow.com/users/1256689",
"pm_score": 0,
"selected": false,
"text": "web gardern count=1"
},
{
"answer_id": 12798878,
"author": "Brad Herder",
"author_id": 1731570,
"author_profile": "https://Stackoverflow.com/users/1731570",
"pm_score": 1,
"selected": false,
"text": "<httpCookies httpOnlyCookies=\"false\" requireSSL=\"true\" />\n web.config"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21367/"
] |
178,601
|
<pre><code><div spry:region="ds1" spry:repeatchildren="ds1">
<b spry:if=" '{title}'!='' ">
<!-- this is the first if -->
<a href="#" spry:if=" '{author}'!='' ">{author}
<!-- this is the second if -->
</a>
</b>
</div>
</code></pre>
<p><br><br>
I wonder if there is any method as simple as </p>
<pre><code>if(x==y && i>j)
</code></pre>
<p>in </p>
<pre><code><b>spry</b>
</code></pre>
<p>region.
I can't find any information in spry docs (labs.adobe.com/technologies/spry/)</p>
|
[
{
"answer_id": 2810735,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 1,
"selected": false,
"text": "spry:if && <b spry:if=\"'{title}' != '' && '{author}' != ''\">\n<!-- ... -->\n</b>\n"
},
{
"answer_id": 3352414,
"author": "loali",
"author_id": 404265,
"author_profile": "https://Stackoverflow.com/users/404265",
"pm_score": 1,
"selected": false,
"text": "spry:if=\"myFunc();\"\n function myfunc()\n{\n//do somethings ;\nif(...)\nreturn true;\nelse\nreturn false;\n}\n"
},
{
"answer_id": 17003176,
"author": "Narayan Yerrabachu",
"author_id": 2379046,
"author_profile": "https://Stackoverflow.com/users/2379046",
"pm_score": 0,
"selected": false,
"text": "<div spry:region=\"ds1\" spry:repeatchildren=\"ds1\">\n <b spry:if=\" '{ds1::title}'!='' && '{ds1::author}'!=''\">\n <a href=\"#\">{author}</a>\n </b>\n</div>\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24439/"
] |
178,611
|
<p>When Instantiating a class, Windsor by default treats all public properties of the class as optional dependencies and tries to satisfy them. In my case, this creates a rather complicated circular dependency which causes my application to hang. </p>
<p>How can I explicitly tell Castle Windsor that it should not be trying to satisfy a public property? I assume there must be an attribute to that extent. I can't find it however so please let me know the appropriate namespace/assembly.</p>
<p>If there is any way to do this without attributes (such as Xml Configuration or configuration via code) that would be preferable since the specific library where this is happening has to date not needed a dependency on castle.</p>
|
[
{
"answer_id": 182002,
"author": "Bittercoder",
"author_id": 4843,
"author_profile": "https://Stackoverflow.com/users/4843",
"pm_score": 4,
"selected": false,
"text": "kernel.GetHandler(typeof(MyComponent)).ComponentModel.Dependencies.RemoveAll(d => d.DependencyKey == \"PropertyThatShouldNotBeWired\");\n"
},
{
"answer_id": 18831845,
"author": "Jean-Francois",
"author_id": 41174,
"author_profile": "https://Stackoverflow.com/users/41174",
"pm_score": 2,
"selected": false,
"text": "container.Register(Component.For(type)\n .LifestyleTransient()\n .Properties( propertyInfo => propertyInfo.PropertyType != typeof(MyOtherType)));\n"
},
{
"answer_id": 53417833,
"author": "breeze393",
"author_id": 3608534,
"author_profile": "https://Stackoverflow.com/users/3608534",
"pm_score": 2,
"selected": false,
"text": "Component.For<Role>().LifestyleTransient().PropertiesIgnore((model, propertyInfo) => true)\n"
},
{
"answer_id": 54653665,
"author": "gleng",
"author_id": 1483894,
"author_profile": "https://Stackoverflow.com/users/1483894",
"pm_score": 1,
"selected": false,
"text": "var container = new WindsorContainer();\n\n// We don't want to inject properties, only ctors\nvar propInjector = container.Kernel.ComponentModelBuilder\n .Contributors\n .OfType<PropertiesDependenciesModelInspector>()\n .Single();\ncontainer.Kernel.ComponentModelBuilder.RemoveContributor(propInjector);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
178,645
|
<p>There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor?</p>
<p>For example, consider this data contract:</p>
<pre><code>[DataContract]
public sealed class CreateMe
{
[DataMember] private readonly string _name;
[DataMember] private readonly int _age;
private readonly bool _wasConstructorCalled;
public CreateMe()
{
_wasConstructorCalled = true;
}
// ... other members here
}
</code></pre>
<p>When obtaining an instance of this object via <code>DataContractSerializer</code> you will see that the field <code>_wasConstructorCalled</code> is <code>false</code>.</p>
<p>So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us?</p>
|
[
{
"answer_id": 179486,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 8,
"selected": true,
"text": "FormatterServices.GetUninitializedObject() using System;\nusing System.Reflection;\nusing System.Runtime.Serialization;\n\nnamespace NoConstructorThingy\n{\n class Program\n {\n static void Main()\n {\n // does not call ctor\n var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));\n\n Console.WriteLine(myClass.One); // writes \"0\", constructor not called\n Console.WriteLine(myClass.Two); // writes \"0\", field initializer not called\n }\n }\n\n public class MyClass\n {\n public MyClass()\n {\n Console.WriteLine(\"MyClass ctor called.\");\n One = 1;\n }\n\n public int One { get; private set; }\n public readonly int Two = 2;\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24874/"
] |
178,667
|
<p>I have the following code:</p>
<pre><code>import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
public class ScratchPad {
public static void main(String args[]) throws Exception {
String html ="<html>"+
"<head>"+
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>"+ // this is the problem right here
"<title>Error 400 BAD_REQUEST</title>"+
"</head>"+
"<body>"+
"<h2>HTTP ERROR: 400</h2><pre>BAD_REQUEST</pre>"+
"<p>RequestURI=null</p>"+
"<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by jetty://</a></small></i></p>"+
"</body>"+
"</html>";
JFrame f = new JFrame();
JEditorPane editor = new JEditorPane();
editor.setEditable( false );
editor.getDocument().putProperty( "Ignore-Charset", "true" ); // this line makes no difference either way
editor.setContentType( "text/html" );
editor.setText( html );
f.add( new JScrollPane(editor, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) );
f.pack();
f.setVisible( true );
}
}
</code></pre>
<p>If you run it, you'll notice the frame is blank. However, if I remove the "; charset=ISO-8859-1" from the meta tag, the HTML shows up. Any ideas why and what I can do to prevent this (other than manually hacking the HTML string over which I have no control...).</p>
<p><strong>Edit #1</strong> - putProperty( "Ignore-Charset", "true" ) makes no difference unfortunately.</p>
|
[
{
"answer_id": 1421097,
"author": "Horcrux7",
"author_id": 12631,
"author_profile": "https://Stackoverflow.com/users/12631",
"pm_score": 5,
"selected": true,
"text": "editor.getDocument().putProperty(\"IgnoreCharsetDirective\", Boolean.TRUE);\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
178,669
|
<p>How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how?</p>
|
[
{
"answer_id": 178709,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": -1,
"selected": false,
"text": " fscommand( \"fullscreen\" , \"true\" ) \n"
},
{
"answer_id": 178892,
"author": "Raleigh Buckner",
"author_id": 1153,
"author_profile": "https://Stackoverflow.com/users/1153",
"pm_score": 5,
"selected": true,
"text": "<param name=\"allowFullScreen\" value=\"true\" />\n allowFullScreen=\"true\"\n stage.displayState = StageDisplayState.FULL_SCREEN; //Flash\nsystemManager.stage.displayState = StageDisplayState.FULL_SCREEN; // Flex\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20601/"
] |
178,675
|
<p>Is it possible to split large ASP.NET-pages into pieces? JSP has the <a href="http://java.sun.com/products/jsp/tags/11/syntaxref1112.html" rel="nofollow noreferrer">jsp:include</a> directive. Is there any equivivalent in ASP.NET</p>
<p>I'm not interested in reusing the pieces. I just want to organize the HTML/ASP code.</p>
<p>Isn't User Controls and Master Pages overkill for doing this?</p>
|
[
{
"answer_id": 178779,
"author": "liggett78",
"author_id": 19762,
"author_profile": "https://Stackoverflow.com/users/19762",
"pm_score": 3,
"selected": true,
"text": "<!--#include file=\"inc_footer.aspx\"-->\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25833/"
] |
178,696
|
<p>I've got the following JavaScript on my web page...</p>
<pre><code>64 var description = new Array();
65 description[0] = "..."
66 description[1] = "..."
...
78 function init() {
79 document.getElementById('somedivid').innerHTML = description[0];
80 }
81
82 window.onload = init();
</code></pre>
<p>In Microsoft Internet Explorer it causes the following error...</p>
<blockquote>
<p>A Runtime Error has occurred.<br>
Do you wish to debug?</p>
<p>Line: 81<br>
Error: Not implemented</p>
</blockquote>
<p><img src="https://i.stack.imgur.com/n06sz.gif" alt="javascript runtime error"></p>
<p>Line 79 executes as expected.</p>
<p>If line 79 is commented out, it still throws the error.</p>
<p>If I comment out line 82, then the function does not execute and there is no error.</p>
|
[
{
"answer_id": 178719,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<body onload=\"init()\"> window.onload = init(); init() window.onload = init; window.onload"
},
{
"answer_id": 178727,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 5,
"selected": true,
"text": "window.onload = init;\n"
},
{
"answer_id": 178765,
"author": "Jacob",
"author_id": 8119,
"author_profile": "https://Stackoverflow.com/users/8119",
"pm_score": 2,
"selected": false,
"text": "var prevload = window.onload;\nwindow.onload = function(){\n prevload();\n init();\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
178,700
|
<p>While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead. </p>
<p>For an example, see <a href="http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.2.0.GA/userguide_en/html_single/index.html#api.listener" rel="noreferrer">JBossCache 2.2</a>. The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).</p>
<p>Here's a sample from the JBossCache docs:</p>
<pre><code>@CacheListener
public class MyListener {
@CacheStarted
@CacheStopped
public void cacheStartStopEvent(Event e) {
switch (e.getType()) {
case Event.Type.CACHE_STARTED:
System.out.println("Cache has started");
break;
case Event.Type.CACHE_STOPPED:
System.out.println("Cache has stopped");
break;
}
}
@NodeCreated
@NodeRemoved
@NodeVisited
@NodeModified
@NodeMoved
public void logNodeEvent(NodeEvent ne) {
log("An event on node " + ne.getFqn() + " has occured");
}
</code></pre>
<p>}</p>
<p>The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.</p>
<p>So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?</p>
|
[
{
"answer_id": 179056,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 2,
"selected": false,
"text": "if (event instanceof NodeCreatedEvent) adapter"
},
{
"answer_id": 179156,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 2,
"selected": false,
"text": "package a.b.c;\n\npublic interface SomeListener {\n void fee();\n void fie();\n void fo();\n void fum();\n}\n package x.y.z;\n\nimport a.b.c.SomeListener;\nimport com.javadude.annotation.Bean;\nimport com.javadude.annotation.NullObject;\n\n@Bean(nullObjectImplementations = {@NullObject(type = SomeListener.class) })\npublic class Foo extends FooGen implements SomeListener {\n @Override\n public void fie() {\n // whatever code you need here\n }\n}\n package a.b.c;\n\nimport com.javadude.annotation.Bean;\nimport com.javadude.annotation.Observer;\n\n@Bean(observers = {@Observer(type = SomeListener.class)})\npublic class Source extends SourceGen {\n // SourceGen will have add/remove listener and fire methods\n // for each method in SomeListener\n}\n"
},
{
"answer_id": 857223,
"author": "Jim Hurne",
"author_id": 106189,
"author_profile": "https://Stackoverflow.com/users/106189",
"pm_score": 1,
"selected": false,
"text": "public class ExampleProducer {\n\n private EventSupport<ActionEvent> eventSupport;\n\n public ExampleProducer() {\n eventSupport = new EventSupport<ActionEvent>(this);\n }\n\n @AddListenersFor(ActionEvent.class)\n public void addActionListener(Object listener)\n {\n eventSupport.addListener(listener);\n }\n\n @RemoveListenersFor(ActionEvent.class)\n public void removeActionListener(Object listener)\n {\n eventSupport.removeListener(listener);\n }\n\n public void buttonClicked() {\n eventSupport.fire(new ActionEvent(this, \n ActionEvent.ACTION_PERFORMED, \"Click\"));\n }\n }\n EventSupport EventSupport public class ExampleListener\n{ \n private ExampleProducer submitButton;\n\n public ExampleListener()\n {\n submitButton = new ExampleProducer();\n EventSupport.autoRegisterEvents(this);\n }\n\n @HandlesEventFor(\"submitButton\")\n public void handleSubmitButtonClick(ActionEvent event)\n {\n //...some code to handle the event here\n }\n}\n EventSupport @HandlesEventFor ExampleListener ExampleProducer"
},
{
"answer_id": 1980181,
"author": "Hendy Irawan",
"author_id": 122441,
"author_profile": "https://Stackoverflow.com/users/122441",
"pm_score": 4,
"selected": true,
"text": "public StatusBar extends JLabel {\n public StatusBar() {\n AnnotationProcessor.process(this);\n }\n @EventSubscriber(eventClass=StatusEvent.class)\n public void updateStatus(StatusEvent statusEvent) {\n this.setText(statusEvent.getStatusText();\n }\n}\n"
},
{
"answer_id": 2039003,
"author": "eric",
"author_id": 222289,
"author_profile": "https://Stackoverflow.com/users/222289",
"pm_score": 2,
"selected": false,
"text": "@actionPerformed\nprivate void onClick() {\n //do something\n}\n\nprotected void initComponents() {\n JButton button = new JButton(\"Click me!!!\");\n button.addActionListener(new ActionListener(this) );\n}\n"
},
{
"answer_id": 2759614,
"author": "Nitramz",
"author_id": 319643,
"author_profile": "https://Stackoverflow.com/users/319643",
"pm_score": 1,
"selected": false,
"text": "public class SomeController {\n\nprivate Calculator c1 = new Calculator();\nprivate Calculator c2 = new Calculator();\n\npublic SomeController() {\n c1.registerReceiver(this);\n c2.registerReceiver(this);\n c1.add(10, 10);\n c2.add(20, 20);\n}\n\n@EventReceiver(handleFor=\"c1\")\npublic void onResultC1(Calculator.Event e) {\n System.out.println(\"Calculator 1 got: \" + e.result);\n}\n\n@EventReceiver(handleFor=\"c2\")\npublic void onResultC2(Calculator.Event e) {\n System.out.println(\"Calculator 2 got: \" + e.result);\n}\n\n@EventReceiver\npublic void onResultAll(Calculator.Event e) {\n System.out.println(\"Calculator got: \" + e.result);\n}\n}\n\npublic class Calculator {\n\nprivate EventHelper eventHelper = new EventHelper(this);\n\npublic class Event {\n\n long result;\n\n public Event(long result) {\n this.result = result;\n }\n}\n\npublic class AddEvent extends Event {\n\n public AddEvent(long result) {\n super(result);\n }\n}\n\npublic class SubEvent extends Event {\n\n public SubEvent(long result) {\n super(result);\n }\n}\n\npublic void unregisterReceiver(Object o) {\n eventHelper.unregisterReceiver(o);\n}\n\npublic void registerReceiver(Object o) {\n eventHelper.registerReceiver(o);\n}\n\npublic void add(long a, long b) {\n eventHelper.fireEvent(new AddEvent(a + b));\n}\n\npublic void sub(long a, long b) {\n eventHelper.fireEvent(new SubEvent(a - b));\n}\n\npublic void pass(long a) {\n eventHelper.fireEvent(new Event(a));\n}\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21234/"
] |
178,712
|
<p>I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. </p>
<p>I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?</p>
|
[
{
"answer_id": 178755,
"author": "Phillip Wells",
"author_id": 3012,
"author_profile": "https://Stackoverflow.com/users/3012",
"pm_score": 5,
"selected": false,
"text": "DataSet.Tables(0).Columns.Contains(name) DataTable"
},
{
"answer_id": 178766,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 8,
"selected": true,
"text": " If DataRow.Table.Columns.Contains(\"column\") Then\n MsgBox(\"YAY\")\n End If\n"
},
{
"answer_id": 34077498,
"author": "Alexander Abakumov",
"author_id": 3345644,
"author_profile": "https://Stackoverflow.com/users/3345644",
"pm_score": 2,
"selected": false,
"text": "Nothing Columns If dataRow.Table.Columns(\"ColumnName\") IsNot Nothing Then\n MsgBox(\"YAY\")\nEnd If\n Contains(\"ColumnName\") DataColumn Dim column = DataRow.Table.Columns(\"ColumnName\")\nIf column IsNot Nothing Then\n Dim type = column.DataType\nEnd If\n Contains(\"ColumnName\")"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178712",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21186/"
] |
178,730
|
<p>I have to lock user accounts in Active Directory programmatically in C#. </p>
<p>Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account).</p>
<p>Now I tried to lock the account by providing incorrect credentials (see below), but this doesn't work either.</p>
<pre><code>int retries = 0;
while (!adsUser.IsAccountLocked && retries < MAX_LOCK_RETRIES)
{
retries++;
try
{
new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache();
}
catch (Exception)
{
/* ... */
}
adsUser.GetInfo();
}
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 6389998,
"author": "Robert Seitz",
"author_id": 803729,
"author_profile": "https://Stackoverflow.com/users/803729",
"pm_score": 0,
"selected": false,
"text": "DirectoryEntry de = result.GetDirectoryEntry();\nint val = (int)de.Properties[\"userAccountControl\"].Value;\nde.Properties[\"userAccountControl\"].Value = val | 0x0002;\n"
},
{
"answer_id": 7930946,
"author": "user489041",
"author_id": 489041,
"author_profile": "https://Stackoverflow.com/users/489041",
"pm_score": 2,
"selected": false,
"text": "/// <summary>\n/// Locks a user account\n/// </summary>\n/// <param name=\"userName\">The name of the user whose account you want to unlock</param>\n/// <remarks>\n/// This actually trys to log the user in with a wrong password. \n/// This in turn will lock the user out\n/// </remarks>\npublic void LockAccount(string userName)\n{\n DirectoryEntry user = GetUser(userName);\n string path = user.Path;\n string badPassword = \"SomeBadPassword\";\n int maxLoginAttempts = 10;\n\n for (int i = 0; i < maxLoginAttempts; i++)\n {\n try\n {\n new DirectoryEntry(path, userName, badPassword).RefreshCache();\n }\n catch (Exception e)\n {\n\n }\n }\n user.Close();\n}\n"
},
{
"answer_id": 28565650,
"author": "obsoleter",
"author_id": 982237,
"author_profile": "https://Stackoverflow.com/users/982237",
"pm_score": 1,
"selected": false,
"text": "LogonUser using System;\nusing System.Runtime.InteropServices;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n IntPtr token = IntPtr.Zero;\n string userPrincipalName = \"userID@domain.com\";\n string authority = null; // Can be null when using UPN (user principal name)\n string badPassword = \"bad\";\n\n int maxTries = 100;\n bool res = false;\n\n for (var i = 0; i < maxTries; i++)\n {\n res = LogonUser(userPrincipalName, authority, badPassword, LogonSessionType.Interactive, LogonProvider.Default, out token);\n CloseHandle(token);\n }\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool LogonUser(\n string principal,\n string authority,\n string password,\n LogonSessionType logonType,\n LogonProvider logonProvider,\n out IntPtr token);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool CloseHandle(IntPtr handle);\n enum LogonSessionType : uint\n {\n Interactive = 2,\n Network,\n Batch,\n Service,\n NetworkCleartext = 8,\n NewCredentials\n }\n\n enum LogonProvider : uint\n {\n Default = 0, // default for platform (use this!)\n WinNT35, // sends smoke signals to authority\n WinNT40, // uses NTLM\n WinNT50 // negotiates Kerb or NTLM\n }\n }\n}\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/830/"
] |
178,738
|
<p>Is there a way to catch a click on a cell in VBA with Excel? I am not referring to the <code>Worksheet_SelectionChange</code> event, as that will not trigger multiple times if the cell is clicked multiple times. <code>BeforeDoubleClick</code> does not solve my problem either, as I do not want to require the user to double click that frequently.</p>
<p>My current solution does work with the <code>SelectionChange</code> event, but it appears to require the use of global variables and other suboptimal coding practices. It also seems prone to error.</p>
|
[
{
"answer_id": 180695,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n 'put your code here to process the selection, then..\n ActiveWindow.VisibleRange.Cells(1, 1).Select\nEnd Sub\n"
},
{
"answer_id": 181698,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 6,
"selected": true,
"text": "Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n 'prevent Select event triggering again when we extend the selection below\n Application.EnableEvents = False\n Target.Resize(1, 2).Select\n Application.EnableEvents = True\nEnd Sub\n"
},
{
"answer_id": 199095,
"author": "Joe",
"author_id": 26883,
"author_profile": "https://Stackoverflow.com/users/26883",
"pm_score": 0,
"selected": false,
"text": "Private Sub Worksheet_Change(ByVal Target As Range)\n\n If Mid(Target.Address, 3, 1) = \"$\" And Mid(Target.Address, 2, 1) < \"E\" Then\n ' The logic in the if condition will filter for a specific cell or block of cells\n Application.ScreenUpdating = False\n 'MsgBox \"You just changed \" & Target.Address\n\n 'all conditions are true .... DO THE FUNCTION NEEDED \n Application.ScreenUpdating = True\n End If\n ' if clicked cell is not in the range then do nothing (if condttion is not run) \nEnd Sub\n block1 = row > 3 and row < 5 and column column >\"b\" and < \"d\" \nblock2 = row > 7 and row < 12 and column column >\"b\" and < \"d\" \nblock3 = row > 10 and row < 15 and column column >\"e\" and < \"g\"\n\nIf block1 or block2 or block 3 then\n do function .....\nend if \n"
},
{
"answer_id": 50528978,
"author": "Dumitru Daniel",
"author_id": 7251685,
"author_profile": "https://Stackoverflow.com/users/7251685",
"pm_score": 0,
"selected": false,
"text": "Public macroIsOnQueue As Boolean\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n macroIsOnQueue = False\n Application.OnTime (Now() + TimeValue(\"00:00:02\")), \"addBordersOnRow\"\n macroIsOnQueue = True\nEnd sub\nSub addBordersOnRow()\n If macroIsOnQueue Then \n macroIsOnQueue = False\n ' add code here\n End if\nEnd sub\n"
},
{
"answer_id": 61377786,
"author": "Super Symmetry",
"author_id": 13386420,
"author_profile": "https://Stackoverflow.com/users/13386420",
"pm_score": 0,
"selected": false,
"text": "ZZ1 Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n Application.EnableEvents = False\n Union(Target, Me.Range(\"ZZ1\")).Select\n Application.EnableEvents = True\n\n ' Respond to click/selection-change here\n\nEnd Sub\n"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12002/"
] |
178,740
|
<p>Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.</p>
<p>Detais are following:</p>
<pre><code>//exception overloads:
public FilterXmlParseException(string message, Exception innerException)
: base(message, innerException) { }
public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...}
//Usage:
XmlReader reader = ...
IXmlLineInfo lineinfo = (IXmlLineInfo)reader;
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
//ok
throw new FilterXmlParseException("<Filter> element expected", lineinfo);
</code></pre>
<p>And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception</p>
|
[
{
"answer_id": 178764,
"author": "Grzenio",
"author_id": 5363,
"author_profile": "https://Stackoverflow.com/users/5363",
"pm_score": 2,
"selected": true,
"text": "//fails\nthrow new FilterXmlParseException(\"<Filter> element expected\", reader);\n"
},
{
"answer_id": 178798,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 0,
"selected": false,
"text": "XmlReader reader = XmlTextReader.Create(sreader, readerSettings);\n XmlTextReader XmlReader reader IXmlLineInfo XmlTextReader XmlReader XmlReader IXmlLineInfo XmlTextReader reader = (XmlTextReader)XmlTextReader.Create(sreader, readerSettings);\n Create XmlReader XmlTextReader"
}
] |
2008/10/07
|
[
"https://Stackoverflow.com/questions/178740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21603/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.