qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
295,287 | <p>Is there any way to 'hide' the name of a class, whose sole purpose is to provide extension methods, from Intellisense? </p>
<p>I would like to remove the class name from the Intellisense list but need the extension methods of the class to be available to external assemblies via Intellisense in the usual way.</p>
| [
{
"answer_id": 295311,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 2,
"selected": false,
"text": "[EditorBrowsable(EditorBrowsableState.Never)]\nstatic class MyExtensions { }\n"
},
{
"answer_id": 295427,
"author": "flesh",
"author_id": 27805,
"author_profile": "https://Stackoverflow.com/users/27805",
"pm_score": 3,
"selected": true,
"text": "[EditorBrowsable(EditorBrowsableState.Never)]\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27805/"
] |
295,291 | <p>I'm currently doing the following to use typed datasets in vs2008: </p>
<p>Right click on "app_code" add new dataset, name it tableDS.</p>
<p>Open tableDS, right click, add "table adapter"</p>
<p>In the wizard, choose a pre defined connection string, "use SQL statements"</p>
<p>select * from tablename and next + next to finish. (I generate one table adapter for each table in my DB)</p>
<p>In my code I do the following to get a row of data when I only need one: </p>
<p>cpcDS.tbl_cpcRow tr = (cpcDS.tbl_cpcRow)(new cpcDSTableAdapters.tbl_cpcTableAdapter()).GetData().Select("cpcID = " + cpcID)[0];</p>
<p>I believe this will get the entire table from the database and to the filtering in dotnet (ie not optimal), is there any way I can get the tableadapter to filer the result set on the database instead (IE what I want to is send select * from tbl_cpc where cpcID = 1 to the database)</p>
<p>And as a side note, I think this is a fairly ok design pattern for getting data from a database in vs2008. It's fairly easy to code with, read and mantain. But I would like to know it there are any other design patterns that is better out there? I use the datasets for read/update/insert and delete. </p>
| [
{
"answer_id": 295324,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": true,
"text": "int id = ... // the primary key we want to look for\nusing(var ctx = new MydataContext()) {\n SomeType record = ctx.SomeTable.Single(x => x.SomeColumn == id);\n //... etc\n\n // ctx.SubmitChanges(); // to commit any updates\n}\n var myOrders = from row in ctx.Orders\n where row.CustomerID = id && row.IsActive\n orderby row.OrderDate\n select row;\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37083/"
] |
295,314 | <p>When I launch an ant script from Eclipse 3.4.x it prints the output to console until certain stage. After that it often hangs (wait forever). Last lines that I see at the screen (console) - partial output from my obfuscator.</p>
<p>Under Eclipse 3.3.2 everything works fine (the same project, workspace, settings, JVM etc.).</p>
<p>Does anybody have the same issue? Any thoughts how to fix it?</p>
| [
{
"answer_id": 295352,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "-diagnostics"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19347/"
] |
295,315 | <p>I have this java code:</p>
<pre><code><script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.2.6");
$("a#more").click(function() {
$("#info_box").show("blind", { direction: "vertical" }, 800);
});
</script>
</code></pre>
<p>And this link:</p>
<pre><code><a href="#" id="more">More Info...</a>
</code></pre>
<p>info_box is just a div with the properties:</p>
<pre><code>width: 30%;
position: absolute;
left: 35%;
top: 250px;
background-color: #FFFFFF;
border: 2px solid #000000;
visibility: hidden;
</code></pre>
<p>How can this not be working, been trying to figure it out for 20 minutes.</p>
| [
{
"answer_id": 295331,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 1,
"selected": false,
"text": "\"blind\" { direction: \"vertical\" }"
},
{
"answer_id": 295351,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 3,
"selected": true,
"text": "ready() display: none <html>\n<head>\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n$(document).ready(\n function()\n {\n $(\"a#more\").click(function() {\n $(\"#info_box\").show(\"blind\");\n });\n});\n</script>\n<style>\n #info_box {\n width: 30%;\n position: absolute;\n left: 35%;\n top: 250px;\n background-color: #FFFFFF;\n border: 2px solid #000000;\n display: none;}\n</style>\n</head>\n<body>\n\n<a href=\"#\" id=\"more\">More Info...</a>\n\n<div id=\"info_box\">Secret info goes here</div>\n\n\n</body>\n</html>\n params"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
295,321 | <p>When using gdb and Vim, often I want to stop on a particular line. Normally in Vim I copy-paste the line number showing on the rule area to the gdb session. It'd save me a lot of hassle if I could use something like <code>"+<magic-incantation></code> to copy the line number of the current cursor position into the xclipboard buffer. Is this possible?</p>
| [
{
"answer_id": 295356,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 5,
"selected": true,
"text": "map ,n <Esc>:let @*=line(\".\")<CR>\n"
},
{
"answer_id": 295366,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 3,
"selected": false,
"text": " :call setreg('*', line('.'))\n line('.') nmap ,ln :call setreg('*', line('.'))<CR>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4596/"
] |
295,333 | <p>If you put up an <code>NSAlert</code> while your app is in the background your dock icon starts bouncing and keeps on bouncing until you switch back. </p>
<p>I find this annoying. </p>
<p>Does anyone know how disable that for a single app? </p>
| [
{
"answer_id": 295372,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "- (void)cancelUserAttentionRequest:(int)request\n"
},
{
"answer_id": 295453,
"author": "Dirk Stoop",
"author_id": 24051,
"author_profile": "https://Stackoverflow.com/users/24051",
"pm_score": 4,
"selected": true,
"text": "- (int)requestUserAttention:(NSRequestUserAttentionType)requestType\n {\n if (dontDoThatBouncyThing) {\n return 0;\n }\n return [super requestUserAttention:requestType];\n }\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22147/"
] |
295,336 | <p>I'm still working on groking the F# thing - trying to work out how to 'think' in F# rather than just translating from other languages I know.</p>
<p>I've recently been thinking about the cases where you don't have a 1:1 map between before and after. Cases where List.map falls down.</p>
<p>One example of this is moving averages, where typically you will have len-n+1 results for a list of length len when averaging over n items.</p>
<p>For the gurus out there, is this a good way to do it (using queue pinched from <a href="http://blogs.msdn.com/jomo_fisher/archive/2007/12/12/strange-confluence-an-immutable-queue-in-f.aspx" rel="noreferrer">Jomo Fisher</a>)?</p>
<pre><code>//Immutable queue, with added Length member
type Fifo<'a> =
new()={xs=[];rxs=[]}
new(xs,rxs)={xs=xs;rxs=rxs}
val xs: 'a list;
val rxs: 'a list;
static member Empty() = new Fifo<'a>()
member q.IsEmpty = (q.xs = []) && (q.rxs = [])
member q.Enqueue(x) = Fifo(q.xs,x::q.rxs)
member q.Length() = (List.length q.xs) + (List.length q.rxs)
member q.Take() =
if q.IsEmpty then failwith "fifo.Take: empty queue"
else match q.xs with
| [] -> (Fifo(List.rev q.rxs,[])).Take()
| y::ys -> (Fifo(ys, q.rxs)),y
//List module, add function to split one list into two parts (not safe if n > lst length)
module List =
let splitat n lst =
let rec loop acc n lst =
if List.length acc = n then
(List.rev acc, lst)
else
loop (List.hd lst :: acc) n (List.tl lst)
loop [] n lst
//Return list with moving average accross len elements of lst
let MovingAverage (len:int) (lst:float list) =
//ugly mean - including this in Fifo kills genericity
let qMean (q:Fifo<float>) = ((List.sum q.xs) + (List.sum q.rxs))/(float (q.Length()))
//get first part of list to initialise queue
let (init, rest) = List.splitat len lst
//initialise queue with first n items
let q = new Fifo<float>([], init)
//loop through input list, use fifo to push/pull values as they come
let rec loop (acc:float list) ls (q:Fifo<float>) =
match ls with
| [] -> List.rev acc
| h::t ->
let nq = q.Enqueue(h) //enqueue new value
let (nq, _) = nq.Take() //drop old value
loop ((qMean nq)::acc) t nq //tail recursion
loop [qMean q] rest q
//Example usage
MovingAverage 3 [1.;1.;1.;1.;1.;2.;2.;2.;2.;2.]
</code></pre>
<p>(Maybe a better way would be to implement a MovingAverageQueue by inheriting from Fifo?)</p>
| [
{
"answer_id": 295537,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": -1,
"selected": false,
"text": "let -- the limited average of a list\nlimitedaverage 0 _ = 0\nlimited verage n (x:xs) = (x/n) + ( limited average (n-1) xs )\n\n-- a list, transformed into a sequence of moving averages of \nmovingaverages n [] = []\nmovingaverages n (x:xs) = ( movingaverage n (x:xs) : movingaverages n xs )\n"
},
{
"answer_id": 295604,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 1,
"selected": false,
"text": "let LimitedAverage n ls = \n let rec loop acc i n ls = \n match i with\n | 0 -> acc //i counts down from n to 0, when we hit 0 we stop\n | _ -> match ls with\n | [] -> acc //if we hit empty list before end of n, we stop too\n | x::xs -> (loop (acc + (x / float n)) (i - 1) n xs) //divide this value by n, perform average on 'rest' of list\n loop 0. n n ls\n\nLimitedAverage 50000 (List.map float [1..9999999])\n//>val it : float = 25000.5\n\nlet rec MovingAverage3 n ls = \n let rec acc loop i n ls = \n match i with \n | 0 -> List.rev acc //i counts down from n to 0, when we hit 0 we stop\n | _ -> match ls with\n | [] -> List.rev acc //if we hit empty list before end of n, we stop too\n | x::xs -> loop (LimitedAverage2 n ls :: acc) (i - 1) n xs // limited average on whole list, then moving average on tail\n loop [] (n + 1) n ls \n\nMovingAverage3 50000 (List.map float [1..9999999])\n//>val it : float list = [25000.5; 25001.5; 25002.5; ...]\n"
},
{
"answer_id": 297775,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 4,
"selected": true,
"text": "#light\n\nlet MovingAverage n s =\n Seq.windowed n s\n |> Seq.map Array.average\n\nlet avgs = MovingAverage 5000 (Seq.map float [|1..999999|])\n\nfor avg in avgs do\n printfn \"%f\" avg\n System.Console.ReadKey() |> ignore\n"
},
{
"answer_id": 508284,
"author": "Juliet",
"author_id": 40516,
"author_profile": "https://Stackoverflow.com/users/40516",
"pm_score": 2,
"selected": false,
"text": "let movingAverage days l =\n seq {\n let queue = new Queue<_>(days : int)\n let divisor = decimal days\n\n let total = ref 0m\n for cur in l do\n queue.Enqueue(cur)\n total := !total + cur\n if queue.Count < days then\n yield (cur, 0m)\n else\n yield (cur, !total / divisor)\n total := !total - (queue.Dequeue())\n }\n #light\nopen System\nopen System.Collections.Generic\nopen System.Diagnostics;\n\nlet windowAverage days (l : #seq<decimal>) = Seq.windowed days l |> Seq.map (Seq.average)\n\nlet princessAverage days l =\n seq {\n let queue = new Queue<_>(days : int)\n let divisor = decimal days\n\n let total = ref 0m\n for cur in l do\n queue.Enqueue(cur)\n total := !total + cur\n if queue.Count < days then\n yield (cur, 0m)\n else\n yield (cur, !total / divisor)\n total := !total - (queue.Dequeue())\n }\n\nlet testData =\n let rnd = new System.Random()\n seq { for a in 1 .. 1000000 -> decimal (rnd.Next(1000)) }\n\nlet benchmark msg f iterations =\n let rec loop = function\n | 0 -> ()\n | n -> f 3 testData |> ignore; loop (n - 1)\n\n let stopWatch = Stopwatch.StartNew()\n loop iterations\n stopWatch.Stop()\n printfn \"%s: %f\" msg stopWatch.Elapsed.TotalMilliseconds\n\nlet _ =\n let iterations = 10000000\n benchmark \"princessAverage\" princessAverage iterations\n benchmark \"windowAverage\" windowAverage iterations\n printfn \"Done\"\n"
},
{
"answer_id": 12211243,
"author": "bradgonesurfing",
"author_id": 158285,
"author_profile": "https://Stackoverflow.com/users/158285",
"pm_score": 2,
"selected": false,
"text": "module MovingAverage = \n let selfZip n l =\n Seq.skip n l |> Seq.zip l \n\n let runTotal i z =\n Seq.scan ( fun sum (s, e) -> sum - s + e ) i z\n\n let average n l:seq<'a> =\n Seq.skip n l\n |> selfZip n\n |> runTotal (l |> Seq.take n |> Seq.sum)\n |> Seq.map ( fun sum -> decimal sum / decimal n ) \n\n let ma = MovingAverage.average 2 myseq\n let myseq = seq { for i in 0..10 do yield i }\n\n Seq.nth 0 ma |> should equal 0.5\n Seq.nth 1 ma |> should equal 1.5\n Seq.nth 2 ma |> should equal 2.5\n Seq.nth 3 ma |> should equal 3.5\n namespace Utils\n\nmodule MovingAverage = \n let selfZip n l =\n Seq.skip n l |> Seq.zip l \n\n let rec zeros = \n seq { yield 0.0; yield! zeros} \n\n // Create a running total given\n let runTotal z =\n Seq.scan (fun sum (s,e) -> sum - s + e ) 0.0 z\n\n let average n l =\n Seq.concat [(Seq.take n zeros); l]\n |> selfZip n\n |> runTotal\n |> Seq.map ( fun sum -> sum / float n ) \n |> Seq.skip n\n"
},
{
"answer_id": 27771041,
"author": "Miro",
"author_id": 4418288,
"author_profile": "https://Stackoverflow.com/users/4418288",
"pm_score": 0,
"selected": false,
"text": "let sma list n =\n let len = List.length list\n let rec loop acc sum cnt =\n if cnt >= len then List.rev acc\n else if cnt < n-1 then loop (0.0::acc) (sum + List.nth list cnt) (cnt+1)\n else loop (((sum + List.nth list cnt)/(float n))::acc) (sum + (List.nth list cnt) - (List.nth list (cnt-n+1))) (cnt+1)\n loop [] 0.0 0\n sma (List.map float [5..50]) 5\n[0, 0, 0, 0, 7, 8, 9, ...]\n"
},
{
"answer_id": 69359811,
"author": "shr",
"author_id": 1094998,
"author_profile": "https://Stackoverflow.com/users/1094998",
"pm_score": 0,
"selected": false,
"text": "let movingAverage (period : int) (values : float seq) =\n Seq.zip values (Seq.skip period values)\n |> Seq.scan (fun last (prev, cur) -> last - prev + cur) (values |> Seq.take period |> Seq.sum)\n |> Seq.map (fun x -> x / float(period))\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
295,337 | <p>i'm currently experimenting using PixelShaders introduced with .net 3.5 sp1 to improve image processing performance. everything is much faster , but til yet i just had effects applied to some elements in my wpf forms, that i actually want to avoid.</p>
<p>we have a bunch of image processing functionality and i'd like to replace some othe the stuff piece by piece with pixel shaders to gain some performance.
is there a way to apply such a pixel shader to an ImageSource without having to display it?</p>
| [
{
"answer_id": 18466797,
"author": "H B",
"author_id": 521443,
"author_profile": "https://Stackoverflow.com/users/521443",
"pm_score": 3,
"selected": true,
"text": "//prepare images\nimg = new Image();\nimg.Stretch = Stretch.None;\nviewbox = new Viewbox();\nviewbox.Stretch = Stretch.None;\nviewbox.Child = img; //control to render\n /// <summary>\n/// Loads the image and viewbox for off-screen rendering.\n/// </summary>\npublic void LoadImage(double width, double height)\n{\n img.BeginInit();\n img.Width = width;\n img.Height = height;\n img.Source = Source;\n img.EndInit();\n\n viewbox.Measure(new Size(img.Width, img.Height));\n viewbox.Arrange(new Rect(0, 0, img.Width, img.Height));\n viewbox.UpdateLayout();\n} \n void SaveUsingEncoder(BitmapEncoder encoder, Stream stream)\n{\n RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(img.Width * DpiX / WPF_DPI_X), (int)(img.Height * DpiY / WPF_DPI_Y), DpiX, DpiY, PixelFormats.Pbgra32);\n bitmap.Render(viewbox);\n\n BitmapFrame frame = BitmapFrame.Create(bitmap);\n encoder.Frames.Add(frame);\n encoder.Save(stream);\n} \n thread.SetApartmentState(ApartmentState.STA);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20227/"
] |
295,345 | <p>I need to encrypt a small block of data (16 bytes) using 512 bit RSA public key -- quite an easy task for most cryptography libraries known to me, except for MS CSP API, as it seems.
Documentation for <a href="http://msdn.microsoft.com/en-us/library/aa379924(VS.85).aspx" rel="nofollow noreferrer">CryptEncrypt</a> function states that</p>
<blockquote>
<p>The Microsoft Enhanced Cryptographic Provider supports direct encryption with RSA public keys and decryption with RSA private keys. The encryption uses PKCS #1 padding.</p>
</blockquote>
<p>It didn't work to me though. Well, my code works and produces encrypted block of data with correct size, but openssl fails to decypher it. It looks much like CryptEncrypt still uses symmetric cypher.</p>
<p>Unfortunately all the examples I've found refer to combined cryptography with symmetric cypher, so I don't have a working example on hands which definitely would make things easier.</p>
<p>Could please anyone point me to such an example or let me know if there are some not that obvious pitfalls I've missed?</p>
<p>Thank you.</p>
| [
{
"answer_id": 18466797,
"author": "H B",
"author_id": 521443,
"author_profile": "https://Stackoverflow.com/users/521443",
"pm_score": 3,
"selected": true,
"text": "//prepare images\nimg = new Image();\nimg.Stretch = Stretch.None;\nviewbox = new Viewbox();\nviewbox.Stretch = Stretch.None;\nviewbox.Child = img; //control to render\n /// <summary>\n/// Loads the image and viewbox for off-screen rendering.\n/// </summary>\npublic void LoadImage(double width, double height)\n{\n img.BeginInit();\n img.Width = width;\n img.Height = height;\n img.Source = Source;\n img.EndInit();\n\n viewbox.Measure(new Size(img.Width, img.Height));\n viewbox.Arrange(new Rect(0, 0, img.Width, img.Height));\n viewbox.UpdateLayout();\n} \n void SaveUsingEncoder(BitmapEncoder encoder, Stream stream)\n{\n RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(img.Width * DpiX / WPF_DPI_X), (int)(img.Height * DpiY / WPF_DPI_Y), DpiX, DpiY, PixelFormats.Pbgra32);\n bitmap.Render(viewbox);\n\n BitmapFrame frame = BitmapFrame.Create(bitmap);\n encoder.Frames.Add(frame);\n encoder.Save(stream);\n} \n thread.SetApartmentState(ApartmentState.STA);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2231145/"
] |
295,348 | <p>I'm looking for a way to <strong>monitor certain Windows services</strong> (on Windows Server 2003) and <strong>restart if necessar</strong>y. The services are on different servers and include mainly SQL Server services (e.g. SQL Server Agent), but also some proprietary services.</p>
<p>Email alerts sent out if a service has stopped would be very useful as well.</p>
| [
{
"answer_id": 295362,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "wmic /node:[hostname] service list\n WMIC SERVICE where caption='TELNET' CALL STARTSERVICE\n"
},
{
"answer_id": 295363,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 7,
"selected": true,
"text": "services.msc"
},
{
"answer_id": 295412,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 4,
"selected": false,
"text": "var srv = new ServiceController(\"MyService\");\nConsole.WriteLine(\"MyService Status {0}\", srv.Status);\nif (srv.Status != ServiceControllerStatus.Running)\n srv.Start();\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16279/"
] |
295,358 | <p>I want to save a set of email addresses collected from a text field (separated by commas) into a single field in a table. I am trying to use serialize but I'm getting SerializationTypeMismatch error. How can I do this?</p>
<p>This is my model:</p>
<p>class Crew < ActiveRecord::Base</p>
<p>class Recipients < HashWithIndifferentAccess ; end</p>
<p>serialize :recipients, Recipients</p>
<p>end</p>
| [
{
"answer_id": 295393,
"author": "Stein G. Strindhaug",
"author_id": 26115,
"author_profile": "https://Stackoverflow.com/users/26115",
"pm_score": 2,
"selected": false,
"text": "has_many :emails"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,383 | <p>When I delete a visual component in a base form, and forget any references in inherited forms, my application only breaks in runtime.</p>
<p>What I normally do is to use a search tool to find references in .DFM, but I'm not completely satisfied with this method.</p>
<p>Do you have any better recommendations?</p>
| [
{
"answer_id": 295431,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "inherited Form1: TForm1\n Caption = 'Form1'\n PixelsPerInch = 96\n TextHeight = 13\nend\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2089/"
] |
295,384 | <p>How can I see which file extensions are related to which kind of syntax highlighting? Unfortunately, <code>Tools -> Options -> Text Editor -> File Extensions</code> lists only those entered manually, no default ones. And I didn't manage to find it on my own via Google or other means. </p>
<p>My particular problem is, I want to have .inc highlighted exactly as .asp but I'm not sure which editor is used for .asp. I did try the following (none worked):</p>
<ul>
<li>Web Form Editor </li>
<li>VBscript Editor </li>
<li>HTML Editor</li>
<li>Script Editor</li>
</ul>
<p>(They did work in a sense that they colored my code in one way or another, but it wasn't the same highlight as I get for <code>.asp</code> files).</p>
| [
{
"answer_id": 295431,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "inherited Form1: TForm1\n Caption = 'Form1'\n PixelsPerInch = 96\n TextHeight = 13\nend\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25413/"
] |
295,386 | <p>How can I create a scheduled task to run a PHP file?<br />
Yes, I filled out everything in the scheduled task, but it still doesn't work.</p>
<blockquote>
<p>Run: "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\WEB\4w_website\save.php"</p>
<p>Start in: "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\WEB\4w_website"</p>
</blockquote>
<p>It just opens the PHP file in Notepad.</p>
<p>I gave the correct user name and pwd.</p>
<p>Please help me..</p>
| [
{
"answer_id": 9122112,
"author": "matobago",
"author_id": 1186446,
"author_profile": "https://Stackoverflow.com/users/1186446",
"pm_score": 4,
"selected": false,
"text": ".bat @ECHO OFF\nphp.exe -f \"C:\\code\\cust.php\"\n C:\\code\\file.bat C:\\code\\"
},
{
"answer_id": 11304858,
"author": "charles",
"author_id": 1312690,
"author_profile": "https://Stackoverflow.com/users/1312690",
"pm_score": 2,
"selected": false,
"text": "<?php my code goes here ?>\n dl(\"php_curl.dll\"); @ECHO OFF\nphp -f d:\\wamp\\www\\V3\\task.php\n"
},
{
"answer_id": 21402469,
"author": "Martin",
"author_id": 2389194,
"author_profile": "https://Stackoverflow.com/users/2389194",
"pm_score": 3,
"selected": false,
"text": "Run: C:\\php\\php.exe \nArguments: -f C:\\web\\myscript.php\n Start in: C:\\web\\\n"
},
{
"answer_id": 32982053,
"author": "Logan Wayne",
"author_id": 3094531,
"author_profile": "https://Stackoverflow.com/users/3094531",
"pm_score": 2,
"selected": false,
"text": " \" \"C:\\Path\\to php file\\php.exe\" -f \"C:\\Path\\to php file\\file.php\"\n file.php include(\"file2.php\"); /* OR */\ninclude_once(\"file2.php\");\n file.php"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38172/"
] |
295,387 | <p>I am writing a windows service. This service runs another process I've developed through Process class methods, but I want to run this process on debug mode also, using breakpoints, for instance.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 295424,
"author": "Ulf Lindback",
"author_id": 30354,
"author_profile": "https://Stackoverflow.com/users/30354",
"pm_score": 3,
"selected": true,
"text": "#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n #if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
295,402 | <p>In our organization, we have the following problem. We want to have our web tree revision-controlled, but many of us want to be able to alter (and check in) any file of that tree. We would also like there to be only a single check-out for all this because the tree is rather huge. For parts of that tree, we are currently using RCS, which allows for the behavior described above, but has several other drawbacks, of course.</p>
<p>Does anyone know how to do such a thing (maybe with some kind of workaround) with Subversion on a Unix server?</p>
| [
{
"answer_id": 295807,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "svn svn commit post-commit cron"
},
{
"answer_id": 296382,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "module1 svn checkout --depth=files svn://server/repository/trunk/src/module1\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,403 | <p>Many times I use 'mqsc' for create MQ queue manager from script files but I don't know how to generate script files.</p>
<p>Thanks</p>
| [
{
"answer_id": 2718735,
"author": "T.Rob",
"author_id": 214668,
"author_profile": "https://Stackoverflow.com/users/214668",
"pm_score": 1,
"selected": false,
"text": "DIS CHL(*) ALL\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
295,415 | <p>I have a .net winforms app which has a few animation effects, fade ins and scroll animations etc. These work fine however if I'm in a Remote Desktop Protocol session the animations start to grate.</p>
<p>Can someone suggest a way of determining whether or not an app is running across an RDP session so I can turn the effects off in this case?</p>
| [
{
"answer_id": 295437,
"author": "George Stocker",
"author_id": 16587,
"author_profile": "https://Stackoverflow.com/users/16587",
"pm_score": 2,
"selected": false,
"text": " BOOL IsRemoteSession(void){\n return GetSystemMetrics( SM_REMOTESESSION );\n }\n [DllImport(\"User32.dll\")]\nstatic extern Boolean IsRemoteSession()\n{\n return GetSystemMetrics ( SM_REMOTESESSION);\n}\n SystemInformation.TerminalServerSession"
},
{
"answer_id": 295478,
"author": "Arnout",
"author_id": 3496,
"author_profile": "https://Stackoverflow.com/users/3496",
"pm_score": 5,
"selected": true,
"text": "System.Windows.Forms.SystemInformation.TerminalServerSession"
},
{
"answer_id": 372157,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Indicates if we're running in a remote desktop session.\n/// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes!\n/// \n/// </summary>\n/// <returns></returns>\npublic static Boolean IsRemoteSession\n{\n //This is just a friendly wrapper around the built-in way\n get \n {\n return System.Windows.Forms.SystemInformation.TerminalServerSession; \n }\n}\n /// <summary>\n/// Indicates if we're running on battery power.\n/// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc\n/// </summary>\npublic static Boolean IsRunningOnBattery\n{\n get\n {\n PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus;\n if (pls == PowerLineStatus.Offline)\n {\n //Offline means running on battery\n return true;\n }\n else\n {\n return false;\n }\n }\n}\n public Boolean UseAnimations()\n{\n return \n (!System.Windows.Forms.SystemInformation.TerminalServerSession) &&\n (System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus != PowerLineStatus.Offline);\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29411/"
] |
295,417 | <p>I need to have a string, based on an integer, which should always have 5 digits.</p>
<p>Example:</p>
<pre><code>myInteger = 999
formatedInteger = "00999"
</code></pre>
<p>What is the best way of doing this in classic ASP?</p>
| [
{
"answer_id": 295440,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "function PadNumber(number, width)\n dim padded : padded = cStr(number)\n\n while (len(padded) < width)\n padded = \"0\" & padded\n wend\n\n PadNumber = padded\nend function\n\nPadNumber(999, 5) '00999\n"
},
{
"answer_id": 295441,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "Const NUMBER_DIGITS = 5\n\nDim myInteger\nDim formatedInteger\n\nmyInteger = 999\nformatedInteger = Right(String(NUMBER_DIGITS, \"0\") & myInteger, NUMBER_DIGITS)\n Const NUMBER_PADDING = \"000000000000\" ' a few zeroes more just to make sure\n\nFunction ZeroPadInteger(i, numberOfDigits)\n ZeroPadInteger = Right(NUMBER_PADDING & i, numberOfDigits)\nEnd Function\n\n' Call in code:\n\nstrNumber = ZeroPadInteger(myInteger, 5)\n"
},
{
"answer_id": 317625,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 1,
"selected": false,
"text": "function padZeroDigits(sVariable, iLength)\n if (iLength <= len(sVariable)) then padZeroDigits = sVariable : exit function : end if\n padZeroDigits = string(iLength - len(sVariable),\"0\") & sVariable\nend function\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2019426/"
] |
295,419 | <p>What is the best free way to get your maintenance plan-generated backups compressed?</p>
<p>I know there are non-free tools that will compress the backups, but I'm not interested in them.</p>
<p>Options:</p>
<ol>
<li>Have a T-SQL task after the backups that will run a script through xp_cmdshell that compresses every non compressed backup.</li>
<li>???</li>
</ol>
<p>Any other ideas welcome, I'd like to avoid writing a script/program.</p>
| [
{
"answer_id": 1784533,
"author": "Clay Lenhart",
"author_id": 113088,
"author_profile": "https://Stackoverflow.com/users/113088",
"pm_score": 3,
"selected": true,
"text": "msbp.exe backup \"db(database=model)\" \"zip64\" \"local(path=c:\\model.full.bak.zip)\"\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
] |
295,421 | <p>I'm trying to find an editor (or some simple JavaScript - preferably jQuery) that will allow me to edit the contents of a textarea.</p>
<p>I don't want it to be rich text or WYSIWYG; I just want to be able to select a bit of text, click a button/link and have some simple HTML tags that I define put either side of the highlighted text. I also want to be able to insert empty tags at the cursor if no text is selected in the textarea. Essentially, what I'm looking for is similar to the Stack Overflow text editor, but for custom HTML, not Markdown.</p>
<p>What options are there that I could use?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 295429,
"author": "Phil Jenkins",
"author_id": 35496,
"author_profile": "https://Stackoverflow.com/users/35496",
"pm_score": 2,
"selected": true,
"text": "document.selection"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21709/"
] |
295,438 | <p>I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test.</p>
<p>What is the best way to control what urllib.urlopen returns?</p>
| [
{
"answer_id": 295465,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 3,
"selected": false,
"text": "class Processor(oject):\n def __init__(self, fetcher):\n self.m_fetcher = fetcher\n\n def doProcessing(self):\n ## use self.m_fetcher to get page contents\n\nclass RealFetcher(object):\n def fetchPage(self, url):\n ## get real contents\n\nclass FakeFetcher(object):\n def fetchPage(self, url):\n ## Return whatever fake contents are required for this test\n"
},
{
"answer_id": 295469,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "def my_grabber(arg1, arg2, arg3):\n # .. do some stuff ..\n url = make_url_somehow()\n data = urllib.urlopen(url)\n # .. do something with data ..\n return answer\n def my_grabber(arg1, arg2, arg3, urlopen=urllib.urlopen):\n # .. do some stuff ..\n url = make_url_somehow()\n data = urlopen(url)\n # .. do something with data ..\n return answer\n\ndef test_my_grabber():\n my_grabber(arg1, arg2, arg3, urlopen=my_mock_open)\n"
},
{
"answer_id": 295481,
"author": "Clint Miller",
"author_id": 38226,
"author_profile": "https://Stackoverflow.com/users/38226",
"pm_score": 8,
"selected": true,
"text": "urlopen() import urllib\n\ndef some_function_that_uses_urllib():\n ...\n urllib.urlopen()\n ...\n import mymodule\n\ndef dummy_urlopen(url):\n ...\n\nmymodule.urllib.urlopen = dummy_urlopen\n mymodule dummy_urlopen() urlopen()"
},
{
"answer_id": 295503,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 5,
"selected": false,
"text": ">>> import urllib\n>>> # check that it works\n>>> urllib.urlopen('http://www.google.com/')\n<addinfourl at 3082723820L ...>\n>>> # check what happens when it doesn't\n>>> urllib.urlopen('http://hopefully.doesnotexist.com/')\n#-- snip --\nIOError: [Errno socket error] (-2, 'Name or service not known')\n\n>>> # OK, let's mock it up\n>>> import mox\n>>> m = mox.Mox()\n>>> m.StubOutWithMock(urllib, 'urlopen')\n>>> # We can be verbose if we want to :)\n>>> urllib.urlopen(mox.IgnoreArg()).AndRaise(\n... IOError('socket error', (-2, 'Name or service not known')))\n\n>>> # Let's check if it works\n>>> m.ReplayAll()\n>>> urllib.urlopen('http://www.google.com/')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/usr/lib/python2.5/site-packages/mox.py\", line 568, in __call__\n raise expected_method._exception\nIOError: [Errno socket error] (-2, 'Name or service not known')\n\n>>> # yay! now unset everything\n>>> m.UnsetStubs()\n>>> m.VerifyAll()\n>>> # and check that it still works\n>>> urllib.urlopen('http://www.google.com/')\n<addinfourl at 3076773548L ...>\n"
},
{
"answer_id": 2392989,
"author": "Dinoboff",
"author_id": 1771,
"author_profile": "https://Stackoverflow.com/users/1771",
"pm_score": 6,
"selected": false,
"text": "from mock import patch\n\n[...]\n\n@patch('urllib.urlopen')\ndef test_foo(self, urlopen_mock):\n urlopen_mock.return_value = MyUrlOpenMock()\n"
},
{
"answer_id": 6644608,
"author": "ilpoldo",
"author_id": 260963,
"author_profile": "https://Stackoverflow.com/users/260963",
"pm_score": 3,
"selected": false,
"text": "import sys,types\nclass MockCallable():\n \"\"\" Mocks a function, can be enquired on how many calls it received \"\"\"\n def __init__(self, result):\n self.result = result\n self._calls = []\n\n def __call__(self, *arguments):\n \"\"\"Mock callable\"\"\"\n self._calls.append(arguments)\n return self.result\n\n def called(self):\n \"\"\"docstring for called\"\"\"\n return self._calls\n\nclass StubModule(types.ModuleType, object):\n \"\"\" Uses a stub instead of loading libraries \"\"\"\n\n def __init__(self, moduleName):\n self.__name__ = moduleName\n sys.modules[moduleName] = self\n\n def __repr__(self):\n name = self.__name__\n mocks = ', '.join(set(dir(self)) - set(['__name__']))\n return \"<StubModule: %(name)s; mocks: %(mocks)s>\" % locals()\n\nclass StubObject(object):\n pass\n >>> urllib = StubModule(\"urllib\")\n>>> import urllib # won't actually load urllib\n\n>>> urls.urlopen = MockCallable(StubObject())\n\n>>> example = urllib.urlopen('http://example.com')\n>>> example.read = MockCallable('foo')\n\n>>> print(example.read())\n'foo'\n"
},
{
"answer_id": 13296807,
"author": "Gabriel Falcão",
"author_id": 460989,
"author_profile": "https://Stackoverflow.com/users/460989",
"pm_score": 4,
"selected": false,
"text": "import urllib2\nfrom httpretty import HTTPretty, httprettified\n\n\n@httprettified\ndef test_one():\n HTTPretty.register_uri(HTTPretty.GET, \"http://yipit.com/\",\n body=\"Find the best daily deals\")\n\n fd = urllib2.urlopen('http://yipit.com')\n got = fd.read()\n fd.close()\n\n assert got == \"Find the best daily deals\"\n"
},
{
"answer_id": 54362965,
"author": "Alex Harvey",
"author_id": 3787051,
"author_profile": "https://Stackoverflow.com/users/3787051",
"pm_score": 0,
"selected": false,
"text": "class FakeURL:\n def read(foo):\n return '{\"some\":\"json_text\"}'\n # Stub out urllib2.open.\ndef dummy_urlopen(foo, bar, baz):\n return FakeURL()\nurllib2.urlopen = dummy_urlopen\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1771/"
] |
295,448 | <p>A number of business areas I work with use a folder structure to organise their Sharepoint housed documents (not ideal I know, but we're stuck with it). </p>
<p>I would like to use a web part page to present a number of views of their document libraries based on the subfolders that the documents appear in, but this is proving more difficult than I had thought. Has anyone overcome this problem in the past?</p>
| [
{
"answer_id": 6751423,
"author": "schletti2000",
"author_id": 852531,
"author_profile": "https://Stackoverflow.com/users/852531",
"pm_score": 4,
"selected": false,
"text": "<Where>\n <Contains>\n <FieldRef Name='FileDirRef' />\n <Value Type='Lookup'>MyFolder</Value>\n </Contains>\n</Where>\n"
},
{
"answer_id": 20910995,
"author": "Billie Hawkins",
"author_id": 688243,
"author_profile": "https://Stackoverflow.com/users/688243",
"pm_score": 0,
"selected": false,
"text": "http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder\n"
},
{
"answer_id": 42290314,
"author": "Abdul Hameed",
"author_id": 5088712,
"author_profile": "https://Stackoverflow.com/users/5088712",
"pm_score": 0,
"selected": false,
"text": "Name Contains Folder_I_want_to_list Name Name equal to Folder_I_want_to_list"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,455 | <p>In Oracle we can print output by <code>dbms_output.put_line()</code> but I don't know to do the same thing in DB2.</p>
<p>I currently use <code>signal</code> for printing some messages when I debug.</p>
| [
{
"answer_id": 6751423,
"author": "schletti2000",
"author_id": 852531,
"author_profile": "https://Stackoverflow.com/users/852531",
"pm_score": 4,
"selected": false,
"text": "<Where>\n <Contains>\n <FieldRef Name='FileDirRef' />\n <Value Type='Lookup'>MyFolder</Value>\n </Contains>\n</Where>\n"
},
{
"answer_id": 20910995,
"author": "Billie Hawkins",
"author_id": 688243,
"author_profile": "https://Stackoverflow.com/users/688243",
"pm_score": 0,
"selected": false,
"text": "http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder\n"
},
{
"answer_id": 42290314,
"author": "Abdul Hameed",
"author_id": 5088712,
"author_profile": "https://Stackoverflow.com/users/5088712",
"pm_score": 0,
"selected": false,
"text": "Name Contains Folder_I_want_to_list Name Name equal to Folder_I_want_to_list"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24550/"
] |
295,459 | <p>How do I execute the following shell command using the Python <a href="https://docs.python.org/library/subprocess.html" rel="noreferrer"><code>subprocess</code></a> module?</p>
<pre><code>echo "input data" | awk -f script.awk | sort > outfile.txt
</code></pre>
<p>The input data will come from a string, so I don't actually need <code>echo</code>. I've got this far, can anyone explain how I get it to pipe through <code>sort</code> too?</p>
<pre><code>p_awk = subprocess.Popen(["awk","-f","script.awk"],
stdin=subprocess.PIPE,
stdout=file("outfile.txt", "w"))
p_awk.communicate( "input data" )
</code></pre>
<p><strong>UPDATE</strong>: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!</p>
| [
{
"answer_id": 295471,
"author": "geocar",
"author_id": 37507,
"author_profile": "https://Stackoverflow.com/users/37507",
"pm_score": 2,
"selected": false,
"text": "Popen .communicate()"
},
{
"answer_id": 295564,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 7,
"selected": true,
"text": "import subprocess\n\nawk_sort = subprocess.Popen( \"awk -f script.awk | sort > outfile.txt\",\n stdin=subprocess.PIPE, shell=True )\nawk_sort.communicate( b\"input data\\n\" )\n awk >file ; sort file awk | sort a | b a | b os.pipe() a b a | b | c a | (b | c) os.pipe() os.exec() os.fork() sys.stdin sys.stdout os.pipe() subprocess.Popen"
},
{
"answer_id": 9164238,
"author": "Cristian",
"author_id": 1192862,
"author_profile": "https://Stackoverflow.com/users/1192862",
"pm_score": 5,
"selected": false,
"text": "import subprocess\n\nsome_string = b'input_data'\n\nsort_out = open('outfile.txt', 'wb', 0)\nsort_in = subprocess.Popen('sort', stdin=subprocess.PIPE, stdout=sort_out).stdin\nsubprocess.Popen(['awk', '-f', 'script.awk'], stdout=sort_in, \n stdin=subprocess.PIPE).communicate(some_string)\n"
},
{
"answer_id": 16709666,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": "from subprocess import check_call\n\ncheck_call('echo \"input data\" | a | b > outfile.txt', shell=True)\n #!/usr/bin/env python\nfrom subprocess import Popen, PIPE\n\na = Popen([\"a\"], stdin=PIPE, stdout=PIPE)\nwith a.stdin:\n with a.stdout, open(\"outfile.txt\", \"wb\") as outfile:\n b = Popen([\"b\"], stdin=a.stdout, stdout=outfile)\n a.stdin.write(b\"input data\")\nstatuses = [a.wait(), b.wait()] # both a.stdin/stdout are closed already\n plumbum #!/usr/bin/env python\nfrom plumbum.cmd import a, b # magic\n\n(a << \"input data\" | b > \"outfile.txt\")()\n #!/bin/sh\necho \"input data\" | awk -f script.awk | sort > outfile.txt\n #!/usr/bin/env python\nfrom plumbum.cmd import awk, sort\n\n(awk[\"-f\", \"script.awk\"] << \"input data\" | sort > \"outfile.txt\")()\n"
},
{
"answer_id": 27301712,
"author": "Kyle Strand",
"author_id": 1858225,
"author_profile": "https://Stackoverflow.com/users/1858225",
"pm_score": 1,
"selected": false,
"text": "pipes pipes subprocess"
},
{
"answer_id": 28429789,
"author": "I159",
"author_id": 629685,
"author_profile": "https://Stackoverflow.com/users/629685",
"pm_score": 2,
"selected": false,
"text": "grep_proc = subprocess.Popen([\"grep\", \"rabbitmq\"],\n stdin=subprocess.PIPE, \n stdout=subprocess.PIPE)\nsubprocess.Popen([\"ps\", \"aux\"], stdout=grep_proc.stdin)\nout, err = grep_proc.communicate()\n grep ps ps ps grep subprocess"
},
{
"answer_id": 47367956,
"author": "uncleremus",
"author_id": 1817805,
"author_profile": "https://Stackoverflow.com/users/1817805",
"pm_score": 2,
"selected": false,
"text": "communicate communicate(input_data) import os\nimport subprocess\n\ninput = \"\"\"\\\ninput data\nmore input\n\"\"\" * 10\n\nrd, wr = os.pipe()\nif os.fork() != 0: # parent\n os.close(wr)\nelse: # child\n os.close(rd)\n os.write(wr, input)\n os.close(wr)\n exit()\n\np_awk = subprocess.Popen([\"awk\", \"{ print $2; }\"],\n stdin=rd,\n stdout=subprocess.PIPE)\np_sort = subprocess.Popen([\"sort\"], \n stdin=p_awk.stdout,\n stdout=subprocess.PIPE)\np_awk.stdout.close()\nout, err = p_sort.communicate()\nprint (out.rstrip())\n from tempfile import TemporaryFile\ntf = TemporaryFile()\ntf.write(input)\ntf.seek(0, 0)\n stdin=tf p_awk sort head -n 10 sort stderr stdout Popen SIG_IGN SIGPIPE SIG_DFL sort"
},
{
"answer_id": 53688246,
"author": "Omry Yadan",
"author_id": 1930838,
"author_profile": "https://Stackoverflow.com/users/1930838",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/env python3\n\nfrom subprocess import Popen, PIPE\n\n# cmd1 : dd if=/dev/zero bs=1m count=100\n# cmd2 : gzip\n# cmd3 : wc -c\ncmd1 = ['dd', 'if=/dev/zero', 'bs=1M', 'count=100']\ncmd2 = ['tee']\ncmd3 = ['wc', '-c']\nprint(f\"Shell style : {' '.join(cmd1)} | {' '.join(cmd2)} | {' '.join(cmd3)}\")\n\np1 = Popen(cmd1, stdout=PIPE, stderr=PIPE) # stderr=PIPE optional, dd is chatty\np2 = Popen(cmd2, stdin=p1.stdout, stdout=PIPE)\np3 = Popen(cmd3, stdin=p2.stdout, stdout=PIPE)\n\nprint(\"Output from last process : \" + (p3.communicate()[0]).decode())\n\n# thoretically p1 and p2 may still be running, this ensures we are collecting their return codes\np1.wait()\np2.wait()\nprint(\"p1 return: \", p1.returncode)\nprint(\"p2 return: \", p2.returncode)\nprint(\"p3 return: \", p3.returncode)\n"
},
{
"answer_id": 56533467,
"author": "mwag",
"author_id": 3160967,
"author_profile": "https://Stackoverflow.com/users/3160967",
"pm_score": 1,
"selected": false,
"text": "from subprocess import Popen, PIPE\n\ndef string_to_2_procs_to_file(input_s, first_cmd, second_cmd, output_filename):\n with open(output_filename, 'wb') as out_f:\n p2 = Popen(second_cmd, stdin=PIPE, stdout=out_f)\n p1 = Popen(first_cmd, stdout=p2.stdin, stdin=PIPE)\n p1.communicate(input=bytes(input_s))\n p1.wait()\n p2.stdin.close()\n p2.wait()\n string_to_2_procs_to_file('input data', ['awk', '-f', 'script.awk'], ['sort'], 'output.txt')\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
295,472 | <p>I am using xsl to control the output of my xml file, but the BOM character is being added.</p>
| [
{
"answer_id": 300474,
"author": "Benedikt Waldvogel",
"author_id": 4308,
"author_profile": "https://Stackoverflow.com/users/4308",
"pm_score": 7,
"selected": false,
"text": "# vim file.xml\n:set nobomb\n:wq\n"
},
{
"answer_id": 7664724,
"author": "ken",
"author_id": 907785,
"author_profile": "https://Stackoverflow.com/users/907785",
"pm_score": 2,
"selected": false,
"text": "<xsl:output method=\"text\"\n encoding=\"ASCII\"/>\n"
},
{
"answer_id": 10314333,
"author": "dr_leevsey",
"author_id": 1355982,
"author_profile": "https://Stackoverflow.com/users/1355982",
"pm_score": 1,
"selected": false,
"text": "<xsl:value-of select=\"translate(StringWithBOM,'','')\"/>"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,511 | <p>MS Access allows the numeric type GUID (in German it's called 'Replikations-ID', so I guess in English that would be 'replication id') which is stored as a 16 byte binary field in the database.</p>
<p>I found how to access these fields in Delphi with <a href="http://docwiki.embarcadero.com/Libraries/Tokyo/en/Data.Win.ADODB.TADOQuery" rel="nofollow noreferrer"><strong>TADOQuery</strong></a>/<a href="http://docwiki.embarcadero.com/Libraries/Tokyo/en/Data.Win.ADODB.TADOTable" rel="nofollow noreferrer"><strong>TADOTable</strong></a> using </p>
<pre><code>(TheQuery.FieldByName('SomeGuidField') as TGUIDField).AsGuid;
</code></pre>
<p>But now I want to execute an SQL-Query like this:</p>
<pre><code>SELECT * FROM SomeTable WHERE SomeGuidField=:AGuid
</code></pre>
<p>I tried setting a <a href="http://docwiki.embarcadero.com/Libraries/Tokyo/en/Data.Win.ADODB.TADOQuery.SQL" rel="nofollow noreferrer"><strong>TADOQuery.SQL</strong></a> property to the above statement, but found no way to actually set the <code>AGuid</code> parameter such that the query can be opened. Whatever I tried resulted in the (ADO/COM) error </p>
<blockquote>
<p>No value given for one or more required parameters</p>
</blockquote>
<p>For example:</p>
<pre><code>TheQuery.ParamByName('AGuid').Value := QuotedString(GuidToStr(AGuid));
TheQuery.Open; // <<== crashes here
</code></pre>
<p>This doesn't work either:</p>
<pre><code>TheQuery.ParamByName('AGuid').Value := GuidToStr(AGuid);
TheQuery.Open; // <<== crashes here
</code></pre>
<p>I had a look at how <code>TGuidField(...).AsGuid</code> works and found that it first converts the GUID to a string and then the string to a variant (and vice versa).</p>
<p>It works fine, if I always generate the SQL-Statement like this:</p>
<pre><code>SELECT * FROM SomeTable WHERE SomeGuidField='<a guid goes here>'
</code></pre>
<p>As I am passing that <strong>TADOQuery</strong> object around in the program I would like to only change the <code>AGuid</code>-Parameter to keep most methods agnostic on the actual SQL-Statement.</p>
<p>Is there any other way to set a GUID-Parameter than always change the complete SQL-Statement?</p>
<p>(It must be a GUID because I need a globally unique identifier to synchronize with other databases which are MS SQL or MS Access based.)</p>
<p><strong>Edit</strong>
vradmilovic is right, this works:</p>
<pre><code>TheQuery.ParamByName('AGuid').Value := GuidToStr(AGuid);
TheQuery.Open;
</code></pre>
<p>I don't understand why it didn't work the first time I tried it.</p>
| [
{
"answer_id": 295571,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": -1,
"selected": false,
"text": "TGuidField(TheQuery.ParamByName('AGuid')).AsGuid\n"
},
{
"answer_id": 1192730,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "QueryIns.Parameters.ParamByName('GUID').Assign(Query.FieldByName('objectGUID'));\n Query.SQL.Add('select cast(objectGUID as uniqueidentifier) as objectGUID');\nQuery.SQL.Add('from vwADGroups');\nQuery.Open;\nwhile not Query.Eof do begin\n Index := List.IndexOfName(Query.FieldByName('objectGUID').AsString);\n //...\nend;\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21506/"
] |
295,515 | <p>Inside my code I'm generating hashes of URLs, (which are practically of unbounded length). I'm currently using sha1(), which I know has a tiny chance of a collision, but I have up to 255 bytes to store the hash in so feel that I might as well use that available space to lower the chance of collision even further.</p>
<p>Is there either:</p>
<ol>
<li>Another PHP hash function with a longer or customisable hash length?</li>
<li>A way of using a fixed-length hash function like sha1 with a variable length input to generate a longer hash?</li>
</ol>
<p>Or, is sha1's 20-byte hash good enough for anything and I should stop worrying about it?</p>
| [
{
"answer_id": 295667,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": "found = false\nhv = hash(urlValue)\nif table[hash,url] contains pair (hv,urlValue)\n found = true\nendif\n\nif (not found)\n insert table (hv,urlValue)\nendif\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34024/"
] |
295,523 | <p>I need to increase the max_allowed_packet param, to fit some theoretically very large items. If I set this param to say 10M, what price if any am I paying compared to setting it to 1M or 4M.
Thanks for any input!
Tomas</p>
| [
{
"answer_id": 296241,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "http://www.astahost.com/info.php/max_allowed_packet-mysql_t2725.html"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38231/"
] |
295,524 | <p>I'm looking for a web based upload manager, with good support for images. It should be as easy as possible for novice users to "add images to a website". I could use such a thing for two use cases:</p>
<ul>
<li>A CMS for external use, needs proper image support (1-file upload doesn't quite cut it).</li>
<li>A Wiki for internal use, to get popular it will need the ability to put in screenshots easily without bothering with "save screenshot to file - upload file - put complicated markup on page to display image".</li>
</ul>
<p>Ideally, the thing I'm looking for shows galleries of uploaded images and allows the user to add/remove/replace images. </p>
<p>I know there are probably a lot of server-side PHP scripts that can do things like this, in a pop-up window, or with AJAX, but where they're all lacking is in copy/paste support. Especially for the internal support site, a printscreen + paste would be an ideal solution, but I'm unable to find a package that supports this.</p>
<p>I'm guessing this should be possible using Flash; unless there's no way to paste image data into a Flash file. I don't know much about that though. I could probably develop something myself, but I really don't want to have to learn Flash, and I don't have the $$ to pay for the Flash development tools.</p>
<p>So tell me, is it even possible to copy/paste bitmap data into a Flash movie? And has someone perhaps already written an elegant image/upload manager that makes use of it?</p>
| [
{
"answer_id": 296241,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "http://www.astahost.com/info.php/max_allowed_packet-mysql_t2725.html"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2474/"
] |
295,533 | <p>say I have an asynchronous library, written in native C++, with an interface similar to this:</p>
<pre><code>class connection {
public:
boost::signal< void() > sig_connection_made;
boost::signal< void(const std::string&) > sig_error;
void connect(const std::string& host, const std::string& port);
};
</code></pre>
<p>that I want to wrap in C#. Does anyone know of a way, using SWIG or something similar, that will allow me to bind the signals to C# delegates?</p>
| [
{
"answer_id": 296241,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "http://www.astahost.com/info.php/max_allowed_packet-mysql_t2725.html"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35656/"
] |
295,538 | <p>When connecting to a network share for which the current user (in my case, a network enabled service user) has no rights, name and password have to be provided.</p>
<p>I know how to do this with Win32 functions (the <code>WNet*</code> family from <code>mpr.dll</code>), but would like to do it with .Net (2.0) functionality.</p>
<p>What options are available?</p>
<p><strong>Maybe some more information helps:</strong></p>
<ul>
<li>The use case is a windows service, not an Asp.Net application.</li>
<li>The service is running under an account which has no rights on the share.</li>
<li>The user account needed for the share is not known on the client side.</li>
<li>Client and server are not members of the same domain.</li>
</ul>
| [
{
"answer_id": 295545,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 1,
"selected": false,
"text": "<identity impersonate=\"true\" userName=\"domain\\user\" password=\"****\" />\n"
},
{
"answer_id": 295553,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "WindowsIdentity.Impersonate ProcessStartInfo .UserName .Password .Domain"
},
{
"answer_id": 295703,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 8,
"selected": true,
"text": "using (new NetworkConnection(@\"\\\\server\\read\", readCredentials))\nusing (new NetworkConnection(@\"\\\\server2\\write\", writeCredentials)) {\n File.Copy(@\"\\\\server\\read\\file\", @\"\\\\server2\\write\\file\");\n}\n"
},
{
"answer_id": 1197430,
"author": "Luke Quinane",
"author_id": 18437,
"author_profile": "https://Stackoverflow.com/users/18437",
"pm_score": 8,
"selected": false,
"text": "public class NetworkConnection : IDisposable\n{\n string _networkName;\n\n public NetworkConnection(string networkName, \n NetworkCredential credentials)\n {\n _networkName = networkName;\n\n var netResource = new NetResource()\n {\n Scope = ResourceScope.GlobalNetwork,\n ResourceType = ResourceType.Disk,\n DisplayType = ResourceDisplaytype.Share,\n RemoteName = networkName\n };\n\n var userName = string.IsNullOrEmpty(credentials.Domain)\n ? credentials.UserName\n : string.Format(@\"{0}\\{1}\", credentials.Domain, credentials.UserName);\n\n var result = WNetAddConnection2(\n netResource, \n credentials.Password,\n userName,\n 0);\n \n if (result != 0)\n {\n throw new Win32Exception(result);\n } \n }\n\n ~NetworkConnection()\n {\n Dispose(false);\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n protected virtual void Dispose(bool disposing)\n {\n WNetCancelConnection2(_networkName, 0, true);\n }\n\n [DllImport(\"mpr.dll\")]\n private static extern int WNetAddConnection2(NetResource netResource, \n string password, string username, int flags);\n\n [DllImport(\"mpr.dll\")]\n private static extern int WNetCancelConnection2(string name, int flags,\n bool force);\n}\n\n[StructLayout(LayoutKind.Sequential)]\npublic class NetResource\n{\n public ResourceScope Scope;\n public ResourceType ResourceType;\n public ResourceDisplaytype DisplayType;\n public int Usage;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string LocalName;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string RemoteName;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string Comment;\n [MarshalAs(UnmanagedType.LPWStr)]\n public string Provider;\n}\n\npublic enum ResourceScope : int\n{\n Connected = 1,\n GlobalNetwork,\n Remembered,\n Recent,\n Context\n};\n\npublic enum ResourceType : int\n{\n Any = 0,\n Disk = 1,\n Print = 2,\n Reserved = 8,\n}\n\npublic enum ResourceDisplaytype : int\n{\n Generic = 0x0,\n Domain = 0x01,\n Server = 0x02,\n Share = 0x03,\n File = 0x04,\n Group = 0x05,\n Network = 0x06,\n Root = 0x07,\n Shareadmin = 0x08,\n Directory = 0x09,\n Tree = 0x0a,\n Ndscontainer = 0x0b\n}\n"
},
{
"answer_id": 8271759,
"author": "Hakan KOSE",
"author_id": 271103,
"author_profile": "https://Stackoverflow.com/users/271103",
"pm_score": 5,
"selected": false,
"text": "var savePath = @\"\\\\servername\\foldername\\myfilename.jpg\";\nvar filePath = @\"C:\\\\temp\\myfileTosave.jpg\";\n SaveACopyfileToServer(filePath, savePath);\n using System.IO\nusing System.Diagnostics;\n\n\npublic static void SaveACopyfileToServer(string filePath, string savePath)\n {\n var directory = Path.GetDirectoryName(savePath).Trim();\n var username = \"loginusername\";\n var password = \"loginpassword\";\n var filenameToSave = Path.GetFileName(savePath);\n\n if (!directory.EndsWith(\"\\\\\"))\n filenameToSave = \"\\\\\" + filenameToSave;\n\n var command = \"NET USE \" + directory + \" /delete\";\n ExecuteCommand(command, 5000);\n\n command = \"NET USE \" + directory + \" /user:\" + username + \" \" + password;\n ExecuteCommand(command, 5000);\n\n command = \" copy \\\"\" + filePath + \"\\\" \\\"\" + directory + filenameToSave + \"\\\"\";\n\n ExecuteCommand(command, 5000);\n\n\n command = \"NET USE \" + directory + \" /delete\";\n ExecuteCommand(command, 5000);\n }\n public static int ExecuteCommand(string command, int timeout)\n {\n var processInfo = new ProcessStartInfo(\"cmd.exe\", \"/C \" + command)\n {\n CreateNoWindow = true, \n UseShellExecute = false, \n WorkingDirectory = \"C:\\\\\",\n };\n\n var process = Process.Start(processInfo);\n process.WaitForExit(timeout);\n var exitCode = process.ExitCode;\n process.Close();\n return exitCode;\n } \n"
},
{
"answer_id": 22481542,
"author": "VladL",
"author_id": 1608660,
"author_profile": "https://Stackoverflow.com/users/1608660",
"pm_score": 4,
"selected": false,
"text": "public sealed class WrappedImpersonationContext\n{\n public enum LogonType : int\n {\n Interactive = 2,\n Network = 3,\n Batch = 4,\n Service = 5,\n Unlock = 7,\n NetworkClearText = 8,\n NewCredentials = 9\n }\n\n public enum LogonProvider : int\n {\n Default = 0, // LOGON32_PROVIDER_DEFAULT\n WinNT35 = 1,\n WinNT40 = 2, // Use the NTLM logon provider.\n WinNT50 = 3 // Use the negotiate logon provider.\n }\n\n [DllImport(\"advapi32.dll\", EntryPoint = \"LogonUserW\", SetLastError = true, CharSet = CharSet.Unicode)]\n public static extern bool LogonUser(String lpszUsername, String lpszDomain,\n String lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);\n\n [DllImport(\"kernel32.dll\")]\n public extern static bool CloseHandle(IntPtr handle);\n\n private string _domain, _password, _username;\n private IntPtr _token;\n private WindowsImpersonationContext _context;\n\n private bool IsInContext\n {\n get { return _context != null; }\n }\n\n public WrappedImpersonationContext(string domain, string username, string password)\n {\n _domain = String.IsNullOrEmpty(domain) ? \".\" : domain;\n _username = username;\n _password = password;\n }\n\n // Changes the Windows identity of this thread. Make sure to always call Leave() at the end.\n [PermissionSetAttribute(SecurityAction.Demand, Name = \"FullTrust\")]\n public void Enter()\n {\n if (IsInContext)\n return;\n\n _token = IntPtr.Zero;\n bool logonSuccessfull = LogonUser(_username, _domain, _password, LogonType.NewCredentials, LogonProvider.WinNT50, ref _token);\n if (!logonSuccessfull)\n {\n throw new Win32Exception(Marshal.GetLastWin32Error());\n }\n WindowsIdentity identity = new WindowsIdentity(_token);\n _context = identity.Impersonate();\n\n Debug.WriteLine(WindowsIdentity.GetCurrent().Name);\n }\n\n [PermissionSetAttribute(SecurityAction.Demand, Name = \"FullTrust\")]\n public void Leave()\n {\n if (!IsInContext)\n return;\n\n _context.Undo();\n\n if (_token != IntPtr.Zero)\n {\n CloseHandle(_token);\n }\n _context = null;\n }\n}\n var impersonationContext = new WrappedImpersonationContext(Domain, Username, Password);\nimpersonationContext.Enter();\n\n//do your stuff here\n\nimpersonationContext.Leave();\n"
},
{
"answer_id": 33548830,
"author": "Alessandro Bernardi",
"author_id": 2703744,
"author_profile": "https://Stackoverflow.com/users/2703744",
"pm_score": 3,
"selected": false,
"text": "Imports System\nImports System.Net\nImports System.Runtime.InteropServices\nImports System.ComponentModel\n\nPublic Class NetworkConnection\n Implements IDisposable\n\n Private _networkName As String\n\n Public Sub New(networkName As String, credentials As NetworkCredential)\n _networkName = networkName\n\n Dim netResource = New NetResource() With {\n .Scope = ResourceScope.GlobalNetwork,\n .ResourceType = ResourceType.Disk,\n .DisplayType = ResourceDisplaytype.Share,\n .RemoteName = networkName\n }\n\n Dim userName = If(String.IsNullOrEmpty(credentials.Domain), credentials.UserName, String.Format(\"{0}\\{1}\", credentials.Domain, credentials.UserName))\n\n Dim result = WNetAddConnection2(NetResource, credentials.Password, userName, 0)\n\n If result <> 0 Then\n Throw New Win32Exception(result, \"Error connecting to remote share\")\n End If\n End Sub\n\n Protected Overrides Sub Finalize()\n Try\n Dispose (False)\n Finally\n MyBase.Finalize()\n End Try\n End Sub\n\n Public Sub Dispose() Implements IDisposable.Dispose\n Dispose (True)\n GC.SuppressFinalize (Me)\n End Sub\n\n Protected Overridable Sub Dispose(disposing As Boolean)\n WNetCancelConnection2(_networkName, 0, True)\n End Sub\n\n <DllImport(\"mpr.dll\")> _\n Private Shared Function WNetAddConnection2(netResource As NetResource, password As String, username As String, flags As Integer) As Integer\n End Function\n\n <DllImport(\"mpr.dll\")> _\n Private Shared Function WNetCancelConnection2(name As String, flags As Integer, force As Boolean) As Integer\n End Function\n\nEnd Class\n\n<StructLayout(LayoutKind.Sequential)> _\nPublic Class NetResource\n Public Scope As ResourceScope\n Public ResourceType As ResourceType\n Public DisplayType As ResourceDisplaytype\n Public Usage As Integer\n Public LocalName As String\n Public RemoteName As String\n Public Comment As String\n Public Provider As String\nEnd Class\n\nPublic Enum ResourceScope As Integer\n Connected = 1\n GlobalNetwork\n Remembered\n Recent\n Context\nEnd Enum\n\nPublic Enum ResourceType As Integer\n Any = 0\n Disk = 1\n Print = 2\n Reserved = 8\nEnd Enum\n\nPublic Enum ResourceDisplaytype As Integer\n Generic = &H0\n Domain = &H1\n Server = &H2\n Share = &H3\n File = &H4\n Group = &H5\n Network = &H6\n Root = &H7\n Shareadmin = &H8\n Directory = &H9\n Tree = &HA\n Ndscontainer = &HB\nEnd Enum\n"
},
{
"answer_id": 33634690,
"author": "python_kaa",
"author_id": 2056222,
"author_profile": "https://Stackoverflow.com/users/2056222",
"pm_score": 1,
"selected": false,
"text": "module NetworkShare\n\nopen System\nopen System.ComponentModel\nopen System.IO\nopen System.Net\nopen System.Runtime.InteropServices\n\ntype ResourceScope =\n| Connected = 1\n| GlobalNetwork = 2\n| Remembered = 3\n| Recent = 4\ntype ResourceType =\n| Any = 0\n| Disk = 1\n| Print = 2\n| Reserved = 8\ntype ResourceDisplayType =\n| Generic = 0x0\n| Domain = 0x01\n| Server = 0x02\n| Share = 0x03\n| File = 0x04\n| Group = 0x05\n| Network = 0x06\n| Root = 0x07\n| Shareadmin = 0x08\n| Directory = 0x09\n| Tree = 0x0a\n| Ndscontainer = 0x0b\n\n//Uses of this construct may result in the generation of unverifiable .NET IL code.\n#nowarn \"9\"\n[<StructLayout(LayoutKind.Sequential)>]\ntype NetResource =\n struct\n val mutable Scope : ResourceScope\n val mutable ResourceType : ResourceType\n val mutable DisplayType : ResourceDisplayType\n val mutable Usage : int\n val mutable LocalName : string\n val mutable RemoteName : string\n val mutable Comment : string\n val mutable Provider : string\n new(name) = {\n // lets preset needed fields\n NetResource.Scope = ResourceScope.GlobalNetwork\n ResourceType = ResourceType.Disk\n DisplayType = ResourceDisplayType.Share\n Usage = 0\n LocalName = null\n RemoteName = name\n Comment = null\n Provider = null\n }\n end\n\ntype WNetConnection(networkName : string, credential : NetworkCredential) =\n [<Literal>]\n static let Mpr = \"mpr.dll\"\n [<DllImport(Mpr, EntryPoint = \"WNetAddConnection2\")>]\n static extern int connect(NetResource netResource, string password, string username, int flags)\n [<DllImport(Mpr, EntryPoint = \"WNetCancelConnection2\")>]\n static extern int disconnect(string name, int flags, bool force)\n\n let mutable disposed = false;\n\n do\n let userName = if String.IsNullOrWhiteSpace credential.Domain\n then credential.UserName\n else credential.Domain + \"\\\\\" + credential.UserName\n let resource = new NetResource(networkName)\n\n let result = connect(resource, credential.Password, userName, 0)\n\n if result <> 0 then\n let msg = \"Error connecting to remote share \" + networkName\n new Win32Exception(result, msg)\n |> raise\n\n let cleanup(disposing:bool) =\n if not disposed then\n disposed <- true\n if disposing then () // TODO dispose managed resources here\n disconnect(networkName, 0, true) |> ignore\n\n interface IDisposable with\n member __.Dispose() =\n disconnect(networkName, 0, true) |> ignore\n GC.SuppressFinalize(__)\n\n override __.Finalize() = cleanup(false)\n\ntype CopyPath =\n | RemotePath of string * NetworkCredential\n | LocalPath of string\n\nlet createDisposable() =\n {\n new IDisposable with\n member __.Dispose() = ()\n }\n\nlet copyFile overwrite destPath srcPath : unit =\n use _srcConn =\n match srcPath with\n | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable\n | LocalPath(_) -> createDisposable()\n use _destConn =\n match destPath with\n | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable\n | LocalPath(_) -> createDisposable()\n match srcPath, destPath with\n | RemotePath(src, _), RemotePath(dest, _)\n | LocalPath(src), RemotePath(dest, _)\n | RemotePath(src, _), LocalPath(dest)\n | LocalPath(src), LocalPath(dest) ->\n if FileInfo(src).Exists |> not then\n failwith (\"Source file not found: \" + src)\n let destFilePath =\n if DirectoryInfo(dest).Exists then Path.Combine(dest, Path.GetFileName src)\n else dest\n File.Copy(src, destFilePath, overwrite)\n\nlet rec copyDir copySubDirs filePattern destPath srcPath =\n use _srcConn =\n match srcPath with\n | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable\n | LocalPath(_) -> createDisposable()\n use _destConn =\n match destPath with\n | RemotePath(path, credential) -> new WNetConnection(path, credential) :> IDisposable\n | LocalPath(_) -> createDisposable()\n match srcPath, destPath with\n | RemotePath(src, _), RemotePath(dest, _)\n | LocalPath(src), RemotePath(dest, _)\n | RemotePath(src, _), LocalPath(dest)\n | LocalPath(src), LocalPath(dest) ->\n let dir = DirectoryInfo(src)\n if dir.Exists |> not then\n failwith (\"Source directory not found: \" + src)\n\n let dirs = dir.GetDirectories()\n if Directory.Exists(dest) |> not then\n Directory.CreateDirectory(dest) |> ignore\n\n let files = dir.GetFiles(filePattern)\n for file in files do\n let tempPath = Path.Combine(dest, file.Name)\n file.CopyTo(tempPath, false) |> ignore\n\n if copySubDirs then\n for subdir in dirs do\n let subdirSrc =\n match srcPath with\n | RemotePath(_, credential) -> RemotePath(Path.Combine(dest, subdir.Name), credential)\n | LocalPath(_) -> LocalPath(Path.Combine(dest, subdir.Name))\n let subdirDest =\n match destPath with\n | RemotePath(_, credential) -> RemotePath(subdir.FullName, credential)\n | LocalPath(_) -> LocalPath(subdir.FullName)\n copyDir copySubDirs filePattern subdirDest subdirSrc\n"
},
{
"answer_id": 39540451,
"author": "Pavel Kovalev",
"author_id": 701869,
"author_profile": "https://Stackoverflow.com/users/701869",
"pm_score": 6,
"selected": false,
"text": "ImpersonationHelper.Impersonate(domain, userName, userPassword, delegate\n {\n //Your code here \n //Let's say file copy:\n if (!File.Exists(to))\n {\n File.Copy(from, to);\n }\n });\n using System;\nusing System.Runtime.ConstrainedExecution;\nusing System.Runtime.InteropServices;\nusing System.Security;\nusing System.Security.Permissions;\nusing System.Security.Principal; \nusing Microsoft.Win32.SafeHandles;\n\n\nnamespace BlaBla\n{\n public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n private SafeTokenHandle()\n : base(true)\n {\n }\n\n [DllImport(\"kernel32.dll\")]\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n [SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseHandle(IntPtr handle);\n\n protected override bool ReleaseHandle()\n {\n return CloseHandle(handle);\n }\n }\n\n public class ImpersonationHelper\n {\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,\n int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n private extern static bool CloseHandle(IntPtr handle);\n\n [PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\n public static void Impersonate(string domainName, string userName, string userPassword, Action actionToExecute)\n {\n SafeTokenHandle safeTokenHandle;\n try\n {\n\n const int LOGON32_PROVIDER_DEFAULT = 0;\n //This parameter causes LogonUser to create a primary token.\n const int LOGON32_LOGON_INTERACTIVE = 2;\n\n // Call LogonUser to obtain a handle to an access token.\n bool returnValue = LogonUser(userName, domainName, userPassword,\n LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,\n out safeTokenHandle);\n //Facade.Instance.Trace(\"LogonUser called.\");\n\n if (returnValue == false)\n {\n int ret = Marshal.GetLastWin32Error();\n //Facade.Instance.Trace($\"LogonUser failed with error code : {ret}\");\n\n throw new System.ComponentModel.Win32Exception(ret);\n }\n\n using (safeTokenHandle)\n {\n //Facade.Instance.Trace($\"Value of Windows NT token: {safeTokenHandle}\");\n //Facade.Instance.Trace($\"Before impersonation: {WindowsIdentity.GetCurrent().Name}\");\n\n // Use the token handle returned by LogonUser.\n using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))\n {\n using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())\n {\n //Facade.Instance.Trace($\"After impersonation: {WindowsIdentity.GetCurrent().Name}\");\n //Facade.Instance.Trace(\"Start executing an action\");\n\n actionToExecute();\n\n //Facade.Instance.Trace(\"Finished executing an action\");\n }\n }\n //Facade.Instance.Trace($\"After closing the context: {WindowsIdentity.GetCurrent().Name}\");\n }\n\n }\n catch (Exception ex)\n {\n //Facade.Instance.Trace(\"Oh no! Impersonate method failed.\");\n //ex.HandleException();\n //On purpose: we want to notify a caller about the issue /Pavel Kovalev 9/16/2016 2:15:23 PM)/\n throw;\n }\n }\n }\n}\n"
},
{
"answer_id": 73763092,
"author": "matpop",
"author_id": 1836314,
"author_profile": "https://Stackoverflow.com/users/1836314",
"pm_score": 1,
"selected": false,
"text": "Process.Start(\"CMDKEY\", @\"/add:\"\"NetworkName\"\" /user:\"\"Username\"\" /pass:\"\"Password\"\"\");\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23772/"
] |
295,557 | <p>What's the best way to do it in .NET?
I always forget what I need to <code>Dispose()</code> (or wrap with <code>using</code>).</p>
<p>EDIT: after a long time using <code>WebRequest</code>, I found out about customizing <code>WebClient</code>. Much better.</p>
| [
{
"answer_id": 295558,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 3,
"selected": false,
"text": "public string GetRequest(Uri uri, int timeoutMilliseconds)\n{\n var request = System.Net.WebRequest.Create(uri);\n request.Timeout = timeoutMilliseconds;\n using (var response = request.GetResponse())\n using (var stream = response.GetResponseStream())\n using (var reader = new System.IO.StreamReader(stream))\n {\n return reader.ReadToEnd();\n }\n}\n"
},
{
"answer_id": 396712,
"author": "Jader Dias",
"author_id": 48465,
"author_profile": "https://Stackoverflow.com/users/48465",
"pm_score": 4,
"selected": false,
"text": "var request = HttpWebRequest.Create(\"http://www.contoso.com\");\nrequest.Timeout = 50000;\nusing (var response = request.GetResponse())\n{\n //your code here\n}\n using System;\nusing System.Net;\nusing System.IO;\nusing System.Text;\nusing System.Threading;\n\n\npublic class RequestState\n{\n // This class stores the State of the request.\n const int BUFFER_SIZE = 1024;\n public StringBuilder requestData;\n public byte[] BufferRead;\n public HttpWebRequest request;\n public HttpWebResponse response;\n public Stream streamResponse;\n public RequestState()\n {\n BufferRead = new byte[BUFFER_SIZE];\n requestData = new StringBuilder(\"\");\n request = null;\n streamResponse = null;\n }\n}\n\nclass HttpWebRequest_BeginGetResponse\n{\n public static ManualResetEvent allDone = new ManualResetEvent(false);\n const int BUFFER_SIZE = 1024;\n const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout\n\n // Abort the request if the timer fires.\n private static void TimeoutCallback(object state, bool timedOut)\n {\n if (timedOut)\n {\n HttpWebRequest request = state as HttpWebRequest;\n if (request != null)\n {\n request.Abort();\n }\n }\n }\n\n static void Main()\n {\n\n try\n {\n // Create a HttpWebrequest object to the desired URL. \n HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(\"http://www.contoso.com\");\n myHttpWebRequest.ReadWriteTimeout = DefaultTimeout;\n\n\n // Create an instance of the RequestState and assign the previous myHttpWebRequest\n // object to its request field. \n RequestState myRequestState = new RequestState();\n myRequestState.request = myHttpWebRequest;\n\n\n // Start the asynchronous request.\n IAsyncResult result =\n (IAsyncResult)myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), myRequestState);\n\n // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted\n ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);\n\n // The response came in the allowed time. The work processing will happen in the \n // callback function.\n allDone.WaitOne();\n\n // Release the HttpWebResponse resource.\n myRequestState.response.Close();\n }\n catch (WebException e)\n {\n Console.WriteLine(\"\\nMain Exception raised!\");\n Console.WriteLine(\"\\nMessage:{0}\", e.Message);\n Console.WriteLine(\"\\nStatus:{0}\", e.Status);\n Console.WriteLine(\"Press any key to continue..........\");\n }\n catch (Exception e)\n {\n Console.WriteLine(\"\\nMain Exception raised!\");\n Console.WriteLine(\"Source :{0} \", e.Source);\n Console.WriteLine(\"Message :{0} \", e.Message);\n Console.WriteLine(\"Press any key to continue..........\");\n Console.Read();\n }\n }\n private static void RespCallback(IAsyncResult asynchronousResult)\n {\n try\n {\n // State of request is asynchronous.\n RequestState myRequestState = (RequestState)asynchronousResult.AsyncState;\n HttpWebRequest myHttpWebRequest = myRequestState.request;\n myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);\n\n // Read the response into a Stream object.\n Stream responseStream = myRequestState.response.GetResponseStream();\n myRequestState.streamResponse = responseStream;\n\n // Begin the Reading of the contents of the HTML page and print it to the console.\n IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);\n return;\n }\n catch (WebException e)\n {\n Console.WriteLine(\"\\nRespCallback Exception raised!\");\n Console.WriteLine(\"\\nMessage:{0}\", e.Message);\n Console.WriteLine(\"\\nStatus:{0}\", e.Status);\n }\n allDone.Set();\n }\n private static void ReadCallBack(IAsyncResult asyncResult)\n {\n try\n {\n\n RequestState myRequestState = (RequestState)asyncResult.AsyncState;\n Stream responseStream = myRequestState.streamResponse;\n int read = responseStream.EndRead(asyncResult);\n // Read the HTML page and then print it to the console.\n if (read > 0)\n {\n myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));\n IAsyncResult asynchronousResult = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);\n return;\n }\n else\n {\n Console.WriteLine(\"\\nThe contents of the Html page are : \");\n if (myRequestState.requestData.Length > 1)\n {\n string stringContent;\n stringContent = myRequestState.requestData.ToString();\n Console.WriteLine(stringContent);\n }\n Console.WriteLine(\"Press any key to continue..........\");\n Console.ReadLine();\n\n responseStream.Close();\n }\n\n }\n catch (WebException e)\n {\n Console.WriteLine(\"\\nReadCallBack Exception raised!\");\n Console.WriteLine(\"\\nMessage:{0}\", e.Message);\n Console.WriteLine(\"\\nStatus:{0}\", e.Status);\n }\n allDone.Set();\n\n }\n}\n"
},
{
"answer_id": 1737584,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 4,
"selected": true,
"text": "WebClient public class WebClientWithTimeout : WebClient\n{\n private readonly int timeoutMilliseconds;\n public WebClientWithTimeout(int timeoutMilliseconds)\n {\n this.timeoutMilliseconds = timeoutMilliseconds;\n }\n\n protected override WebRequest GetWebRequest(Uri address)\n {\n var result = base.GetWebRequest(address);\n result.Timeout = timeoutMilliseconds;\n return result;\n }\n}\n public string GetRequest(Uri uri, int timeoutMilliseconds)\n{\n using (var client = new WebClientWithTimeout(timeoutMilliseconds))\n {\n return client.DownloadString();\n }\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37020/"
] |
295,563 | <p>I need to disable windows-update service from my installation. I already use vbscript to do some stuff so I would like to do it in vbscript.</p>
<p>My knowledge of vbscript (or any other script language) is very limited so...can anybody help me out with that? I'll really appreciate it!</p>
<p>Thanks.</p>
| [
{
"answer_id": 295586,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "strComputer = \".\" 'could be any computer, not just the local one '\nSet objWMIService = GetObject(\"winmgmts:\\\\\" & strComputer & \"\\root\\cimv2\")\n\nSet colServiceList = objWMIService.ExecQuery _\n(\"Select * from Win32_Service where Name = 'wuauserv'\")\n\nFor Each objService in colServiceList\n objService.ChangeStartMode(\"Disabled\")\nNext\n sc.exe sc.exe C:\\>sc config\nModifies a service entry in the registry and Service Database.\nSYNTAX:\nsc <server> config [service name] <option1> <option2>...\nCONFIG OPTIONS:\nNOTE: The option name includes the equal sign.\n type= <own|share|interact|kernel|filesys|rec|adapt>\n start= <boot|system|auto|demand|disabled>\n error= <normal|severe|critical|ignore>\n binPath= <BinaryPathName>\n group= <LoadOrderGroup>\n tag= <yes|no>\n depend= <Dependencies(separated by / (forward slash))>\n obj= <AccountName|ObjectName>\n DisplayName= <display name>\n password= <password>\n"
},
{
"answer_id": 295602,
"author": "Javier De Pedro",
"author_id": 14053,
"author_profile": "https://Stackoverflow.com/users/14053",
"pm_score": 2,
"selected": false,
"text": "Const SCHEDULED_INSTALLATION = 1\n\nSet objAutoUpdate = CreateObject(\"Microsoft.Update.AutoUpdate\")\nSet objSettings = objAutoUpdate.Settings\n\nobjSettings.NotificationLevel = SCHEDULED_INSTALLATION\nobjSettings.Save\n"
},
{
"answer_id": 299050,
"author": "Javier De Pedro",
"author_id": 14053,
"author_profile": "https://Stackoverflow.com/users/14053",
"pm_score": 4,
"selected": true,
"text": "strComputer = \".\" 'could be any computer, not just the local one '\nSet objWMIService = GetObject(\"winmgmts:\\\\\" & strComputer & \"\\root\\cimv2\")\n\nSet colServiceList = objWMIService.ExecQuery _\n(\"Select * from Win32_Service where Name = 'wuauserv'\")\n\nFor Each objService in colServiceList\n objService.ChangeStartMode(\"Disabled\")\nNext\n Const AU_DISABLED = 1\n\nSet objAutoUpdate = CreateObject(\"Microsoft.Update.AutoUpdate\")\nSet objSettings = objAutoUpdate.Settings\n\nobjSettings.NotificationLevel = AU_DISABLED\nobjSettings.Save\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14053/"
] |
295,566 | <p>I need to display external resources loaded via cross domain requests and make sure to only display "<em>safe</em>" content. </p>
<p>Could use Prototype's <a href="http://www.prototypejs.org/api/string/stripScripts" rel="noreferrer">String#stripScripts</a> to remove script blocks. But handlers such as <code>onclick</code> or <code>onerror</code> are still there.</p>
<p>Is there any library which can at least</p>
<ul>
<li>strip script blocks,</li>
<li>kill DOM handlers,</li>
<li>remove black listed tags (eg: <code>embed</code> or <code>object</code>).</li>
</ul>
<p>So are any JavaScript related links and examples out there?</p>
| [
{
"answer_id": 430240,
"author": "Mike Samuel",
"author_id": 20394,
"author_profile": "https://Stackoverflow.com/users/20394",
"pm_score": 7,
"selected": false,
"text": "var tagBody = '(?:[^\"\\'>]|\"[^\"]*\"|\\'[^\\']*\\')*';\n\nvar tagOrComment = new RegExp(\n '<(?:'\n // Comment body.\n + '!--(?:(?:-*[^->])*--+|-?)'\n // Special \"raw text\" elements whose content should be elided.\n + '|script\\\\b' + tagBody + '>[\\\\s\\\\S]*?</script\\\\s*'\n + '|style\\\\b' + tagBody + '>[\\\\s\\\\S]*?</style\\\\s*'\n // Regular name\n + '|/?[a-z]'\n + tagBody\n + ')>',\n 'gi');\nfunction removeTags(html) {\n var oldHtml;\n do {\n oldHtml = html;\n html = html.replace(tagOrComment, '');\n } while (html !== oldHtml);\n return html.replace(/</g, '<');\n}\n innerHTML innerText textContent <img src=bogus onerror=alert(1337)> onerror"
},
{
"answer_id": 11323186,
"author": "John",
"author_id": 606371,
"author_profile": "https://Stackoverflow.com/users/606371",
"pm_score": 0,
"selected": false,
"text": "function xhtml_cleaner(id)\n{\n var e = document.getElementById(id);\n var f = document.createDocumentFragment();\n f.appendChild(e.cloneNode(true));\n\n var walker = document.createTreeWalker(f,NodeFilter.SHOW_ELEMENT,null,false);\n\n while (walker.nextNode())\n {\n var c = walker.currentNode;\n if (c.hasAttribute('contentEditable')) {c.removeAttribute('contentEditable');}\n if (c.hasAttribute('style')) {c.removeAttribute('style');}\n\n if (c.nodeName.toLowerCase()=='script') {element_del(c);}\n }\n\n alert(new XMLSerializer().serializeToString(f));\n return f;\n}\n\n\nfunction element_del(element_id)\n{\n if (document.getElementById(element_id))\n {\n document.getElementById(element_id).parentNode.removeChild(document.getElementById(element_id));\n }\n else if (element_id)\n {\n element_id.parentNode.removeChild(element_id);\n }\n else\n {\n alert('Error: the object or element \\'' + element_id + '\\' was not found and therefore could not be deleted.');\n }\n}\n"
},
{
"answer_id": 11343433,
"author": "Jeffery To",
"author_id": 311572,
"author_profile": "https://Stackoverflow.com/users/311572",
"pm_score": 5,
"selected": false,
"text": "ant html-sanitizer-minified.js html-css-sanitizer-minified.js html_sanitize(...) importScripts('html-css-sanitizer-minified.js'); // or 'html-sanitizer-minified.js'\n\nvar urlTransformer, nameIdClassTransformer;\n\n// customize if you need to filter URLs and/or ids/names/classes\nurlTransformer = nameIdClassTransformer = function(s) { return s; };\n\n// when we receive some HTML\nself.onmessage = function(event) {\n // sanitize, then send the result back\n postMessage(html_sanitize(event.data, urlTransformer, nameIdClassTransformer));\n};\n"
},
{
"answer_id": 28533511,
"author": "aldel",
"author_id": 2501624,
"author_profile": "https://Stackoverflow.com/users/2501624",
"pm_score": 4,
"selected": false,
"text": "var tagWhitelist_ = {\n 'A': true,\n 'B': true,\n 'BODY': true,\n 'BR': true,\n 'DIV': true,\n 'EM': true,\n 'HR': true,\n 'I': true,\n 'IMG': true,\n 'P': true,\n 'SPAN': true,\n 'STRONG': true\n};\n\nvar attributeWhitelist_ = {\n 'href': true,\n 'src': true\n};\n\nfunction sanitizeHtml(input) {\n var iframe = document.createElement('iframe');\n if (iframe['sandbox'] === undefined) {\n alert('Your browser does not support sandboxed iframes. Please upgrade to a modern browser.');\n return '';\n }\n iframe['sandbox'] = 'allow-same-origin';\n iframe.style.display = 'none';\n document.body.appendChild(iframe); // necessary so the iframe contains a document\n iframe.contentDocument.body.innerHTML = input;\n \n function makeSanitizedCopy(node) {\n if (node.nodeType == Node.TEXT_NODE) {\n var newNode = node.cloneNode(true);\n } else if (node.nodeType == Node.ELEMENT_NODE && tagWhitelist_[node.tagName]) {\n newNode = iframe.contentDocument.createElement(node.tagName);\n for (var i = 0; i < node.attributes.length; i++) {\n var attr = node.attributes[i];\n if (attributeWhitelist_[attr.name]) {\n newNode.setAttribute(attr.name, attr.value);\n }\n }\n for (i = 0; i < node.childNodes.length; i++) {\n var subCopy = makeSanitizedCopy(node.childNodes[i]);\n newNode.appendChild(subCopy, false);\n }\n } else {\n newNode = document.createDocumentFragment();\n }\n return newNode;\n };\n\n var resultElement = makeSanitizedCopy(iframe.contentDocument.body);\n document.body.removeChild(iframe);\n return resultElement.innerHTML;\n};\n href <a href=\"javascript:alert('Oops')\">"
},
{
"answer_id": 36037310,
"author": "AsGoodAsItGets",
"author_id": 134120,
"author_profile": "https://Stackoverflow.com/users/134120",
"pm_score": 2,
"selected": false,
"text": "CKEDITOR.instances['myCKEInstance'].dataProcessor.toHtml(myHTMLstring)\n CKEDITOR.htmlParser"
},
{
"answer_id": 39106919,
"author": "ericsoco",
"author_id": 222356,
"author_profile": "https://Stackoverflow.com/users/222356",
"pm_score": 4,
"selected": false,
"text": "npm sanitize-html \nnpm install --save sanitize-html\n \nvar sanitizeHtml = require('sanitize-html');\n// ...\nvar sanitized = sanitizeHtml(htmlInput);\n \nimport sanitizeHtml from 'sanitize-html';\n// ...\nlet sanitized = sanitizeHtml(htmlInput);\n"
},
{
"answer_id": 54292708,
"author": "Alex from Jitbit",
"author_id": 56621,
"author_profile": "https://Stackoverflow.com/users/56621",
"pm_score": 2,
"selected": false,
"text": "tags/attributes/styles var input = HtmlSanitizer.SanitizeHtml(\"<script> Alert('xss!'); </scr\"+\"ipt>\");\n"
},
{
"answer_id": 66028632,
"author": "Explosion",
"author_id": 14197829,
"author_profile": "https://Stackoverflow.com/users/14197829",
"pm_score": 1,
"selected": false,
"text": "const sanitize = (html, tags = undefined, attributes = undefined) => {\n var attributes = attributes || [\n { attribute: \"src\", tags: \"*\", regex: /^(?:https|http|\\/\\/):/ },\n { attribute: \"href\", tags: \"*\", regex: /^(?!javascript:).+/ },\n { attribute: \"width\", tags: \"*\", regex: /^[0-9]+$/ },\n { attribute: \"height\", tags: \"*\", regex: /^[0-9]+$/ },\n { attribute: \"id\", tags: \"*\", regex: /^[a-zA-Z]+$/ },\n { attribute: \"class\", tags: \"*\", regex: /^[a-zA-Z ]+$/ },\n { attribute: \"value\", tags: [\"INPUT\", \"TEXTAREA\"], regex: /^.+$/ },\n { attribute: \"checked\", tags: [\"INPUT\"], regex: /^(?:true|false)+$/ },\n {\n attribute: \"placeholder\",\n tags: [\"INPUT\", \"TEXTAREA\"],\n regex: /^.+$/,\n },\n {\n attribute: \"alt\",\n tags: [\"IMG\", \"AREA\", \"INPUT\"],\n //\"^\" and \"$\" match beggining and end\n regex: /^[0-9a-zA-Z]+$/,\n },\n { attribute: \"autofocus\", tags: [\"INPUT\"], regex: /^(?:true|false)+$/ },\n { attribute: \"for\", tags: [\"LABEL\", \"OUTPUT\"], regex: /^[a-zA-Z0-9]+$/ },\n ]\n var tags = tags || [\n \"I\",\n \"P\",\n \"B\",\n \"BODY\",\n \"HTML\",\n \"DEL\",\n \"INS\",\n \"STRONG\",\n \"SMALL\",\n \"A\",\n \"IMG\",\n \"CITE\",\n \"FIGCAPTION\",\n \"ASIDE\",\n \"ARTICLE\",\n \"SUMMARY\",\n \"DETAILS\",\n \"NAV\",\n \"TD\",\n \"TH\",\n \"TABLE\",\n \"THEAD\",\n \"TBODY\",\n \"NAV\",\n \"SPAN\",\n \"BR\",\n \"CODE\",\n \"PRE\",\n \"BLOCKQUOTE\",\n \"EM\",\n \"HR\",\n \"H1\",\n \"H2\",\n \"H3\",\n \"H4\",\n \"H5\",\n \"H6\",\n \"DIV\",\n \"MAIN\",\n \"HEADER\",\n \"FOOTER\",\n \"SELECT\",\n \"COL\",\n \"AREA\",\n \"ADDRESS\",\n \"ABBR\",\n \"BDI\",\n \"BDO\",\n ]\n\n attributes = attributes.map((el) => {\n if (typeof el === \"string\") {\n return { attribute: el, tags: \"*\", regex: /^.+$/ }\n }\n let output = el\n if (!el.hasOwnProperty(\"tags\")) {\n output.tags = \"*\"\n }\n if (!el.hasOwnProperty(\"regex\")) {\n output.regex = /^.+$/\n }\n return output\n })\n var el = new DOMParser().parseFromString(html, \"text/html\")\n var elements = el.querySelectorAll(\"*\")\n for (let i = 0; i < elements.length; i++) {\n const current = elements[i]\n let attr_list = get_attributes(current)\n for (let j = 0; j < attr_list.length; j++) {\n const attribute = attr_list[j]\n if (!attribute_matches(current, attribute)) {\n current.removeAttribute(attr_list[j])\n }\n }\n if (!tags.includes(current.tagName)) {\n current.remove()\n }\n }\n return el.documentElement.innerHTML\n function attribute_matches(element, attribute) {\n let output = attributes.filter((attr) => {\n let returnval =\n attr.attribute === attribute &&\n (attr.tags === \"*\" || attr.tags.includes(element.tagName)) &&\n attr.regex.test(element.getAttribute(attribute))\n return returnval\n })\n\n return output.length > 0\n }\n function get_attributes(element) {\n for (\n var i = 0, atts = element.attributes, n = atts.length, arr = [];\n i < n;\n i++\n ) {\n arr.push(atts[i].nodeName)\n }\n return arr\n }\n } * {\n font-family: sans-serif;\n}\ntextarea {\n width: 49%;\n height: 300px;\n padding: 10px;\n box-sizing: border-box;\n resize: none;\n} <h1>Sanitize HTML client side</h1>\n<textarea id='input' placeholder=\"Unsanitized HTML\">\n<!-- This removes both the src and onerror attributes because src is not a valid url. -->\n<img src="error" onerror="alert('XSS')">\n<div id="something_harmless" onload="alert('More XSS')">\n <b>Bold text!</b> and <em>Italic text!</em>, some more text. <del>Deleted text!</del>\n</div>\n <script>\n alert("This would be XSS");\n </script>\n</textarea>\n<textarea id='output' placeholder=\"Sanitized HTML will appear here\" readonly></textarea>\n<script>\n document.querySelector(\"#input\").onkeyup = () => {\n document.querySelector(\"#output\").value = sanitize(document.querySelector(\"#input\").value);\n }\n</script>"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28150/"
] |
295,569 | <p>What I am looking for is a way to programmatically verify a target object has been deallocated. Currently I have an NSLog statement in the dealloc methods of the objects I wish to observe.
The unit testing framework is from the Google Toolbox for the mac, and it working nicely. I am just not certain how to frame this particular test.</p>
| [
{
"answer_id": 297815,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 2,
"selected": false,
"text": "dealloc method_exchangeImplementations dealloc NO"
},
{
"answer_id": 4156216,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 0,
"selected": false,
"text": "YES BOOL getsDeallocatedByReleasing(id object);\n BOOL classGetsDeallocated(Class c, void (^block)(void));\n retain"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24707/"
] |
295,576 | <p>I have a LinqDataSource that I use to calculate the number of rows in a table. I would like to update the value of literal with the number, with the following code, taken from MSDN (<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.linqdatasourcestatuseventargs.totalrowcount.aspx" rel="nofollow noreferrer">linqdatasourcestatuseventargs.totalrowcount.aspx</a>):</p>
<pre><code>protected void linqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
Literal1.Text = e.TotalRowCount.ToString();
}
</code></pre>
<p>By how do I trigger the select event on the data source? The SqlDataSource class has a Select() method so that it can be triggered programmatically in e.g. Page_Load, but the LinqDataSource does not have this method. I currently solved the problem by binding my data source to an empty FormView element, but this is just too ugly.</p>
<p>I feel pretty confident that there is a much nicer way to get the total number of rows into my literal when using LinqToSql, I just don't know how to do so.</p>
<p>The suggestion by tvanfosson, of attaching an method to the data source's selected event, does unfortunately not solve my problem, because the select event is still not triggered when the page loads. (I have, by the way, already attached the _Selected method with the OnSelected attribute, like this)</p>
<pre><code><asp:LinqDataSource ID="linqDataSource1" runat="server"
OnSelected="linqDataSource1_Selected">
</code></pre>
| [
{
"answer_id": 297621,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "public void Page_Load( object sender, EventArgs e )\n{\n linqDataSource1.Selected += LinqDataSource1_Selected;\n}\n\nprotected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)\n{\n Literal1.Text = e.TotalRowCount.ToString();\n}\n"
},
{
"answer_id": 303867,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 1,
"selected": true,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n if (!Page.IsPostBack)\n {\n var context = new MyDataContext();\n\n numberOfModificationsLiteral.Text =\n (\n from modification in context.Modifications\n where modification.Start >= DateTime.Now\n select modification\n ).Count().ToString();\n }\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37147/"
] |
295,579 | <p>I'm looking for the fastest way to determine if a <code>long</code> value is a perfect square (i.e. its square root is another integer): </p>
<ol>
<li>I've done it the easy way, by using the built-in <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#sqrt(double)" rel="noreferrer"><code>Math.sqrt()</code></a>
function, but I'm wondering if there is a way to do it faster by
restricting yourself to integer-only domain.</li>
<li>Maintaining a lookup table is impractical (since there are about
2<sup>31.5</sup> integers whose square is less than 2<sup>63</sup>).</li>
</ol>
<p>Here is the very simple and straightforward way I'm doing it now:</p>
<pre><code>public final static boolean isPerfectSquare(long n)
{
if (n < 0)
return false;
long tst = (long)(Math.sqrt(n) + 0.5);
return tst*tst == n;
}
</code></pre>
<p><sub>Note: I'm using this function in many <a href="http://projecteuler.net/" rel="noreferrer">Project Euler</a> problems. So no one else will ever have to maintain this code. And this kind of micro-optimization could actually make a difference, since part of the challenge is to do every algorithm in less than a minute, and this function will need to be called millions of times in some problems.</sub></p>
<hr>
<p>I've tried the different solutions to the problem:</p>
<ul>
<li>After exhaustive testing, I found that adding <code>0.5</code> to the result of Math.sqrt() is not necessary, at least not on my machine.</li>
<li>The <a href="https://en.wikipedia.org/wiki/Fast_inverse_square_root" rel="noreferrer">fast inverse square root</a> was faster, but it gave incorrect results for n >= 410881. However, as suggested by <a href="https://stackoverflow.com/users/38426/bobbyshaftoe">BobbyShaftoe</a>, we can use the FISR hack for n < 410881.</li>
<li>Newton's method was a good bit slower than <code>Math.sqrt()</code>. This is probably because <code>Math.sqrt()</code> uses something similar to Newton's Method, but implemented in the hardware so it's much faster than in Java. Also, Newton's Method still required use of doubles.</li>
<li>A modified Newton's method, which used a few tricks so that only integer math was involved, required some hacks to avoid overflow (I want this function to work with all positive 64-bit signed integers), and it was still slower than <code>Math.sqrt()</code>.</li>
<li>Binary chop was even slower. This makes sense because the binary chop will on average require 16 passes to find the square root of a 64-bit number.</li>
<li>According to John's tests, using <code>or</code> statements is faster in C++ than using a <code>switch</code>, but in Java and C# there appears to be no difference between <code>or</code> and <code>switch</code>.</li>
<li>I also tried making a lookup table (as a private static array of 64 boolean values). Then instead of either switch or <code>or</code> statement, I would just say <code>if(lookup[(int)(n&0x3F)]) { test } else return false;</code>. To my surprise, this was (just slightly) slower. This is because <a href="https://stackoverflow.com/questions/299079/why-is-this-code-with-several-or-statements-slightly-faster-than-using-a-lookup-t#299205">array bounds are checked in Java</a>. </li>
</ul>
| [
{
"answer_id": 295590,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 6,
"selected": false,
"text": "float Q_rsqrt( float number )\n{\n long i;\n float x2, y;\n const float threehalfs = 1.5F;\n\n x2 = number * 0.5F;\n y = number;\n i = * ( long * ) &y; // evil floating point bit level hacking\n i = 0x5f3759df - ( i >> 1 ); // wtf?\n y = * ( float * ) &i;\n y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration\n // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed\n\n #ifndef Q3_VM\n #ifdef __linux__\n assert( !isnan(y) ); // bk010122 - FPE?\n #endif\n #endif\n return y;\n}\n * (long*) &y 0x5f3759df - (i >> 1); * (float*) &i y = y * ( threehalfs - ( x2 * y * y ) ) * 0.5F"
},
{
"answer_id": 295592,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "(n+1)^2 = n^2 + 2n + 1\n(n-1)^2 = n^2 - 2n + 1\n n^2 n^2 = target n^2 + 2n + 1 > target > n^2 n^2 - 2n + 1 < target < n^2 target < n^2 - 2n + 1 n target > n^2 + 2n + 1 n n target (2^x)^2 = 2^(2x)"
},
{
"answer_id": 295678,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 7,
"selected": false,
"text": "public final static boolean isPerfectSquare(long n)\n{\n if (n < 0)\n return false;\n\n switch((int)(n & 0xF))\n {\n case 0: case 1: case 4: case 9:\n long tst = (long)Math.sqrt(n);\n return tst*tst == n;\n\n default:\n return false;\n }\n}\n int isPerfectSquare(int n)\n{\n int h = n & 0xF; // h is the last hex \"digit\"\n if (h > 9)\n return 0;\n // Use lazy evaluation to jump out of the if statement as soon as possible\n if (h != 2 && h != 3 && h != 5 && h != 6 && h != 7 && h != 8)\n {\n int t = (int) floor( sqrt((double) n) + 0.5 );\n return t*t == n;\n }\n return 0;\n}\n"
},
{
"answer_id": 299183,
"author": "mrzl",
"author_id": 29288,
"author_profile": "https://Stackoverflow.com/users/29288",
"pm_score": 4,
"selected": false,
"text": "Math.sqrt()"
},
{
"answer_id": 327134,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 4,
"selected": false,
"text": "d d b n n b d n % pow(b, d) m n % m"
},
{
"answer_id": 333510,
"author": "Cyrille Ka",
"author_id": 39622,
"author_profile": "https://Stackoverflow.com/users/39622",
"pm_score": 4,
"selected": false,
"text": "boolean isPerfectSquare(long number)\n{\n if (number < 0) return false;\n if (number < 2) return true;\n\n for (int i = 0; ; i++)\n {\n long square = squareTable[i];\n if (square > number) return false;\n while (number % square == 0)\n {\n number /= square;\n }\n if (number == 1) return true;\n }\n}\n"
},
{
"answer_id": 405554,
"author": "David Lehavi",
"author_id": 50761,
"author_profile": "https://Stackoverflow.com/users/50761",
"pm_score": 3,
"selected": false,
"text": "m = N - (N & (N-1));\n m = N & (N-1); // the lawest bit of N\nN /= m;\nbyte = N & 0x0F;\nif ((m % 2) || (byte !=1 && byte !=9))\n return false;\n m = N & (N-1); // the lawest bit of N\nN /= m;\nif ((m % 2) || (N & 0x07 != 1))\n return false;\n"
},
{
"answer_id": 405578,
"author": "Brent.Longborough",
"author_id": 9634,
"author_profile": "https://Stackoverflow.com/users/9634",
"pm_score": 3,
"selected": false,
"text": "def isexactsqrt(v)\n value = v.abs\n residue = value\n root = 0\n onebit = 1\n onebit <<= 8 while (onebit < residue)\n onebit >>= 2 while (onebit > residue)\n while (onebit > 0)\n x = root + onebit\n if (residue >= x) then\n residue -= x\n root = x + onebit\n end\n root >>= 1\n onebit >>= 2\n end\n return (residue == 0)\nend\n #include <iostream> \n\nusing namespace std; \ntypedef unsigned long long int llint;\n\nclass ISqrt { // Integer Square Root\n llint value; // Integer whose square root is required\n llint root; // Result: floor(sqrt(value))\n llint residue; // Result: value-root*root\n llint onebit, x; // Working bit, working value\n\npublic:\n\n ISqrt(llint v = 2) { // Constructor\n Root(v); // Take the root \n };\n\n llint Root(llint r) { // Resets and calculates new square root\n value = r; // Store input\n residue = value; // Initialise for subtracting down\n root = 0; // Clear root accumulator\n\n onebit = 1; // Calculate start value of counter\n onebit <<= (8*sizeof(llint)-2); // Set up counter bit as greatest odd power of 2 \n while (onebit > residue) {onebit >>= 2; }; // Shift down until just < value\n\n while (onebit > 0) {\n x = root ^ onebit; // Will check root+1bit (root bit corresponding to onebit is always zero)\n if (residue >= x) { // Room to subtract?\n residue -= x; // Yes - deduct from residue\n root = x + onebit; // and step root\n };\n root >>= 1;\n onebit >>= 2;\n };\n return root; \n };\n llint Residue() { // Returns residue from last calculation\n return residue; \n };\n};\n\nint main() {\n llint big, i, q, r, v, delta;\n big = 0; big = (big-1); // Kludge for \"big number\"\n ISqrt b; // Make q sqrt generator\n for ( i = big; i > 0 ; i /= 7 ) { // for several numbers\n q = b.Root(i); // Get the square root\n r = b.Residue(); // Get the residue\n v = q*q+r; // Recalc original value\n delta = v-i; // And diff, hopefully 0\n cout << i << \": \" << q << \" ++ \" << r << \" V: \" << v << \" Delta: \" << delta << \"\\n\";\n };\n return 0;\n};\n"
},
{
"answer_id": 424936,
"author": "A. Rex",
"author_id": 3508,
"author_profile": "https://Stackoverflow.com/users/3508",
"pm_score": 11,
"selected": true,
"text": "int64 x if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )\n return false;\nif( x == 0 )\n return true;\n int64 y = x;\ny = (y & 4294967295LL) + (y >> 32); \ny = (y & 65535) + (y >> 16);\ny = (y & 255) + ((y >> 8) & 255) + (y >> 16);\n// At this point, y is between 0 and 511. More code can reduce it farther.\n if( bad255[y] )\n return false;\n// However, I just use a table of size 512\n if((x & 4294967295LL) == 0)\n x >>= 32;\nif((x & 65535) == 0)\n x >>= 16;\nif((x & 255) == 0)\n x >>= 8;\nif((x & 15) == 0)\n x >>= 4;\nif((x & 3) == 0)\n x >>= 2;\n if((x & 7) != 1)\n return false;\n int64 t = 4, r = 1;\nt <<= 1; r += ((x - r * r) & t) >> 1;\nt <<= 1; r += ((x - r * r) & t) >> 1;\nt <<= 1; r += ((x - r * r) & t) >> 1;\n// Repeat until t is 2^33 or so. Use a loop if you want.\n int64 r, t, z;\nr = start[(x >> 3) & 1023];\ndo {\n z = x - r * r;\n if( z == 0 )\n return true;\n if( z < 0 )\n return false;\n t = z & (-z);\n r += (z & t) >> 1;\n if( r > (t >> 1) )\n r = t - r;\n} while( t <= (1LL << 33) );\n z = r - x * x typedef signed long long int int64;\n\nint start[1024] =\n{1,3,1769,5,1937,1741,7,1451,479,157,9,91,945,659,1817,11,\n1983,707,1321,1211,1071,13,1479,405,415,1501,1609,741,15,339,1703,203,\n129,1411,873,1669,17,1715,1145,1835,351,1251,887,1573,975,19,1127,395,\n1855,1981,425,453,1105,653,327,21,287,93,713,1691,1935,301,551,587,\n257,1277,23,763,1903,1075,1799,1877,223,1437,1783,859,1201,621,25,779,\n1727,573,471,1979,815,1293,825,363,159,1315,183,27,241,941,601,971,\n385,131,919,901,273,435,647,1493,95,29,1417,805,719,1261,1177,1163,\n1599,835,1367,315,1361,1933,1977,747,31,1373,1079,1637,1679,1581,1753,1355,\n513,1539,1815,1531,1647,205,505,1109,33,1379,521,1627,1457,1901,1767,1547,\n1471,1853,1833,1349,559,1523,967,1131,97,35,1975,795,497,1875,1191,1739,\n641,1149,1385,133,529,845,1657,725,161,1309,375,37,463,1555,615,1931,\n1343,445,937,1083,1617,883,185,1515,225,1443,1225,869,1423,1235,39,1973,\n769,259,489,1797,1391,1485,1287,341,289,99,1271,1701,1713,915,537,1781,\n1215,963,41,581,303,243,1337,1899,353,1245,329,1563,753,595,1113,1589,\n897,1667,407,635,785,1971,135,43,417,1507,1929,731,207,275,1689,1397,\n1087,1725,855,1851,1873,397,1607,1813,481,163,567,101,1167,45,1831,1205,\n1025,1021,1303,1029,1135,1331,1017,427,545,1181,1033,933,1969,365,1255,1013,\n959,317,1751,187,47,1037,455,1429,609,1571,1463,1765,1009,685,679,821,\n1153,387,1897,1403,1041,691,1927,811,673,227,137,1499,49,1005,103,629,\n831,1091,1449,1477,1967,1677,697,1045,737,1117,1737,667,911,1325,473,437,\n1281,1795,1001,261,879,51,775,1195,801,1635,759,165,1871,1645,1049,245,\n703,1597,553,955,209,1779,1849,661,865,291,841,997,1265,1965,1625,53,\n1409,893,105,1925,1297,589,377,1579,929,1053,1655,1829,305,1811,1895,139,\n575,189,343,709,1711,1139,1095,277,993,1699,55,1435,655,1491,1319,331,\n1537,515,791,507,623,1229,1529,1963,1057,355,1545,603,1615,1171,743,523,\n447,1219,1239,1723,465,499,57,107,1121,989,951,229,1521,851,167,715,\n1665,1923,1687,1157,1553,1869,1415,1749,1185,1763,649,1061,561,531,409,907,\n319,1469,1961,59,1455,141,1209,491,1249,419,1847,1893,399,211,985,1099,\n1793,765,1513,1275,367,1587,263,1365,1313,925,247,1371,1359,109,1561,1291,\n191,61,1065,1605,721,781,1735,875,1377,1827,1353,539,1777,429,1959,1483,\n1921,643,617,389,1809,947,889,981,1441,483,1143,293,817,749,1383,1675,\n63,1347,169,827,1199,1421,583,1259,1505,861,457,1125,143,1069,807,1867,\n2047,2045,279,2043,111,307,2041,597,1569,1891,2039,1957,1103,1389,231,2037,\n65,1341,727,837,977,2035,569,1643,1633,547,439,1307,2033,1709,345,1845,\n1919,637,1175,379,2031,333,903,213,1697,797,1161,475,1073,2029,921,1653,\n193,67,1623,1595,943,1395,1721,2027,1761,1955,1335,357,113,1747,1497,1461,\n1791,771,2025,1285,145,973,249,171,1825,611,265,1189,847,1427,2023,1269,\n321,1475,1577,69,1233,755,1223,1685,1889,733,1865,2021,1807,1107,1447,1077,\n1663,1917,1129,1147,1775,1613,1401,555,1953,2019,631,1243,1329,787,871,885,\n449,1213,681,1733,687,115,71,1301,2017,675,969,411,369,467,295,693,\n1535,509,233,517,401,1843,1543,939,2015,669,1527,421,591,147,281,501,\n577,195,215,699,1489,525,1081,917,1951,2013,73,1253,1551,173,857,309,\n1407,899,663,1915,1519,1203,391,1323,1887,739,1673,2011,1585,493,1433,117,\n705,1603,1111,965,431,1165,1863,533,1823,605,823,1179,625,813,2009,75,\n1279,1789,1559,251,657,563,761,1707,1759,1949,777,347,335,1133,1511,267,\n833,1085,2007,1467,1745,1805,711,149,1695,803,1719,485,1295,1453,935,459,\n1151,381,1641,1413,1263,77,1913,2005,1631,541,119,1317,1841,1773,359,651,\n961,323,1193,197,175,1651,441,235,1567,1885,1481,1947,881,2003,217,843,\n1023,1027,745,1019,913,717,1031,1621,1503,867,1015,1115,79,1683,793,1035,\n1089,1731,297,1861,2001,1011,1593,619,1439,477,585,283,1039,1363,1369,1227,\n895,1661,151,645,1007,1357,121,1237,1375,1821,1911,549,1999,1043,1945,1419,\n1217,957,599,571,81,371,1351,1003,1311,931,311,1381,1137,723,1575,1611,\n767,253,1047,1787,1169,1997,1273,853,1247,413,1289,1883,177,403,999,1803,\n1345,451,1495,1093,1839,269,199,1387,1183,1757,1207,1051,783,83,423,1995,\n639,1155,1943,123,751,1459,1671,469,1119,995,393,219,1743,237,153,1909,\n1473,1859,1705,1339,337,909,953,1771,1055,349,1993,613,1393,557,729,1717,\n511,1533,1257,1541,1425,819,519,85,991,1693,503,1445,433,877,1305,1525,\n1601,829,809,325,1583,1549,1991,1941,927,1059,1097,1819,527,1197,1881,1333,\n383,125,361,891,495,179,633,299,863,285,1399,987,1487,1517,1639,1141,\n1729,579,87,1989,593,1907,839,1557,799,1629,201,155,1649,1837,1063,949,\n255,1283,535,773,1681,461,1785,683,735,1123,1801,677,689,1939,487,757,\n1857,1987,983,443,1327,1267,313,1173,671,221,695,1509,271,1619,89,565,\n127,1405,1431,1659,239,1101,1159,1067,607,1565,905,1755,1231,1299,665,373,\n1985,701,1879,1221,849,627,1465,789,543,1187,1591,923,1905,979,1241,181};\n\nbool bad255[512] =\n{0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,\n 1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,\n 0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,\n 1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,\n 1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,\n 1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,\n 1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,\n 0,0,1,1,0,1,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,\n 1,1,0,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0,1,1,1,\n 0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,1,0,1,1,0,0,1,1,1,1,1,1,1,1,0,1,\n 1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,1,1,0,1,1,1,1,0,0,1,1,1,1,1,1,\n 1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,\n 1,1,1,1,1,1,0,1,1,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,\n 1,1,1,0,0,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,\n 1,0,1,1,1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,1,1,\n 0,0};\n\ninline bool square( int64 x ) {\n // Quickfail\n if( x < 0 || (x&2) || ((x & 7) == 5) || ((x & 11) == 8) )\n return false;\n if( x == 0 )\n return true;\n\n // Check mod 255 = 3 * 5 * 17, for fun\n int64 y = x;\n y = (y & 4294967295LL) + (y >> 32);\n y = (y & 65535) + (y >> 16);\n y = (y & 255) + ((y >> 8) & 255) + (y >> 16);\n if( bad255[y] )\n return false;\n\n // Divide out powers of 4 using binary search\n if((x & 4294967295LL) == 0)\n x >>= 32;\n if((x & 65535) == 0)\n x >>= 16;\n if((x & 255) == 0)\n x >>= 8;\n if((x & 15) == 0)\n x >>= 4;\n if((x & 3) == 0)\n x >>= 2;\n\n if((x & 7) != 1)\n return false;\n\n // Compute sqrt using something like Hensel's lemma\n int64 r, t, z;\n r = start[(x >> 3) & 1023];\n do {\n z = x - r * r;\n if( z == 0 )\n return true;\n if( z < 0 )\n return false;\n t = z & (-z);\n r += (z & t) >> 1;\n if( r > (t >> 1) )\n r = t - r;\n } while( t <= (1LL << 33) );\n \n return false;\n}\n"
},
{
"answer_id": 574455,
"author": "paulmurray",
"author_id": 63189,
"author_profile": "https://Stackoverflow.com/users/63189",
"pm_score": 1,
"selected": false,
"text": "public static void main(String[] args) {\n final int BITS = 16;\n\n BitSet foo = new BitSet();\n\n for(int i = 0; i< (1<<BITS); i++) {\n int sq = (i*i);\n sq = sq & ((1<<BITS)-1);\n foo.set(sq);\n }\n\n System.out.println(\"int[] mayBeASquare = {\");\n\n for(int i = 0; i< 1<<(BITS-5); i++) {\n int kk = 0;\n for(int j = 0; j<32; j++) {\n if(foo.get((i << 5) | j)) {\n kk |= 1<<j;\n }\n }\n System.out.print(\"0x\" + Integer.toHexString(kk) + \", \");\n if(i%8 == 7) System.out.println();\n }\n System.out.println(\"};\");\n}\n"
},
{
"answer_id": 634473,
"author": "Ben",
"author_id": 76649,
"author_profile": "https://Stackoverflow.com/users/76649",
"pm_score": 0,
"selected": false,
"text": "// Divide out powers of 4 using binary search\n\nif((n & 0x3L) == 0) {\n n >>=2;\n\n if((n & 0xffffffffL) == 0)\n n >>= 32;\n if((n & 0xffffL) == 0)\n n >>= 16;\n if((n & 0xffL) == 0)\n n >>= 8;\n if((n & 0xfL) == 0)\n n >>= 4;\n if((n & 0x3L) == 0)\n n >>= 2;\n}\n while ((n & 0x03L) == 0) n >>= 2;\n"
},
{
"answer_id": 634494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "typedef unsigned long long UVLONG\nUVLONG pp1,pp2;\n\nvoid init2() {\n for (int i = 0; i < 64; i++) {\n for (int j = 0; j < 64; j++)\n if (isPerfectSquare(i * 64 + j)) {\n pp1 |= (1 << j);\n pp2 |= (1 << i);\n break;\n }\n }\n cout << \"pp1=\" << pp1 << \",\" << pp2 << \"\\n\"; \n}\n\n\ninline bool isPerfectSquare5(UVLONG x) {\n return pp1 & (1 << (x & 0x3F)) ? isPerfectSquare(x) : false;\n}\n"
},
{
"answer_id": 682088,
"author": "bgiles",
"author_id": 81502,
"author_profile": "https://Stackoverflow.com/users/81502",
"pm_score": 3,
"selected": false,
"text": "2^64 n^2 (n-1) n n^2-1 = (n-1)(n+1) floor(sqrt(x))"
},
{
"answer_id": 905031,
"author": "Jonny Heggheim",
"author_id": 48011,
"author_profile": "https://Stackoverflow.com/users/48011",
"pm_score": 3,
"selected": false,
"text": "if(n < 410881L){...}\n if (n < 11043908100L) {\n //John Carmack hack, converted to Java.\n // See: http://www.codemaestro.com/reviews/9\n int i;\n float x2, y;\n\n x2 = n * 0.5F;\n y = n;\n i = Float.floatToRawIntBits(y);\n //using the magic number from \n //http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf\n //since it more accurate\n i = 0x5f375a86 - (i >> 1);\n y = Float.intBitsToFloat(i);\n y = y * (1.5F - (x2 * y * y));\n y = y * (1.5F - (x2 * y * y)); //Newton iteration, more accurate\n\n sqrt = Math.round(1.0F / y);\n} else {\n //Carmack hack gives incorrect answer for n >= 11043908100.\n sqrt = (long) Math.sqrt(n);\n}\n"
},
{
"answer_id": 2781475,
"author": "finnw",
"author_id": 12048,
"author_profile": "https://Stackoverflow.com/users/12048",
"pm_score": 3,
"selected": false,
"text": "public class SquareTester {\n\n public static boolean isPerfectSquare(long n) {\n if (n < 0) {\n return false;\n } else {\n switch ((byte) n) {\n case -128: case -127: case -124: case -119: case -112:\n case -111: case -103: case -95: case -92: case -87:\n case -79: case -71: case -64: case -63: case -60:\n case -55: case -47: case -39: case -31: case -28:\n case -23: case -15: case -7: case 0: case 1:\n case 4: case 9: case 16: case 17: case 25:\n case 33: case 36: case 41: case 49: case 57:\n case 64: case 65: case 68: case 73: case 81:\n case 89: case 97: case 100: case 105: case 113:\n case 121:\n long i = (n * INV3465) >>> 52;\n if (! good3465[(int) i]) {\n return false;\n } else {\n long r = round(Math.sqrt(n));\n return r*r == n; \n }\n default:\n return false;\n }\n }\n }\n\n private static int round(double x) {\n return (int) Double.doubleToRawLongBits(x + (double) (1L << 52));\n }\n\n /** 3465<sup>-1</sup> modulo 2<sup>64</sup> */\n private static final long INV3465 = 0x8ffed161732e78b9L;\n\n private static final boolean[] good3465 =\n new boolean[0x1000];\n\n static {\n for (int r = 0; r < 3465; ++ r) {\n int i = (int) ((r * r * INV3465) >>> 52);\n good3465[i] = good3465[i+1] = true;\n }\n }\n\n}\n"
},
{
"answer_id": 4351380,
"author": "nabam serbang",
"author_id": 530074,
"author_profile": "https://Stackoverflow.com/users/530074",
"pm_score": 3,
"selected": false,
"text": "int main()\n{\n unsigned int c1=0 ,c2 = 0; \n unsigned int x = 0; \n unsigned int p = 0; \n int k1 = 0; \n scanf(\"%d\",&p); \n if(p % 2 == 0) { \n x = p/2; \n } \n else { \n x = (p/2) +1; \n } \n while(x) \n {\n if((x*x) > p) { \n c1 = x; \n x = x/2; \n }else { \n c2 = x; \n break; \n } \n } \n if((p%2) != 0) \n c2++;\n\n while(c2 < c1) \n { \n if((c2 * c2 ) == p) { \n k1 = 1; \n break; \n } \n c2++; \n } \n if(k1) \n printf(\"\\n Perfect square for %d\", c2); \n else \n printf(\"\\n Not perfect but nearest to :%d :\", c2); \n return 0; \n} \n"
},
{
"answer_id": 8373278,
"author": "Fractaly",
"author_id": 920769,
"author_profile": "https://Stackoverflow.com/users/920769",
"pm_score": 3,
"selected": false,
"text": "public static boolean isSquare(final long val) {\n if ((val & 2) == 2 || (val & 7) == 5) {\n return false;\n }\n if ((val & 11) == 8 || (val & 31) == 20) {\n return false;\n }\n\n if ((val & 47) == 32 || (val & 127) == 80) {\n return false;\n }\n\n if ((val & 191) == 128 || (val & 511) == 320) {\n return false;\n }\n\n // if((val & a == b) || (val & c == d){\n // return false;\n // }\n\n if (!modSq[(int) (val % modSq.length)]) {\n return false;\n }\n\n final long root = (long) Math.sqrt(val);\n return root * root == val;\n}\n"
},
{
"answer_id": 17028771,
"author": "durron597",
"author_id": 1768232,
"author_profile": "https://Stackoverflow.com/users/1768232",
"pm_score": 5,
"selected": false,
"text": "// This is faster because a number is divisible by 2^4 or more only 6% of the time\n// and more than that a vanishingly small percentage.\nwhile((x & 0x3) == 0) x >>= 2;\n// This is effectively the same as the switch-case statement used in the original\n// answer. \nif((x & 0x7) != 1) return false;\n switch-case Math.abs(java.util.Random.nextLong()) 0% Scenario{vm=java, trial=0, benchmark=Internet} 39673.40 ns; ?=378.78 ns @ 3 trials\n33% Scenario{vm=java, trial=0, benchmark=Durron} 37785.75 ns; ?=478.86 ns @ 10 trials\n67% Scenario{vm=java, trial=0, benchmark=DurronTwo} 35978.10 ns; ?=734.10 ns @ 10 trials\n\nbenchmark us linear runtime\n Internet 39.7 ==============================\n Durron 37.8 ============================\nDurronTwo 36.0 ===========================\n\nvm: java\ntrial: 0\n 0% Scenario{vm=java, trial=0, benchmark=Internet} 2933380.84 ns; ?=56939.84 ns @ 10 trials\n33% Scenario{vm=java, trial=0, benchmark=Durron} 2243266.81 ns; ?=50537.62 ns @ 10 trials\n67% Scenario{vm=java, trial=0, benchmark=DurronTwo} 3159227.68 ns; ?=10766.22 ns @ 3 trials\n\nbenchmark ms linear runtime\n Internet 2.93 ===========================\n Durron 2.24 =====================\nDurronTwo 3.16 ==============================\n\nvm: java\ntrial: 0\n DurronTwo Math.sqrt Durron Durron public final static boolean isPerfectSquareDurron(long n) {\n if(n < 0) return false;\n if(n == 0) return true;\n\n long x = n;\n // This is faster because a number is divisible by 16 only 6% of the time\n // and more than that a vanishingly small percentage.\n while((x & 0x3) == 0) x >>= 2;\n // This is effectively the same as the switch-case statement used in the original\n // answer. \n if((x & 0x7) == 1) {\n\n long sqrt;\n if(x < 410881L)\n {\n int i;\n float x2, y;\n\n x2 = x * 0.5F;\n y = x;\n i = Float.floatToRawIntBits(y);\n i = 0x5f3759df - ( i >> 1 );\n y = Float.intBitsToFloat(i);\n y = y * ( 1.5F - ( x2 * y * y ) );\n\n sqrt = (long)(1.0F/y);\n } else {\n sqrt = (long) Math.sqrt(x);\n }\n return sqrt*sqrt == x;\n }\n return false;\n}\n DurronTwo public final static boolean isPerfectSquareDurronTwo(long n) {\n if(n < 0) return false;\n // Needed to prevent infinite loop\n if(n == 0) return true;\n\n long x = n;\n while((x & 0x3) == 0) x >>= 2;\n if((x & 0x7) == 1) {\n long sqrt;\n if (x < 41529141369L) {\n int i;\n float x2, y;\n\n x2 = x * 0.5F;\n y = x;\n i = Float.floatToRawIntBits(y);\n //using the magic number from \n //http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf\n //since it more accurate\n i = 0x5f375a86 - (i >> 1);\n y = Float.intBitsToFloat(i);\n y = y * (1.5F - (x2 * y * y));\n y = y * (1.5F - (x2 * y * y)); //Newton iteration, more accurate\n sqrt = (long) ((1.0F/y) + 0.2);\n } else {\n //Carmack hack gives incorrect answer for n >= 41529141369.\n sqrt = (long) Math.sqrt(x);\n }\n return sqrt*sqrt == x;\n }\n return false;\n}\n public class SquareRootBenchmark {\n public static class Benchmark1 extends SimpleBenchmark {\n private static final int ARRAY_SIZE = 10000;\n long[] trials = new long[ARRAY_SIZE];\n\n @Override\n protected void setUp() throws Exception {\n Random r = new Random();\n for (int i = 0; i < ARRAY_SIZE; i++) {\n trials[i] = Math.abs(r.nextLong());\n }\n }\n\n\n public int timeInternet(int reps) {\n int trues = 0;\n for(int i = 0; i < reps; i++) {\n for(int j = 0; j < ARRAY_SIZE; j++) {\n if(SquareRootAlgs.isPerfectSquareInternet(trials[j])) trues++;\n }\n }\n\n return trues; \n }\n\n public int timeDurron(int reps) {\n int trues = 0;\n for(int i = 0; i < reps; i++) {\n for(int j = 0; j < ARRAY_SIZE; j++) {\n if(SquareRootAlgs.isPerfectSquareDurron(trials[j])) trues++;\n }\n }\n\n return trues; \n }\n\n public int timeDurronTwo(int reps) {\n int trues = 0;\n for(int i = 0; i < reps; i++) {\n for(int j = 0; j < ARRAY_SIZE; j++) {\n if(SquareRootAlgs.isPerfectSquareDurronTwo(trials[j])) trues++;\n }\n }\n\n return trues; \n }\n }\n\n public static void main(String... args) {\n Runner.main(Benchmark1.class, args);\n }\n}\n 0xFFFFFF = 3 x 3 x 5 x 7 x 13 x 17 x 241 if (!goodLookupSquares[(int) ((n & 0xFFFFFFl) + ((n >> 24) & 0xFFFFFFl) + (n >> 48))]) return false;\n + 0xFFFFFF + 0x1FFFFFE 0xFFFFFF ByteBuffer public final static boolean isPerfectSquareDurronThree(long n) {\n if(n < 0) return false;\n if(n == 0) return true;\n\n long x = n;\n while((x & 0x3) == 0) x >>= 2;\n if((x & 0x7) == 1) {\n if (!goodLookupSquares[(int) ((n & 0xFFFFFFl) + ((n >> 24) & 0xFFFFFFl) + (n >> 48))]) return false;\n long sqrt;\n if(x < 410881L)\n {\n int i;\n float x2, y;\n\n x2 = x * 0.5F;\n y = x;\n i = Float.floatToRawIntBits(y);\n i = 0x5f3759df - ( i >> 1 );\n y = Float.intBitsToFloat(i);\n y = y * ( 1.5F - ( x2 * y * y ) );\n\n sqrt = (long)(1.0F/y);\n } else {\n sqrt = (long) Math.sqrt(x);\n }\n return sqrt*sqrt == x;\n }\n return false;\n}\n boolean private static boolean[] goodLookupSquares = null;\n\npublic static void initGoodLookupSquares() throws Exception {\n Scanner s = new Scanner(new File(\"24residues_squares.txt\"));\n\n goodLookupSquares = new boolean[0x1FFFFFE];\n\n while(s.hasNextLine()) {\n int residue = Integer.valueOf(s.nextLine());\n goodLookupSquares[residue] = true;\n goodLookupSquares[residue + 0xFFFFFF] = true;\n goodLookupSquares[residue + 0x1FFFFFE] = true;\n }\n\n s.close();\n}\n Durron 0% Scenario{vm=java, trial=0, benchmark=Internet} 40665.77 ns; ?=566.71 ns @ 10 trials\n33% Scenario{vm=java, trial=0, benchmark=Durron} 38397.60 ns; ?=784.30 ns @ 10 trials\n67% Scenario{vm=java, trial=0, benchmark=DurronThree} 36171.46 ns; ?=693.02 ns @ 10 trials\n\n benchmark us linear runtime\n Internet 40.7 ==============================\n Durron 38.4 ============================\nDurronThree 36.2 ==========================\n\nvm: java\ntrial: 0\n"
},
{
"answer_id": 18686659,
"author": "maaartinus",
"author_id": 581205,
"author_profile": "https://Stackoverflow.com/users/581205",
"pm_score": 9,
"selected": false,
"text": "long goodMask; // 0xC840C04048404040 computed below\n{\n for (int i=0; i<64; ++i) goodMask |= Long.MIN_VALUE >>> (i*i);\n}\n\npublic boolean isSquare(long x) {\n // This tests if the 6 least significant bits are right.\n // Moving the to be tested bit to the highest position saves us masking.\n if (goodMask << x >= 0) return false;\n final int numberOfTrailingZeros = Long.numberOfTrailingZeros(x);\n // Each square ends with an even number of zeros.\n if ((numberOfTrailingZeros & 1) != 0) return false;\n x >>= numberOfTrailingZeros;\n // Now x is either 0 or odd.\n // In binary each odd square ends with 001.\n // Postpone the sign test until now; handle zero in the branch.\n if ((x&7) != 1 | x <= 0) return x == 0;\n // Do it in the classical way.\n // The correctness is not trivial as the conversion from long to double is lossy!\n final long tst = (long) Math.sqrt(x);\n return tst * tst == x;\n}\n long Long.numberOfTrailingZeros double double long double"
},
{
"answer_id": 19385572,
"author": "Colonel Panic",
"author_id": 284795,
"author_profile": "https://Stackoverflow.com/users/284795",
"pm_score": 4,
"selected": false,
"text": "t**2 <= n r**2 = n f(t) = t**2 - n"
},
{
"answer_id": 24721612,
"author": "dfeuer",
"author_id": 1477667,
"author_profile": "https://Stackoverflow.com/users/1477667",
"pm_score": 3,
"selected": false,
"text": "long goodMask; // 0xC840C04048404040 computed below\n{\n for (int i=0; i<64; ++i) goodMask |= Long.MIN_VALUE >>> (i*i);\n}\n\npublic boolean isSquare(long x) {\n // This tests if the 6 least significant bits are right.\n // Moving the to be tested bit to the highest position saves us masking.\n if (goodMask << x >= 0) return false;\n // Remove an even number of trailing zeros, leaving at most one.\n x >>= (Long.numberOfTrailingZeros(x) & (-2);\n // Repeat the test on the 6 least significant remaining bits.\n if (goodMask << x >= 0 | x <= 0) return x == 0;\n // Do it in the classical way.\n // The correctness is not trivial as the conversion from long to double is lossy!\n final long tst = (long) Math.sqrt(x);\n return tst * tst == x;\n}\n if (goodMask << x >= 0) return false;\n"
},
{
"answer_id": 46720183,
"author": "Steve Storck",
"author_id": 8031498,
"author_profile": "https://Stackoverflow.com/users/8031498",
"pm_score": 2,
"selected": false,
"text": "private static final MathContext precision = new MathContext(20);\n\nprivate static final Function<Long, Boolean> isRootWhole = (n) -> {\n long digit = n % 10;\n if (digit == 2 || digit == 3 || digit == 7 || digit == 8) {\n return false;\n }\n return new BigDecimal(n).sqrt(precision).scale() == 0;\n};\n"
},
{
"answer_id": 52522407,
"author": "MWB",
"author_id": 4331279,
"author_profile": "https://Stackoverflow.com/users/4331279",
"pm_score": -1,
"selected": false,
"text": "public static boolean isIntRoot(int number) {\n return isIntRootHelper(number, 1);\n}\n\nprivate static boolean isIntRootHelper(int number, int index) {\n if (number == index) {\n return true;\n }\n if (number < index) {\n return false;\n }\n else {\n return isIntRootHelper(number - 2 * index, index + 1);\n }\n}\n"
},
{
"answer_id": 52864659,
"author": "aventurin",
"author_id": 4917881,
"author_profile": "https://Stackoverflow.com/users/4917881",
"pm_score": 2,
"selected": false,
"text": "/**\n * Test if the given number is a perfect square.\n * @param n Must be greater than 0 and less\n * than Long.MAX_VALUE.\n * @return <code>true</code> if n is a perfect\n * square, or <code>false</code> otherwise.\n */\npublic static boolean isSquare(long n)\n{\n long x1 = n;\n long x2 = 1L;\n\n while (x1 > x2)\n {\n x1 = (x1 + x2) / 2L;\n x2 = n / x1;\n }\n\n return x1 == x2 && n % x1 == 0L;\n}\n Math.sqrt"
},
{
"answer_id": 53948574,
"author": "MWB",
"author_id": 4331279,
"author_profile": "https://Stackoverflow.com/users/4331279",
"pm_score": 2,
"selected": false,
"text": "number solution solution number number solution number solution number solution number solution number solution solution number == solution * solution\n public class SquareRootChecker {\n\n private long number;\n private long initialLow;\n private long initialHigh;\n\n public SquareRootChecker(long number) {\n this.number = number;\n\n initialLow = 1;\n initialHigh = 4;\n if (Long.toString(number).length() % 2 == 0) {\n initialLow = 3;\n initialHigh = 10;\n }\n for (long i = 0; i < Long.toString(number).length() / 2; i++) {\n initialLow *= 10;\n initialHigh *= 10;\n }\n if (Long.toString(number).length() % 2 == 0) {\n initialLow /= 10;\n initialHigh /=10;\n }\n }\n\n public boolean checkSquareRoot() {\n return findSquareRoot(initialLow, initialHigh, number);\n }\n\n private boolean findSquareRoot(long low, long high, long number) {\n long check = low + (high - low) / 2;\n if (high >= low) {\n if (number == check * check) {\n return true;\n }\n else if (number < check * check) {\n high = check - 1;\n return findSquareRoot(low, high, number);\n }\n else {\n low = check + 1;\n return findSquareRoot(low, high, number);\n }\n }\n return false;\n }\n\n}\n long number = 1234567;\nlong square = number * number;\nSquareRootChecker squareRootChecker = new SquareRootChecker(square);\nSystem.out.println(square + \": \" + squareRootChecker.checkSquareRoot()); //Prints \"1524155677489: true\"\n\nlong notSquare = square + 1;\nsquareRootChecker = new SquareRootChecker(notSquare);\nSystem.out.println(notSquare + \": \" + squareRootChecker.checkSquareRoot()); //Prints \"1524155677490: false\"\n"
},
{
"answer_id": 58655853,
"author": "Sajjad Ali Vayani",
"author_id": 12306536,
"author_profile": "https://Stackoverflow.com/users/12306536",
"pm_score": 2,
"selected": false,
"text": "/**\n * Calculate square root if the given number is a perfect square.\n * \n * Approach: Sum of n odd numbers is equals to the square root of n*n, given \n * that n is a perfect square.\n *\n * @param number\n * @return squareRoot\n */\n\npublic static int calculateSquareRoot(int number) {\n\n int sum=1;\n int count =1;\n int squareRoot=1;\n while(sum<number) {\n count+=2;\n sum+=count;\n squareRoot++;\n }\n return squareRoot;\n}\n"
},
{
"answer_id": 71258391,
"author": "FrederickAmpsUp",
"author_id": 17942727,
"author_profile": "https://Stackoverflow.com/users/17942727",
"pm_score": -1,
"selected": false,
"text": "static boolean isPerfectSquare (int input) {\n return Math.sqrt(input) == (int) Math.sqrt(input);\n}\n input true false"
},
{
"answer_id": 74416232,
"author": "Simon Goater",
"author_id": 20460267,
"author_profile": "https://Stackoverflow.com/users/20460267",
"pm_score": 0,
"selected": false,
"text": "a_n+1 = (a_n + x/a_n)/2\n #include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include <math.h>\n\n_Bool isperfectsquare(uint64_t x, uint64_t *isqrtx) {\n // NOTE: isqrtx approximate for non-squares. (benchmarked at 162ns 3GHz i5)\n uint32_t i;\n uint64_t ai;\n ai = 1 + ((x & 0xffff000000000000) >> 32) + ((x & 0xffff00000000) >> 24) + ((x & 0xffff0000) >> 16);\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = (ai + x/ai)/2;\n ai = ai & 0xffffffff;\n if (isqrtx != NULL) isqrtx[0] = ai;\n return ai*ai == x;\n}\n\nvoid main() {\n\n uint64_t x, isqrtx;\n uint64_t i;\n for (i=1; i<0x100000000; i++) {\n if (!isperfectsquare(i*i, &isqrtx)) {\n printf(\"Failed at %li\", i);\n exit(1);\n }\n }\n printf(\"All OK.\\n\");\n} \n simon@simon-Inspiron-N5040:~$ time ./isqrt.bin \nAll OK.\n\nreal 11m37.096s\nuser 11m35.053s\nsys 0m0.272s\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
295,584 | <p>I've found a few pages (some that even link to a number of other pages) on the Microsoft website that I bookmarked last night for reading today, but I'm curious as to other good non-Microsoft resources for discussing ASP.NET web applications, both Forms and MVC (including comparisons/contrasts between the two).</p>
| [
{
"answer_id": 295792,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 3,
"selected": true,
"text": "</shamelessPlug>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
295,593 | <p>I have a List containing several keywords.
I foreach through them building my linq query with them like so (boiled down to remove the code noise):</p>
<pre><code>List<string> keys = FillKeys()
foreach (string key in keys){
q = q.Where(c => c.Company.Name.Contains(key));
}
</code></pre>
<p>When I now make my keys contain 2 keys that return results seperatly, but can never occure together (every item in q is either "xyz" or "123", never "123" AND "xyz"), I still get results. The resultset is then the same as the last string it got to.</p>
<p>I had a look at the linq query and it appears it creates the correct sql, but it replaces @p1 AND @p2 both by the same (last itterated) value.</p>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 295597,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "key List<string> keys = FillKeys()\nforeach (string key in keys){\n string copy = key;\n q = q.Where(c => c.Company.Name.Contains(copy));\n}\n"
},
{
"answer_id": 295605,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "List<string> keys = FillKeys()\nforeach (string key in keys){\n string tmp = key;\n q = q.Where(c => c.Company.Name.Contains(tmp));\n}\n"
},
{
"answer_id": 14087372,
"author": "komizo",
"author_id": 1792434,
"author_profile": "https://Stackoverflow.com/users/1792434",
"pm_score": 1,
"selected": false,
"text": " static void Main()\n {\n IEnumerable<char> query = \"aaa bbb ccc\";\n string lettersToRemove = \"ab\";\n\n Console.WriteLine(\"\\nOK with foreach:\");\n foreach (var item in lettersToRemove)\n {\n query = query.Where(c => c != item); \n } \n foreach (char c in query) Console.Write(c);\n\n //OK:\n Console.WriteLine(\"\\nOK with foreach and local temp variable:\");\n query = \"aaa bbb ccc\";\n\n foreach (var item in lettersToRemove)\n {\n var tmp = item;\n query = query.Where(c => c != tmp);\n } \n foreach (char c in query) Console.Write(c);\n\n\n /*\n An IndexOutOfRangeException is thrown because:\n firstly compiler iterates the for loop treating i as an outsite declared variable \n when the query is finnaly invoked the same variable of i is captured (lettersToRemove[i] equals 3) which generates IndexOutOfRangeException\n\n The following program writes aaa ccc instead of writing ccc:\n Each iteration gets the same variable=\"C\", i (last one frome abc). \n */\n\n //Console.WriteLine(\"\\nNOK with for loop and without temp variable:\");\n //query = \"aaa bbb ccc\";\n\n //for (int i = 0; i < lettersToRemove.Length; i++)\n //{\n // query = query.Where(c => c != lettersToRemove[i]);\n //}\n //foreach (char c in query) Console.Write(c);\n\n /*\n OK\n The solution is to assign the iteration variable to a local variable scoped inside the loop\n This causes the closure to capture a different variable on each iteration.\n */\n Console.WriteLine(\"\\nOK with for loop and with temp variable:\");\n query = \"aaa bbb ccc\";\n\n for (int i = 0; i < lettersToRemove.Length; i++)\n {\n var tmp = lettersToRemove[i];\n query = query.Where(c => c != tmp);\n }\n foreach (char c in query) Console.Write(c);\n } \n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
295,600 | <p>Assume that you have a running SQL Server Express instance named (local)\SQLEXPRESS. Its database folder is c:\program files\Microsoft SQL Server\MSSQL.1\MSSQL\Data. </p>
<p>How can VBScript be used to retrieve that folder? </p>
<p>Maybe by using SMO? And if so, how? <- Forget that. SMO uses .NET. Only possible in PowerShell.</p>
<hr>
<p><strong>Update:</strong>
The reason for this is, that I am developing an MSI setup that uses a custom action (call to a .NET based assembly) for attaching mdf Files to an existing SQL server instance. for this, the .mdf files get transferred from the installation medium to the hard drive. So the setup needs to know where to place the files.</p>
<p>Since I would like to support the standards, I need to place the files into the common data folder.</p>
<hr>
<p><strong>Update:</strong>
When selecting a SQL server instance in InstallShield, the Property IS _ SQLSERVER _ SERVER is set with the instance name.</p>
<p>I found out, that I can query the registry under HKLM\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL to get the SQL name for the instance name (e.g. SQLEXPRESS -> MSSQL.1).</p>
<p>With this information, I can query HKLM\Software\Microsoft\Microsoft SQL Server\MSSQL.1\Setup to retrieve the SQLDataRoot key. When I append a \Data to the value found here, I have the folder, I was looking for. </p>
<p>However, is there a better way?</p>
| [
{
"answer_id": 295738,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "root\\Microsoft\\SqlServer"
},
{
"answer_id": 45663755,
"author": "Codename K",
"author_id": 2267382,
"author_profile": "https://Stackoverflow.com/users/2267382",
"pm_score": 0,
"selected": false,
"text": "strName = \"(local)\\SQLEXPRESS\"\narrNames = Split(strName, \"\\\")\nintIndex = Ubound(arrNames)\nstrFile = arrNames(intIndex)\nstrFile = trim(strFile)\n\nif strFile <> \"\" then\n reg = readFromRegistry(\"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SQL Server\\\" & strFile & \"\\Setup\\SQLPath\", \"\")\n reg = trim(reg)\n if reg <> \"\" then\n reg = reg & \"\\DATA\"\n end if\nend if\n\nmsgbox reg\n\nfunction readFromRegistry (strRegistryKey, strDefault )\n Dim WSHShell, value\n\n On Error Resume Next\n Set WSHShell = CreateObject(\"WScript.Shell\")\n value = WSHShell.RegRead( strRegistryKey )\n\n if err.number <> 0 then\n readFromRegistry= strDefault\n else\n readFromRegistry=value\n end if\n\n set WSHShell = nothing\nend function\n reg strName"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23369/"
] |
295,611 | <p>I have some questions about basic CSS that I was unable to understand or find an answer for.</p>
<p>First, I tried placing 3 div tags within another div tag. The first main div tag containing the 3 other tags had nothing set for it except a size, which was <code>400px</code> by <code>400px</code>. Of the other 3 divs inside, all were <code>20px</code> by <code>20px</code>, and 1 was assigned <code>float:left</code>, and the other two were assigned a style that was float right. All attributes were defined within a style, and the two divs that were <code>float:right</code> were assigned the same style. My problem is that out of the 2 divs, the one that came last in the code, would appear first in a browser, and I did not understand the reasoning for this.</p>
<p>Here is the code:</p>
<pre><code><html>
<head>
<style>
#main{
border: red 4px dashed;
width: 25%
height: 25%,
}
#left{
float: left;
width: 20px;
height: 20px,
}
#right{
float: right;
width: 20px;
height: 20px,
}
</style>
</head>
<body>
<div id="main">
<div id="left">1</div>
<div id="right">2</div>
<div id="right">3</div>
</div>
</body>
</head>
</html>
</code></pre>
| [
{
"answer_id": 295633,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 0,
"selected": false,
"text": "...\n<div class=\"right\">2</div>\n<div class=\"right\">3</div>\n...\n #right .right"
},
{
"answer_id": 295634,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 0,
"selected": false,
"text": "float: right; \n\nwidth: 20px;\n\nheight: 20px,\n\n}\n"
},
{
"answer_id": 295637,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "#main{ \n border: red 4px dashed;\n width: 25%; /* <-- Missing ; */\n height: 25%; /* <-- change , to ; */\n}\n#left{ \n float: left; \n width: 20px;\n height: 20px; /* <-- change , to ; */\n}\n#right{ \n float: right; \n width: 20px;\n height: 20px; /* <-- change , to ; */\n}\n"
},
{
"answer_id": 29796620,
"author": "Mohit Ranpura",
"author_id": 3494098,
"author_profile": "https://Stackoverflow.com/users/3494098",
"pm_score": -1,
"selected": false,
"text": "<html>\n<head>\n<style>\n#main {\n border: 4px dashed red;\n display: block;\n overflow: hidden;\n}\n#left {\n float: left;\n width: 20px;\n height: 20px,\n}\n#right {\n float: right;\n width: 20px;\n height: 20px,\n}\n</style>\n</head>\n<body>\n<div id=\"main\">\n <div id=\"left\">1</div>\n <div id=\"right\">3</div>\n <div id=\"right\">2</div>\n</div>\n</body>\n</head>\n</html>\n"
},
{
"answer_id": 57818735,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<div id=\"main\">\n <div id=\"left\">1</div>\n <div id=\"right\">3</div>\n <div id=\"right\">2</div>\n </div>\n"
},
{
"answer_id": 59202238,
"author": "Kunal Raut",
"author_id": 10652194,
"author_profile": "https://Stackoverflow.com/users/10652194",
"pm_score": 0,
"selected": false,
"text": "<div class=\"right\">2</div>\n<div class=\"right\">3</div>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
295,615 | <p>I Have a problem where I occasionally (i.e. not always) see the below error popup from the Debug Flash Player after launching my app:</p>
<pre><code>Error #2044: Unhandled securityError:. text=Error #2048: Security sandbox violation: http://example.com/myApp.swf cannot load data from localhost:4499.
at org.mydomain.mypackage::MyClassUsingSocket()
at MyMainApplicationClass$cinit()
at global$init()
at global$init()
at flash.system::ApplicationDomain/hasDefinition()
at mx.managers::SystemManager/getDefinitionByName()
at _MyMainApplicationClass_mx_managers_SystemManager/create()
at mx.managers::SystemManager/initializeTopLevelWindow()
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler()
</code></pre>
<p>I have some code in this app that tries to connect to <code>localhost:4499</code> via a <code>Socket</code>, and this error occurs when the socket server is not running and listening for the connections, <em>which is to be expected</em>. What I <em>don't</em> understand, however, is <strong>why Flash Player is complaining about unhandled securityErrors when I have try/catch blocks to catch the <code>SecurityError</code>s</strong> when trying to connect the socket (as well as listeners for the <code>SecurityErrorEvents</code>, which this error message doesn't seem to point to, though).</p>
<p>The constructor of the relevant class is below:</p>
<pre><code>/**
* Constructor.
*/
public function MyClassUsingSocket(aHost:String = null, aPort:int = -1):void
{
super();
var hostToConnectTo:String = (aHost != null) ? aHost : DEFAULT_HOST;
var portToConnectTo:int = (aPort != -1) ? aPort : DEFAULT_PORT;
try
{
_out_socket = new Socket();
// note: the event handlers used below are private functions within the same class
_out_socket.addEventListener(Event.CONNECT, _socketConnectEventHandler, false,0,true);
_out_socket.addEventListener(IOErrorEvent.IO_ERROR, _socketIOErrorEventHandler, false,0,true);
_out_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _socketSecurityErrorEventHandler, false,0,true);
_out_socket.connect(hostToConnectTo, portToConnectTo);
}
catch(e:IOError)
{
enabled = false;
}
catch(e:SecurityError)
{
enabled = false;
}
}
</code></pre>
<p>Any ideas on why this might be occurring? What am I missing?</p>
| [
{
"answer_id": 298805,
"author": "geraldalewis",
"author_id": 7501,
"author_profile": "https://Stackoverflow.com/users/7501",
"pm_score": -1,
"selected": false,
"text": "\n\n try\n {\n _out_socket = new Socket();\n\n // note: the event handlers used below are private functions within the same class\n _out_socket.addEventListener(Event.CONNECT, _socketConnectEventHandler, false,0,true);\n _out_socket.addEventListener(IOErrorEvent.IO_ERROR, _socketIOErrorEventHandler, false,0,true);\n _out_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, _socketSecurityErrorEventHandler, false,0,true);\n\n _out_socket.connect(hostToConnectTo, portToConnectTo);\n }\n catch(e:IOError)\n {\n enabled = false;\n }\n catch(e:SecurityError)\n {\n enabled = false;\n }\n catch( e:Error )\n {\n trace( e );\n }\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4111/"
] |
295,620 | <p>Given the following Delphil DLL declaration</p>
<pre><code>function csd_HandleData(aBuf: PChar; aLen: integer): integer; stdcall;
</code></pre>
<p>what would be the VB6 declaration to use it?</p>
<p>I've tried a variety of declarations, e.g.</p>
<pre><code>Declare Function csd_HandleData Lib "chsdet.dll" (ByVal aBuf As String, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Long, ByVal aLen As Integer)
Declare Function csd_HandleData Lib "chsdet.dll" (aBuf As Byte, ByVal aLen As Integer)
</code></pre>
<p>with the relevant code to suit the parameters, but nothing seems to work, i.e. the Delphi debugger says I have a too-largish value in aLen and a null string in aBuf.</p>
<p>I am working toward using a TypeLib to drive the connection, but was prototyping with Declares.</p>
| [
{
"answer_id": 295638,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 3,
"selected": true,
"text": "Declare Function csd_HandleData Lib \"chsdet.dll\" (ByVal aBuf As String, \nByVal aLen As Integer) As Integer\n"
},
{
"answer_id": 295639,
"author": "DonOctavioDelFlores",
"author_id": 22694,
"author_profile": "https://Stackoverflow.com/users/22694",
"pm_score": -1,
"selected": false,
"text": "Declare Function csd_HandleData Lib \"chsdet.dll\" (**ByReference <--guessing here :D** aBuf As String, ByVal aLen As Integer)\n"
},
{
"answer_id": 295643,
"author": "remonedo",
"author_id": 11920,
"author_profile": "https://Stackoverflow.com/users/11920",
"pm_score": 0,
"selected": false,
"text": "aLen Declare Function csd_HandleData Lib \"chsdet.dll\" (aBuf As Byte, ByVal aLen As Long) As Long\n"
},
{
"answer_id": 298096,
"author": "Mohammed Nasman",
"author_id": 24462,
"author_profile": "https://Stackoverflow.com/users/24462",
"pm_score": 1,
"selected": false,
"text": "Declare Function csd_HandleData Lib \"chsdet.dll\" (ByVal aBuf As String, ByVal aLen As long) as long\n"
},
{
"answer_id": 298105,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "// Generated .IDL file (by the OLE/COM Object Viewer)\n// \n// typelib filename: chsdet.tlb\n\n[\n uuid(316A83D7-8BF4-490E-BDDE-75EBC332C355),\n version(1.0),\n helpstring(\"Charset Detector - as the name says - is a stand alone executable module for automatic charset detection of a given text.\\r\\n\\t\\r\\nIt can be useful for internationalisation support in multilingual applications such as web-script editors or Unicode editors.\\r\\n\\t\\r\\nGiven input buffer will be analysed to guess used encoding. The result can be used as control parameter for charset conversation procedure.\\r\\n\\t\\r\\nCharset Detector can be compiled (and hopefully used) for MS Windows (as dll - dynamic link library) or Linux.\\r\\n\\t\\r\\nBased on Mozilla's i18n component - http://www.mozilla.org/projects/intl/. \\r\\n\\r\\nCharset Detector is open source project and distributed under Lesser GPL.\\r\\nSee the GNU Lesser General Public License for more details - http://www.opensource.org/licenses/lgpl-license.php\\r\\n\\r\\nNikolaj Yakowlew \\xFFFFFFA9 2006-2008 \\r\\nTypeLib by Bruce M. Axtens, 2008.\")\n]\nlibrary CHSDET\n{\n // TLib : // Forward declare all types defined in this typelib\n\n [\n dllname(\"CHSDET.dll\"),\n version(1.0),\n helpstring(\"Functions in CHSDET.DLL\")\n ]\n module CHSDETFunctions {\n [entry(0x60000000), helpstring(\"Returns rAbout record (qv)\")]\n void _stdcall GetAbout([in, out] rAbout* AboutRec);\n [entry(0x60000001), helpstring(\"Reset detector. Prepares for new analysis.\")]\n void _stdcall Reset();\n [entry(0x60000002), helpstring(\"Analyse given buffer of specified length.\n\nReturn value is of eHandleDataErrors, either \nNS_ERROR_OUT_OF_MEMORY (Unable to create internal objects) or NS_OK.\n\nFunction can be called more that one time to continue guessing. Charset Detector remembers last state until Reset called.\")]\n void _stdcall HandleData(\n [in] BSTR aBuf, \n [in] short aLen, \n [out, retval] short* retVal);\n [entry(0x60000003), helpstring(\"Returns either TRUE (Charset Detector is sure about text encoding.) or FALSE.\n\nNB: If input buffer is smaller then 1K, Charset Detector returns FALSE.\")]\n void _stdcall IsDone([out, retval] short* retVal);\n [entry(0x60000004), helpstring(\"Signal data end. If Charset Detector hasn't sure result (IsDone = FALSE) the best guessed encoding will be set as result.\")]\n void _stdcall DataEnd();\n [entry(0x60000005), helpstring(\"Returns guessed charset as rCharsetInfo record\")]\n void _stdcall GetDetectedCharset([out, retval] rCharsetInfo* retVal);\n [entry(0x60000006), helpstring(\"Returns all supported charsets in form \"0x0A Name - CodePage\"\")]\n void _stdcall GetKnownCharsets(\n [in, out] long* sList, \n [out, retval] long* retVal);\n [entry(0x60000007), helpstring(\"Return eBOMKind value matching byte order mark (if any) of input data.\")]\n void _stdcall GetDetectedBOM([out, retval] eBOMKind* retVal);\n [entry(0x60000008), helpstring(\"Remove CodePage from consideration as a possible match\")]\n void _stdcall DisableCharsetCP([in] long CodePage);\n };\n\n typedef [uuid(91694067-30AB-44A9-A210-F5602935475F)]\n struct tagrAbout {\n\nlong lMajor;\n\nlong lMinor;\n\nlong lRelease;\n\nlong sAbout;\n } rAbout;\n\n typedef [uuid(3C8B7420-D40B-458B-8DE8-9B3D28607396)]\n enum {\n BOM_Not_Found = 0,\n BOM_UCS4_BE = 1,\n BOM_UCS4_LE = 2,\n BOM_UCS4_2143 = 3,\n BOM_UCS4_3412 = 4,\n BOM_UTF16_BE = 5,\n BOM_UTF16_LE = 6,\n BOM_UTF8 = 7\n } eBOMKind;\n\n typedef [uuid(9B231DEF-93FB-440D-B06B-D760AECE09D0)]\n struct tagrCharsetInfo {\n\nlong Name;\n\nshort CodePage;\n\nlong Language;\n } rCharsetInfo;\n\n typedef enum {\n NS_OK = 0,\n NS_ERROR_OUT_OF_MEMORY = -2147024882\n } eHandleDataErrors;\n};\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
295,621 | <p>I have an iframe inside my main page. There is a modalpopup inside the iframe page. So when the modalpopup is shown, the parent of the modalpopup is the iframe body and the main page parent body. Thus the overlay only covers the iframe and not the entire page.</p>
<p>I tried moving the modalpopup from the iframe to the parent windows body element (or any other element inside the parents body) using jQuery. I am getting an invalid argument error.</p>
<p>How do I show a modalpopup from an page inside iframe and it should cover the entire document, parent document as well?</p>
<p><strong>Update:</strong> </p>
<p>Since few users are interested in achieving the same behavior .. here is the workaround</p>
<p>The best workaround that I would suggest would be to have the modalpopup in the main page .. and then invoke it from the iframe .. say something like this ..</p>
<pre><code>/* function in the main(parent) page */
var _onMyModalPopupHide = null;
function pageLoad(){
// would be called by ScriptManager when page loads
// add the callback that will be called when the modalpopup is closed
$find('MyModalPopupBehaviorID').add_hidden(onMyModalPopupHide);
}
// will be invoked from the iframe to show the popup
function ShowMyModalPopup(callback) {
_onMyModalPopupHide = callback;
$find('MyModalPopupBehaviorID').show();
}
/* this function would be called when the modal popup is closed */
function onMyModalPopupHide(){
if (typeof(_onMyModalPopupHide) === "function") {
// fire the callback function
_onMyModalPopupHide.call(this);
}
}
/* functions in the page loaded in the iframe */
function ShowPopup(){
if(typeof(window.parent.ShowMyModalPopup) === "function") {
window.parent.ShowMyModalPopup.apply(this, [OnPopupClosed]);
}
}
// will be invoked from the parent page .. after the popup is closed
function OnPopupClosed(){
// do something after the modal popup is closed
}
</code></pre>
<p>Hope it helps</p>
| [
{
"answer_id": 23271920,
"author": "Adeel Rizvi",
"author_id": 3569277,
"author_profile": "https://Stackoverflow.com/users/3569277",
"pm_score": 0,
"selected": false,
"text": "<button type=\"button\" id=\"popup\">Show Popup</button>\n<br />\n<br />\n<iframe src=\"your url\" style=\"width: 100%; height:400px;\"></iframe>\n // Author : Adeel Rizvi\n// It's just a attempt to get the desire element inside the iframe show outside from iframe as a model popup window.\n\n// As i don't have the access inside the iframe for now, so I'll grab the desire element from parent window.\n\n(function () {\n $.fn.toPopup = function () {\n return this.each(function () {\n\n // Create dynamic div and set its properties\n var popUpDiv = $(\"<div />\", {\n class: \"com_popup\",\n width: \"100%\",\n height: window.innerHeight\n });\n\n // append all the html into newly created div\n $(this).appendTo(popUpDiv);\n\n // check if we are in iframe or not\n if ($('body', window.parent.document).length !== 0) {\n\n // get iframe parent window body element\n var parentBody = $('body', window.parent.document);\n\n // set height according to parent window body\n popUpDiv.css(\"height\", parentBody.height());\n\n // add newly created div into parent window body\n popUpDiv.appendTo(parentBody);\n\n } else {\n\n // if not inside iframe then add to current window body\n popUpDiv.appendTo($('body'));\n }\n\n });\n }\n})();\n\n$(function(){\n $(\"#popup\").click(function () {\n\n // find element inside the iframe\n var bodyDiv = $('iframe').contents().find('YourSelector');\n\n\n if (bodyDiv.length !== 0) {\n\n // Show\n $(bodyDiv).toPopup();\n\n } else {\n alert('Sorry!, no element found');\n }\n\n });\n});\n .com_popup {\n background-color: Blue;\n left: 0;\n position: absolute;\n top: 0;\n z-index: 999999;\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25138/"
] |
295,626 | <p>I have a .net 3.5 WinForms application that runs fine on my machine, but on another machine it immediately crashes with a system.io.fileloadexception. Unfortunately, there are absolutely no details on which file failed to load, so I do not know where the problem actually is.</p>
<p>I believe I know which one it could be (SQL Server Compact edition), but before I aimlessly hunt, I wonder if there is a proper way to find out what caused the fileloadexception, other than using FileMon from SysInternals.</p>
<p>The only error message is:</p>
<blockquote>
<p>EventType clr20r3, P1 myapplication.exe, P2 2.1.0.0, P3 490eca78, P4 myapplication, P5 2.1.0.0, P6 490eca78, P7 2e, P8 21, P9 system.io.fileloadexception, P10 NIL.</p>
</blockquote>
| [
{
"answer_id": 295654,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": false,
"text": "Main() Main() Main() Main() MainCore() Main() MainCore()"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
295,628 | <p>Our team is using a SecureRandom to generate a list of key pairs (the SecureRandom is passed to a KeyPairGenerator). We cannot agree on which of the following two options to use:</p>
<ol>
<li><p>Create a new instance every time we need to generate a key pair</p></li>
<li><p>Initialize a static instance and use it for all key pairs</p></li>
</ol>
<p>Which approach is generally better and <em>why</em>?</p>
<p>ADDED: My gut feeling is that the second option is more secure. But my only argument is a theoretical attack based on the assumption that the pseudorandomness is derived from the current timestamp: someone may see the creation time of the key pair, guess timestamps in the surrounding time interval, compute the possible pseudorandom sequences, and obtain the key material.</p>
<p>ADDED: My assumption about determinism based on a timestamp was wrong. That's the difference between Random and SecureRandom. So, it looks like the answer is: in terms of security it doesn't really matter.</p>
| [
{
"answer_id": 295652,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 5,
"selected": true,
"text": "java.util.Random java.security.SecureRandom java.util.Random SecureRandom"
},
{
"answer_id": 1304948,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "SecureRandom /dev/random SecureRandom SecureRandom nextBytes generateSeed SecureRandom SecureRandom SecureRandom() /dev/random nextBytes generateSeed SecureRandom"
},
{
"answer_id": 3278399,
"author": "Matthew McCullough",
"author_id": 56039,
"author_profile": "https://Stackoverflow.com/users/56039",
"pm_score": 4,
"selected": false,
"text": "mySecureRandom.setSeed(mySecureRandom.generateSeed(someInt));\n"
},
{
"answer_id": 69588297,
"author": "Charlie Reitzel",
"author_id": 4863347,
"author_profile": "https://Stackoverflow.com/users/4863347",
"pm_score": 0,
"selected": false,
"text": "SecureRandom warm up \n-----------------------------\ndefault seed - re-use - 1807 ms\nexplicit seed - re-use - 835 ms\nconstant seed - new every time - 1044 ms\ndefault seed - new every time - 1621 ms\n-----------------------------\ninteration 0\n-----------------------------\ndefault seed - re-use - 412 ms\nexplicit seed - re-use - 418 ms\nconstant seed - new every time - 955 ms\ndefault seed - new every time - 1676 ms\n-----------------------------\ninteration 1\n-----------------------------\ndefault seed - re-use - 389 ms\nexplicit seed - re-use - 369 ms\nconstant seed - new every time - 893 ms\ndefault seed - new every time - 1498 ms\n package foo;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.junit.Assert.assertTrue;\n\nimport java.security.SecureRandom;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.junit.BeforeClass;\nimport org.junit.Test;\n\npublic class SecureRandomTest {\n \n static long elapsedMillis( long startNs ) {\n long now = System.nanoTime();\n return (now - startNs) / 1_000_000;\n }\n final static long seed = 123456789123456L;\n final static int nIter = 1000000;\n \n public static void main(String[] args) {\n warmup();\n SecureRandomTest test = new SecureRandomTest();\n for ( int ix = 0; ix < 5; ++ix ) {\n test.run(ix);\n }\n }\n \n void run(int ix) {\n System.out.printf( \"interation %d\\n-----------------------------\\n\", ix);\n secure_random_default_seed_reuse();\n secure_random_constant_seed_reuse();\n secure_random_constant_seed();\n secure_random_default_seed();\n System.out.println(\"-----------------------------\");\n }\n\n /* Warm up JVM/JIT */\n @BeforeClass\n public static void warmup() {\n new SecureRandomTest().run(-1);\n }\n\n @Test\n public void secure_random_constant_seed() {\n long started = System.nanoTime();\n int nDupes = 0, ix = 0;\n Set<Long> generated = new HashSet<>(nIter);\n for ( /**/; ix < nIter; ++ix) {\n SecureRandom rand = new SecureRandom();\n rand.setSeed(seed);\n long xRand = rand.nextLong();\n if ( !generated.add(xRand) ) {\n ++nDupes;\n }\n }\n assertEquals( \"Unexpected # of dupes \" + nDupes + \", ix == \" + ix, nIter-1, nDupes );\n System.out.printf( \"constant seed - new every time - %d ms\\n\", elapsedMillis(started) );\n }\n\n @Test\n public void secure_random_constant_seed_reuse() {\n long started = System.nanoTime();\n int nDupes = 0, ix = 0;\n SecureRandom rand = new SecureRandom();\n rand.setSeed(seed);\n Set<Long> generated = new HashSet<>(nIter);\n for ( /**/; ix < nIter; ++ix) {\n long xRand = rand.nextLong();\n if ( !generated.add(xRand) ) {\n ++nDupes;\n }\n }\n assertTrue( \"Unexpected # of dupes \" + nDupes + \", ix == \" + ix, 0 == nDupes );\n System.out.printf( \"explicit seed - re-use - %d ms\\n\", elapsedMillis(started) );\n }\n\n @Test\n public void secure_random_default_seed() {\n long started = System.nanoTime();\n int nDupes = 0, ix = 0;\n Set<Long> generated = new HashSet<>(nIter);\n for ( /**/; ix < nIter; ++ix) {\n long xRand = new SecureRandom().nextLong();\n if ( !generated.add(xRand) ) {\n ++nDupes;\n }\n }\n assertTrue( \"Unexpected # of dupes \" + nDupes + \", ix == \" + ix, 0 == nDupes );\n System.out.printf( \"default seed - new every time - %d ms\\n\", elapsedMillis(started) );\n }\n\n @Test\n public void secure_random_default_seed_reuse() {\n long started = System.nanoTime();\n int nDupes = 0, ix = 0;\n SecureRandom rand = new SecureRandom();\n Set<Long> generated = new HashSet<>(nIter);\n for ( /**/; ix < nIter; ++ix) {\n long xRand = rand.nextLong();\n if ( !generated.add(xRand) ) {\n ++nDupes;\n }\n }\n assertTrue( \"Unexpected # of dupes \" + nDupes + \", ix == \" + ix, 0 == nDupes );\n System.out.printf( \"default seed - re-use - %d ms\\n\", elapsedMillis(started) );\n }\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23109/"
] |
295,629 | <p>I'm writing an application which has to be configurable to connect to Oracle, SQL Server and MySQL depending on client whim.</p>
<p>Up till now I'd been planning on using the JDBC-ODBC bridge and just connecting to the databases using different connection strings.</p>
<p><strong>I'm told this is not very efficient.</strong></p>
<ol>
<li><p>Is there a pattern or best practice for connecting to multiple database systems? Or for selecting which driver to use?</p></li>
<li><p>Should I have it configurable? but include all three drivers or build three separate clients?</p></li>
</ol>
<p>I'm not doing anything complex just pumping (inserting) data into the database from an event stream.</p>
| [
{
"answer_id": 295656,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": true,
"text": " if(DB.equals(\"MySQL\")){\n DAO = new MySQLDAO();\n}\nreturn DAO;\n"
},
{
"answer_id": 295712,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 1,
"selected": false,
"text": "jee:jndi-lookup"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20400/"
] |
295,645 | <p>I'm developing an invisible Java Applet, that will be controlled entirely from JavaScript.</p>
<p>I can call the applet's Java methods easily, and I can call JavaScript methods from within the applet by using <code>netscape.javascript.JSObject.getWindow(this).call()</code>.</p>
<p>But in order to register a JavaScript callback in the applet, I guess I would need an JavaScript function object of some sort.</p>
<p>I would like to do:</p>
<pre><code>public void registerCallback( SomeJavascriptFunction func ) { ... }
</code></pre>
<p>Which I could call from Javascript:</p>
<pre><code>myapplet.registerCallback(function(){ alert("called back"); });
</code></pre>
<p>So I could call this function in later code:</p>
<pre><code>func.call( ... );
</code></pre>
<p>Does something like this exist? How can I do this?</p>
<p>Rigth now I'm thinking of creating some Javascript to handle this callback mechanism instead of doing so from the applet.</p>
| [
{
"answer_id": 296452,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "function CallJava()\n{\n document.Applet.Call(\"Does it work?\");\n document.Applet.Call(function () { alert(\"It works!\"); });\n document.Applet.Call(DoSomething); // A simple parameterless JS function\n document.Applet.Call(window.location);\n}\nfunction DumbTest(message, value)\n{\n alert(\"This is a dumb test with a message:\\n\" + message + \"\\n\" + value);\n}\n public void Call(String message)\n{\n JSObject win = (JSObject) JSObject.getWindow(this);\n String[] arguments = { \"Call with String\", message };\n win.call(\"DumbTest\", arguments);\n}\n\npublic void Call(JSObject jso)\n{\n JSObject win = (JSObject) JSObject.getWindow(this);\n String[] arguments = { \"Call with JSObject\", jso.toString() };\n win.call(\"DumbTest\", arguments);\n}\n public int Do()\n{\n JSObject win = (JSObject) JSObject.getWindow(this);\n JSObject doc = (JSObject) win.getMember(\"document\");\n JSObject fun = (JSObject) win.getMember(\"DumberTest\");\n JSObject loc = (JSObject) doc.getMember(\"location\");\n String href = (String) loc.getMember(\"href\");\n String[] arguments = { href, fun.toString() };\n win.call(\"DumbTest\", arguments);\n return fun.toString().length();\n}\n function RegisterCallback(cbFunction)\n{\n var callback = cbFunction.toString(); // We get JS code\n var callbackName = /^function (\\w+)\\(/.exec(callback);\n document.Applet.RegisterCallback(callbackName[1]);\n}\n String callbackFunction;\npublic void RegisterCallback(String functionName)\n{\n callbackFunction = functionName;\n}\nvoid UseCallbackFunction()\n{\n if (callbackFunction == null) return;\n JSObject win = (JSObject) JSObject.getWindow(this);\n win.call(callbackFunction, null);\n}\n"
},
{
"answer_id": 296947,
"author": "RealHowTo",
"author_id": 25122,
"author_profile": "https://Stackoverflow.com/users/25122",
"pm_score": 1,
"selected": false,
"text": "String callbackFunction;\npublic void RegisterCallback(String functionName)\n{\n callbackFunction = functionName;\n}\nvoid UseCallbackFunction()\n{\n if (callbackFunction == null) return;\n JSObject win = (JSObject) JSObject.getWindow(this);\n win.eval(callbackFunction);\n}\n"
},
{
"answer_id": 11933349,
"author": "James Thorpe",
"author_id": 791010,
"author_profile": "https://Stackoverflow.com/users/791010",
"pm_score": 2,
"selected": false,
"text": "applet.DoProcessing({\n success: function(param) {\n alert('Success: ' + param);\n },\n error: function(param) {\n alert('Failed: ' + param);\n }\n});\n function ProcessingCallback(isSuccessful, cbParam, jsObject) {\n if (isSuccessful && jsObject.success)\n jsObject.success(cbParam);\n else if (!isSuccessful && jsObject.error)\n jsObject.error(cbParam);\n}\n public void DoProcessing(final Object callbacks) {\n //do processing....\n\n\n JSObject w = JSObject.getWindow(this);\n //Call our named callback, note how we pass the callbacks parameter straight\n //back out again - it will be unchanged in javascript.\n w.call(\"ProcessingCallback\", new Object[]{successful, output, callbacks});\n}\n public void DoProcessing(final Object callbacks) {\n //hold a reference for use in the thread\n final Applet app = this;\n\n //Create a new Thread object to run our request asynchronously\n //so we can return back to single threaded javascript immediately\n Thread async = new Thread() {\n //Thread objects need a run method\n public void run() {\n //do processing....\n\n\n JSObject w = JSObject.getWindow(app);\n //Call our named callback, note how we pass the callbacks parameter\n //straight back out again - it will be unchanged in javascript.\n w.call(\"ProcessingCallback\", new Object[]{successful, output, callbacks});\n }\n }\n //start the thread\n async.start();\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30700/"
] |
295,647 | <p>I'm attempting to register an anonymous function when a user clicks a cell in an HTML table. Here's some of the raw, unadulterated code:</p>
<pre><code>document.getElementById(
"course"+displayed_year_index+occurrences_indices[displayed_year_index]).onclick =
eval("function() {PrintReceipt("+result.years[result_year_index].rul_code+");};");
</code></pre>
<p>Note the use of <code>eval</code>, since this sits in a loop and the anonymous function is different each time round.</p>
<p>Suffice to say, this works absolutely fine in Firefox 2. But, Firefox 3 throws a 'Syntax Error', pointing inside the brackets after the word 'function'.</p>
<p>Does anybody have any smart ideas on how I can fix this?</p>
<hr>
<p>Just to make it crystal clear what I'm attempting to do, here's a much simplified example:</p>
<pre><code>for (index=0; index<4; index++) {
document.getElementById("div"+index).onclick =
eval("function () {Foo(index);};");
}
</code></pre>
<p>In other words, I wish to trigger the same function with a different parameter value for each <code>div</code>.</p>
| [
{
"answer_id": 295666,
"author": "Tom",
"author_id": 26155,
"author_profile": "https://Stackoverflow.com/users/26155",
"pm_score": 3,
"selected": false,
"text": "document.getElementById('course' + displayed_year_index + occurences_indices[displayed_year_index]) =\n function (nr)\n {\n return function () { PrintReceipt(nr) }\n } (result.years[result_year_index].rul_code);\n"
},
{
"answer_id": 295689,
"author": "ng.mangine",
"author_id": 37784,
"author_profile": "https://Stackoverflow.com/users/37784",
"pm_score": 0,
"selected": false,
"text": "document.getElementById(\"course\"+displayed_year_index+occurrences_indices[displayed_year_index]).addeventlistener(\"click\", function() {\n var current_rul_code = result.years[result_year_index].rul_code;\n PrintReceipt(current_rul_code);\n}, true);\n"
},
{
"answer_id": 296242,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 3,
"selected": true,
"text": "for ( /* your definition */ ) {\n var e = document.getElementById(\n \"course\"+displayed_year_index+occurrences_indices[displayed_year_index]\n );\n e.rul_code = result.years[result_year_index].rul_code;\n e.onclick = PrintReceipt;\n}\n function PrintReceipt() {\n //This function is called as an onclick handler, and \"this\" is a reference to the element that was clicked.\n if (this.rul_code === undefined) { return; }\n //Do what you want with this.rul_code\n alert (this.rul_code);\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/441661/"
] |
295,649 | <p>We have a simple project where we read data from a socket and we want to populate a table with the coming data, but we can't find a way to add rows to a yet created <code>JTable</code> object, we can only find how to add rows at creation time of the table.</p>
<p>Is it possible to add rows dynamically to a <code>JTable</code>, or there is a better alternative object to deal with this way of showing data?</p>
<p><strong>EDIT</strong>: Thanks a lot for your answers.</p>
<p>All three of them look very promising, but I have to choose only one and I think the best is Guillaume's.</p>
| [
{
"answer_id": 295674,
"author": "Guillaume",
"author_id": 23704,
"author_profile": "https://Stackoverflow.com/users/23704",
"pm_score": 5,
"selected": true,
"text": "TableModel JTable TableModel AbstractTableModel fireTableRowsInserted()"
},
{
"answer_id": 295695,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 4,
"selected": false,
"text": " if ( dest+1 < table.getRowCount()-1 )\n ( (DefaultTableModel) table.getModel() ).insertRow(dest+1, getValuesForNewRow());\n else\n ( (DefaultTableModel) table.getModel() ).addRow(getValuesForNewRow());\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38238/"
] |
295,660 | <p>I am trying to have one one layer, and center images within. I.E., if I have 3 images and want 3 links beneath them, is there a way to do this without using a separate div tag for each link and image? To automatically make the links be centered under the images, and the images to be spaced evenly within a layer? </p>
<p>I was also wondering how I would make the div show behind standard html if that is possible. I.E. if I have some text and a div over the text, the div will default show over the text, when I would like it to be behind. Is this only possible by using another layer?</p>
| [
{
"answer_id": 295669,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<div class=\"pictureBox\">\n <div>\n <img />\n caption caption\n </div>\n <div>\n <img />\n more caption\n </div>\n</div>\n--------\n.pictureBox div {\n text-align: center;\n /* whatever width/height/positioning you want */\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
295,662 | <p>This is one is for any of you Doctrine users out there. I have a PHP CLI daemon process that checks a table every n seconds to find entries that haven't been processed. It's basically a FIFO. Anyways, I always exceed the memory allocated to PHP becuase Doctrine does not free it's resources. To combat this problem it provides free for the query object. I can't seem to make it work though. Here's the code:</p>
<pre><code> 22 print "You are using " . (memory_get_usage() / 1024). "\n";
23 $query = Doctrine_Query::create()
24 ->from('SubmissionQueue s')
25 ->where('s.time_acted_on IS NULL')
26 ->orderby('s.time_queued')
27 ->limit(1)
28 ->execute();
29 print $query[0]->time_queued . "\n";
30 $query->free();
</code></pre>
<p>Any ideas what I am doing wrong?</p>
<p>EDIT: I am using 1.0.3</p>
<p>EDIT: I have tried all of the below suggestions. I was very hopeful for <code>unset()</code> as I had it in there before I found <code>free()</code>.</p>
<p>Here is more of the code to possibly aid in any help. Before you question the opening and closing of the connection it will be daemon process that spawns children and from I have experienced the connection has to be unique.</p>
<pre><code> 1 <?php
2
3 require_once('/usr/local/lib/php/Doctrine/lib/Doctrine.php');
4
5 spl_autoload_register(array('Doctrine', 'autoload'));
6
7 $manager = Doctrine_Manager::getInstance();
8 $manager->setAttribute('model_loading','conservative');
9 Doctrine::loadModels('lib/model/master');
10
11 while(1){
12 print "You are using " . intval(memory_get_usage() / 1024) . "\n";
13 $manager->connection('********************************************','master');
14 $query = Doctrine_Query::create()
15 ->from('SubmissionQueue s')
16 ->where('s.time_acted_on IS NULL')
17 ->orderby('s.time_queued')
18 ->limit(1)
19 ->execute();
20 print "[" . $query[0]->time_queued . "]\n";
21 $query->free();
22 unset($query);
23 $query = null;
24 $manager->closeConnection(Doctrine_Manager::getInstance()->getConnection('master'));
25 sleep(5);
26 }
27
</code></pre>
<p>Some sample output:</p>
<pre><code>You are using 14949KB
[2008-11-17 13:59:00]
You are using 14978KB
[2008-11-17 13:59:00]
You are using 15007KB
[2008-11-17 13:59:00]
You are using 15035KB
[2008-11-17 13:59:00]
You are using 15064KB
[2008-11-17 13:59:00]
You are using 15093KB
[2008-11-17 13:59:00]
You are using 15121KB
[2008-11-17 13:59:00]
You are using 15150KB
[2008-11-17 13:59:00]
You are using 15179KB
[2008-11-17 13:59:00]
You are using 15207KB
[2008-11-17 13:59:00]
You are using 15236KB
[2008-11-17 13:59:00]
You are using 15265KB
[2008-11-17 13:59:00]
You are using 15293KB
[2008-11-17 13:59:00]
You are using 15322KB
</code></pre>
| [
{
"answer_id": 295954,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "$query = Doctrine_Query::create()\n ->from('SubmissionQueue s')\n ->where('s.time_acted_on IS NULL')\n ->orderby('s.time_queued')\n ->limit(1);\n$query->execute();\nprint $query[0]->time_queued . \"\\n\";\n$query->free();\n"
},
{
"answer_id": 296502,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 4,
"selected": true,
"text": "free() unset() $query free() $query = Doctrine_Query::create()\n ->from('SubmissionQueue s')\n ->where('s.time_acted_on IS NULL')\n ->orderby('s.time_queued')\n ->limit(1);\n$query->execute();\nprint $query[0]->time_queued . \"\\n\";\n$query->free();\nunset($query); // perhaps $query = null; will also work\n"
},
{
"answer_id": 555057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": " $query = Doctrine_Query::create()\n ->from('SubmissionQueue s')\n ->where('s.time_acted_on IS NULL')\n ->orderby('s.time_queued')\n ->limit(1);\n $results = $query->execute();\n print $results[0]->time_queued . \"\\n\";\n\n $results->free();\n $query->free();\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28714/"
] |
295,670 | <p>What is and how can it be used in C#.<br/>
Can you use the same concept in Python/Perl?</p>
| [
{
"answer_id": 295713,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 2,
"selected": false,
"text": "class A(object):\n pass\n\nobj = A()\n\ndef _some_method(self):\n print self.__class__\nA.identify = _some_method\n\nobj.identify()\n"
},
{
"answer_id": 295733,
"author": "Clinton Pierce",
"author_id": 8173,
"author_profile": "https://Stackoverflow.com/users/8173",
"pm_score": 3,
"selected": false,
"text": " use MyClass;\n use MyClassOtherStuff;\n package MyClass;\n # [..class code here...]\n package MyClass;\n # [...rest of code here...]\n"
},
{
"answer_id": 295760,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 4,
"selected": true,
"text": "class A_part1:\n def m1(self):\n print \"m1\"\n\nclass A_part2:\n def m2(self):\n print \"m2\"\n\nclass A(A_part1, A_part2):\n pass\n\na = A()\na.m1()\na.m2()\n"
},
{
"answer_id": 15490754,
"author": "LCJ",
"author_id": 696627,
"author_profile": "https://Stackoverflow.com/users/696627",
"pm_score": 0,
"selected": false,
"text": "auto-generated code"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31179/"
] |
295,686 | <p>The following error is being thrown:</p>
<pre><code>com.sun.jdi.InternalException: Got error code in reply:35 occurred while retrieving value. for all expressions
</code></pre>
<p>I am getting this error for all expressions and cant find anything on it. My guess is that the debugger isn't correctly connecting to the remote version, but I am not sure.</p>
| [
{
"answer_id": 678516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "com.sun.jdi.internalexception"
},
{
"answer_id": 8151260,
"author": "Shri",
"author_id": 1049589,
"author_profile": "https://Stackoverflow.com/users/1049589",
"pm_score": 3,
"selected": false,
"text": "for for(Object obj: list)\n{\n for(Object obj2 : list)\n {}\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,687 | <p>I would like to get the path to the execution directory of a Windows Forms application. (That is, the directory in which the executable is located.)</p>
<p>Does anyone know of a built-in method in .NET to do this?</p>
| [
{
"answer_id": 295694,
"author": "Tomas Pajonk",
"author_id": 4694,
"author_profile": "https://Stackoverflow.com/users/4694",
"pm_score": 6,
"selected": false,
"text": "Dim directory as String = My.Application.Info.DirectoryPath\n string directory = AppDomain.CurrentDomain.BaseDirectory;\n"
},
{
"answer_id": 295696,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 4,
"selected": false,
"text": "Path.GetDirectoryName(Application.ExecutablePath);\n"
},
{
"answer_id": 295709,
"author": "thmsn",
"author_id": 28145,
"author_profile": "https://Stackoverflow.com/users/28145",
"pm_score": 7,
"selected": true,
"text": "AppDomain.CurrentDomain.BaseDirectory\n"
},
{
"answer_id": 295732,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "string apppath = \n (new System.IO.FileInfo\n (System.Reflection.Assembly.GetExecutingAssembly().CodeBase)).DirectoryName;\n"
},
{
"answer_id": 330393,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "System.Windows.Forms.Application.StartupPath"
},
{
"answer_id": 8307181,
"author": "sandeep k",
"author_id": 1070788,
"author_profile": "https://Stackoverflow.com/users/1070788",
"pm_score": 1,
"selected": false,
"text": "Imports System.IO\nImports System.Management\n\nPublic Class Form1\n Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)\n Process.Start(TextBox1.Text)\n End Sub\nEnd Class\n"
},
{
"answer_id": 26228971,
"author": "али ",
"author_id": 4115719,
"author_profile": "https://Stackoverflow.com/users/4115719",
"pm_score": 2,
"selected": false,
"text": "TextBox1.Text = My.Application.Info.DirectoryPath\n TextBox2.Text = IO.Path.GetFullPath(Application.ExecutablePath)\n"
},
{
"answer_id": 45592377,
"author": "vignesh pethaperumal",
"author_id": 7651808,
"author_profile": "https://Stackoverflow.com/users/7651808",
"pm_score": 0,
"selected": false,
"text": "Private Sub Main_Shown(sender As Object, e As EventArgs) Handles Me.Shown\n Dim args() As String = Environment.GetCommandLineArgs()\n If args.Length > 0 Then\n TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)\n Process.Start(TextBox1.Text) \n End If\nEnd Sub\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
295,688 | <p>I have 2 tables event + event_artist</p>
<h2>event</h2>
<pre><code>eventId | eventName
-------------------
1 , gig1
2, gig2
</code></pre>
<h2>event_artist</h2>
<pre><code>eventId, artistName
-------------------
1, Led Zip
1, The Beatles
</code></pre>
<p>ie Led Zep and the Beatles are both playing @ Gig1</p>
<p>I need to create the SQl to bind to a gridview ( you necessarily need to know about gridviews to answers this )</p>
<p>The results that i want would look like this<br>
eventId = 1, EventName = Gig1. ArtistLineup = Led Zep, The beatles</p>
<p>So i need to create an alias ArtistLineup that would list all the artist. Via an inner select i think.</p>
<p>Any thoughts on what this would look like. </p>
| [
{
"answer_id": 295819,
"author": "ScottK",
"author_id": 37757,
"author_profile": "https://Stackoverflow.com/users/37757",
"pm_score": 3,
"selected": true,
"text": "drop table event\ngo\n\ndrop table event_artist\ngo\n\ncreate table event (eventid int, eventname varchar(255))\ngo\n\ncreate table event_artist (eventid int, artistname varchar(255))\ngo\n\ninsert into event values (1, 'gig1')\ngo\n\ninsert into event values (2, 'gig2')\ngo\n\ninsert into event_artist values (1, 'Led Zip')\ngo\n\ninsert into event_artist values (1, 'The Beatles')\ngo\n\ndrop function Event_Display\ngo\n\ncreate function Event_Display (@EventID int) returns varchar(2000) as\nbegin\n declare @artistList varchar(2000)\n set @artistList=''\n\n select @artistList=@artistList + ', ' + isnull(artistname,'') \n from event_artist \n where eventid=@EventID\n\n return substring(@artistList,3,2000) --eliminate initial comma\nend\ngo\n\nselect event.eventid, event.eventname, dbo.Event_Display(event.eventid) from event \n"
},
{
"answer_id": 295870,
"author": "Scott Lawrence",
"author_id": 3475,
"author_profile": "https://Stackoverflow.com/users/3475",
"pm_score": 0,
"selected": false,
"text": "select e.*, dbo.ArtistList(e.EventId) as ArtistList\nfrom [event] e\n CREATE FUNCTION ArtistList<br>\n(\n -- Add the parameters for the function here<br>\n @EventId int<br>\n)\nRETURNS varchar(MAX)<br>\nAS\nBEGIN\n -- Declare the return variable here\n DECLARE @ArtistList varchar(MAX)\n -- Add the T-SQL statements to compute the return value here\n SELECT @ArtistList = COALESCE(@ArtistList + ', ', '') + Artist\n FROM EventArtist\n WHERE EventId = @EventId\n -- Return the result of the function\n RETURN @ArtistList\nEND\nGO\n varchar(MAX)"
},
{
"answer_id": 295903,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "/*\ncreate table [event] (eventid int, eventname varchar(255))\ncreate table event_artist (eventid int, artistname varchar(255))\ninsert into [event] values (1, 'gig1')\ninsert into [event] values (2, 'gig2')\ninsert into event_artist values (1, 'Led Zip')\ninsert into event_artist values (1, 'The Beatles')\n*/\n\nSELECT e.eventid\n ,e.eventname\n ,REPLACE(REPLACE(RTRIM((\n SELECT artistname + '| '\n FROM [event_artist]\n WHERE eventid = e.eventid\n FOR\n XML PATH('')\n )), '| ', ', '), '|', '') AS artists\nFROM [event] AS e\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461880/"
] |
295,690 | <p>I've got a section of code on a b2evo PHP site that does the following: </p>
<pre><code>$content = preg_replace_callback(
'/[\x80-\xff]/',
create_function( '$j', 'return "&#".ord($j[0]).";";' ),
$content);
</code></pre>
<p>What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure. </p>
<p>Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory. </p>
<p>This is causing problems with my web application. Why am I losing memory, and how do I rewrite this so I don't get a memory leak?</p>
| [
{
"answer_id": 295697,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "create_function &#xxx;"
},
{
"answer_id": 295698,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": true,
"text": "$content = 'Çà ! Nœm dé fîçhïèr tôrdù, @ pöür têstër... ? ~ Œ[€]';\n$content = preg_replace_callback('/[\\x80-\\xff]/', 'CB_CharToEntity', $content);\necho $econtent . '<br>';\necho htmlspecialchars($content) . '<br>';\necho htmlentities($content) . '<br>';\necho htmlentities($content, ENT_NOQUOTES, 'cp1252') . '<br>';\n\nfunction CB_CharToEntity($matches)\n{\n return '&#' . ord($matches[0]) . ';';\n}\n"
},
{
"answer_id": 1736901,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 0,
"selected": false,
"text": "preg_replace /e $content = preg_replace(\n '/[\\x80-\\xff]/e',\n '\"&#\".ord($0).\";\"',\n $content);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] |
295,708 | <p>Before I ask my question, here's the offending code:</p>
<pre><code>var coords = dojo.coords(g);
g.style.left = coords.x + "px";
g.style.top = coords.y + "px";
g.style.position = "absolute";
</code></pre>
<p>Now imagine that <code>g</code> is a relatively positioned element with an <code>x</code> position of 70 and a <code>y</code> position of 30. If I comment out the last line of the above code, that's what <code>dojo.coords(g)</code> gives me. But as soon as I add the last line, <code>dojo.coords(g)</code> returns an <code>x</code> position of 18, which is where the element would be if it were absolutely positioned. It seems to me that the call to <code>dojo.coords()</code> shouldn't be affected by code below it, but it is.</p>
<p>I'm also seeing the same problem with <code>dojo.require()</code> where if I call it directly before the function call that it's loading, I get an undefined error for that given function.</p>
<p>I'm testing in Firefox 3, but I also am noticing similar problems in Safari 3. Any ideas?</p>
| [
{
"answer_id": 295720,
"author": "José Leal",
"author_id": 37190,
"author_profile": "https://Stackoverflow.com/users/37190",
"pm_score": -1,
"selected": false,
"text": "g.style.left = parseInt(coords.x) + \"px\";\ng.style.top = parseInt(coords.y) + \"px\";\n g.offsetTop\n g.offsetLeft \n"
},
{
"answer_id": 296512,
"author": "inxilpro",
"author_id": 12549,
"author_profile": "https://Stackoverflow.com/users/12549",
"pm_score": 1,
"selected": true,
"text": "var coords = dojo.coords(g);\ng.style.left = coords.x + \"px\";\ng.style.top = coords.y + \"px\";\nsetTimeout(function(h) {\n h.style.position = \"absolute\";\n}, 0, g);\n"
},
{
"answer_id": 313430,
"author": "Eugene Lazutkin",
"author_id": 26394,
"author_profile": "https://Stackoverflow.com/users/26394",
"pm_score": 1,
"selected": false,
"text": "var coords = dojo.coords(g);\ng.style.position = \"absolute\";\ndojo.marginBox(g, {l: coords.x, t: coords.y});\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549/"
] |
295,710 | <p>There is a need from a customer to log every data change to a logging table with the actual user who made the modification. The application is using one SQL user to access the database, but we need to log the "real" user id.</p>
<p>We can do this in t-sql by writing triggers for every table insert and update, and using context_info to store the user id. We passed the user id to a stored procedure, stored the user id in the contextinfo, and the trigger could use this info to write log rows to the log table.</p>
<p>I can not find the place or way where or how can I do something similar using EF. So the main goal is: if I make a change in the data via EF, I would like to log the exact data change to a table in a semi-automatic way (so I don't want to check for every field for change before saving the object). We are using EntitySQL.</p>
<p>Unfortunately we have to stick on SQL 2000 so the data change capture introduced in SQL2008 is not an option (but maybe that's also not the right way for us).</p>
<p>Any ideas, links or starting points?</p>
<p><strong>[Edit]</strong>
Some notes: by using ObjectContext.SavingChanges eventhandler, I can get the point where I can inject the SQL statement to initialize the contextinfo. However I cannot mix the EF and the standard SQL. So I can get the EntityConnection but I cannot execute a T-SQL statement using it. Or I can get the connection string of the EntityConnection and create an SqlConnection based on it, but it will be a different connection, so the contextinfo will not affect the save made by the EF.</p>
<p>I tried the following in the SavingChanges handler:</p>
<pre><code>testEntities te = (testEntities)sender;
DbConnection dc = te.Connection;
DbCommand dcc = dc.CreateCommand();
dcc.CommandType = CommandType.StoredProcedure;
DbParameter dp = new EntityParameter();
dp.ParameterName = "userid";
dp.Value = textBox1.Text;
dcc.CommandText = "userinit";
dcc.Parameters.Add(dp);
dcc.ExecuteNonQuery();
</code></pre>
<p>Error: The value of EntityCommand.CommandText is not valid for a StoredProcedure command.
The same with SqlParameter instead of EntityParameter: SqlParameter cannot be used.</p>
<pre><code>StringBuilder cStr = new StringBuilder("declare @tx char(50); set @tx='");
cStr.Append(textBox1.Text);
cStr.Append("'; declare @m binary(128); set @m = cast(@tx as binary(128)); set context_info @m;");
testEntities te = (testEntities)sender;
DbConnection dc = te.Connection;
DbCommand dcc = dc.CreateCommand();
dcc.CommandType = CommandType.Text;
dcc.CommandText = cStr.ToString();
dcc.ExecuteNonQuery();
</code></pre>
<p>Error: The query syntax is not valid.</p>
<p>So here I am, stuck to create a bridge between Entity Framework and ADO.NET.
If I can get it working, I will post a proof of concept.</p>
| [
{
"answer_id": 304709,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "-- This is for the data\ncreate table datastuff (\n id int not null identity(1, 1),\n userid nvarchar(64) not null default(''),\n primary key(id)\n)\ngo\n\n-- This is for the log\ncreate table naplo (\n id int not null identity(1, 1),\n userid nvarchar(64) not null default(''),\n datum datetime not null default('2099-12-31'),\n primary key(id)\n)\ngo\n create trigger myTrigger on datastuff for insert as\n\n declare @User_id int,\n @User_context varbinary(128),\n @User_id_temp varchar(64)\n\n select @User_context = context_info\n from master.dbo.sysprocesses\n where spid=@@spid\n\n set @User_id_temp = cast(@User_context as varchar(64))\n\n declare @insuserid nvarchar(64)\n\n select @insuserid=userid from inserted\n\n insert into naplo(userid, datum)\n values(@User_id_temp, getdate())\n\ngo\n create procedure userinit(@userid varchar(64))\nas\nbegin\n declare @m binary(128)\n set @m = cast(@userid as binary(128))\n set context_info @m\nend\ngo\n using (testEntities te = new testEntities())\n{\n // Hook to the event\n te.SavingChanges += new EventHandler(te_SavingChanges);\n\n // This is important, because the context info is set inside a connection\n te.Connection.Open();\n\n // Add a new datastuff\n datastuff ds = new datastuff();\n\n // This is coming from a text box of my test form\n ds.userid = textBox1.Text;\n te.AddTodatastuff(ds);\n\n // Save the changes\n te.SaveChanges(true);\n\n // This is not needed, only to make sure\n te.Connection.Close();\n}\n // Take my entity\ntestEntities te = (testEntities)sender;\n\n// Get it's connection\nEntityConnection dc = (EntityConnection )te.Connection;\n\n// This is important!\nDbConnection storeConnection = dc.StoreConnection;\n\n// Create our command, which will call the userinit SP\nDbCommand command = storeConnection.CreateCommand();\ncommand.CommandText = \"userinit\";\ncommand.CommandType = CommandType.StoredProcedure;\n\n// Put the user id as the parameter\ncommand.Parameters.Add(new SqlParameter(\"userid\", textBox1.Text));\n\n// Execute the command\ncommand.ExecuteNonQuery();\n"
},
{
"answer_id": 5122375,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 4,
"selected": false,
"text": "private int _contextUserId;\n\npublic void SomeMethod()\n{\n var db = new MyEntities();\n db.Connection.StateChange += this.Connection_StateChange;\n this._contextUserId = theCurrentUserId;\n\n // whatever else you want to do\n}\n\nprivate void Connection_StateChange(object sender, StateChangeEventArgs e)\n{\n // only do this when we first open the connection\n if (e.OriginalState == ConnectionState.Open ||\n e.CurrentState != ConnectionState.Open)\n return;\n\n // use the existing open connection to set the context info\n var connection = ((EntityConnection) sender).StoreConnection;\n var command = connection.CreateCommand();\n command.CommandText = \"proc_ContextInfoSet\";\n command.CommandType = CommandType.StoredProcedure;\n command.Parameters.Add(new SqlParameter(\"ContextUserID\", this._contextUserId));\n command.ExecuteNonQuery();\n}\n"
},
{
"answer_id": 25170754,
"author": "CatGuardian",
"author_id": 3914739,
"author_profile": "https://Stackoverflow.com/users/3914739",
"pm_score": 2,
"selected": false,
"text": "...\nFileMoverContext context = new FileMoverContext();\ncontext.SetSessionContextInfo(Environment.UserName);\n...\ncontext.SaveChanges();\n public bool SetSessionContextInfo(string infoValue)\n{\n try\n {\n if (infoValue == null)\n throw new ArgumentNullException(\"infoValue\");\n\n string rawQuery =\n @\"DECLARE @temp varbinary(128)\n SET @temp = CONVERT(varbinary(128), '\";\n\n rawQuery = rawQuery + infoValue + @\"');\n SET CONTEXT_INFO @temp\";\n this.Database.ExecuteSqlCommand(rawQuery);\n\n return true;\n }\n catch (Exception e)\n {\n return false;\n }\n}\n"
},
{
"answer_id": 32476887,
"author": "MAQ",
"author_id": 3099784,
"author_profile": "https://Stackoverflow.com/users/3099784",
"pm_score": 0,
"selected": false,
"text": " public class GenericRepository<T> : IGenericRepository<T> where T : class\n{\n internal SampleDBContext Context;\n internal DbSet<T> DbSet;\n\n /// <summary>\n /// Constructor to initialize type collection\n /// </summary>\n /// <param name=\"context\"></param>\n public GenericRepository(SampleDBContext context)\n {\n Context = context;\n DbSet = context.Set<T>();\n }\n\n /// <summary>\n /// Get query on current entity\n /// </summary>\n /// <returns></returns>\n public virtual IQueryable<T> GetQuery()\n {\n return DbSet;\n }\n\n /// <summary>\n /// Performs read operation on database using db entity\n /// </summary>\n /// <param name=\"filter\"></param>\n /// <param name=\"orderBy\"></param>\n /// <param name=\"includeProperties\"></param>\n /// <returns></returns>\n public virtual IEnumerable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>,\n IOrderedQueryable<T>> orderBy = null, string includeProperties = \"\")\n {\n IQueryable<T> query = DbSet;\n\n if (filter != null)\n {\n query = query.Where(filter);\n }\n\n query = includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Aggregate(query, (current, includeProperty) => current.Include(includeProperty));\n\n if (orderBy == null)\n return query.ToList();\n else\n return orderBy(query).ToList();\n }\n\n /// <summary>\n /// Performs read by id operation on database using db entity\n /// </summary>\n /// <param name=\"id\"></param>\n /// <returns></returns>\n public virtual T GetById(object id)\n {\n return DbSet.Find(id);\n }\n\n /// <summary>\n /// Performs add operation on database using db entity\n /// </summary>\n /// <param name=\"entity\"></param>\n public virtual void Insert(T entity)\n {\n //if (!entity.GetType().Name.Contains(\"AuditLog\"))\n //{\n // LogEntity(entity, \"I\");\n //}\n DbSet.Add(entity);\n }\n\n /// <summary>\n /// Performs delete by id operation on database using db entity\n /// </summary>\n /// <param name=\"id\"></param>\n public virtual void Delete(object id)\n {\n T entityToDelete = DbSet.Find(id);\n Delete(entityToDelete);\n }\n\n /// <summary>\n /// Performs delete operation on database using db entity\n /// </summary>\n /// <param name=\"entityToDelete\"></param>\n public virtual void Delete(T entityToDelete)\n {\n if (!entityToDelete.GetType().Name.Contains(\"AuditLog\"))\n {\n LogEntity(entityToDelete, \"D\");\n }\n\n if (Context.Entry(entityToDelete).State == EntityState.Detached)\n {\n DbSet.Attach(entityToDelete);\n }\n DbSet.Remove(entityToDelete);\n }\n\n /// <summary>\n /// Performs update operation on database using db entity\n /// </summary>\n /// <param name=\"entityToUpdate\"></param>\n public virtual void Update(T entityToUpdate)\n {\n if (!entityToUpdate.GetType().Name.Contains(\"AuditLog\"))\n {\n LogEntity(entityToUpdate, \"U\");\n }\n DbSet.Attach(entityToUpdate);\n Context.Entry(entityToUpdate).State = EntityState.Modified;\n }\n\n public void LogEntity(T entity, string action = \"\")\n {\n try\n {\n //*********Populate the audit log entity.**********\n var auditLog = new AuditLog();\n auditLog.TableName = entity.GetType().Name;\n auditLog.Actions = action;\n auditLog.NewData = Newtonsoft.Json.JsonConvert.SerializeObject(entity);\n auditLog.UpdateDate = DateTime.Now;\n foreach (var property in entity.GetType().GetProperties())\n {\n foreach (var attribute in property.GetCustomAttributes(false))\n {\n if (attribute.GetType().Name == \"KeyAttribute\")\n {\n auditLog.TableIdValue = Convert.ToInt32(property.GetValue(entity));\n\n var entityRepositry = new GenericRepository<T>(Context);\n var tempOldData = entityRepositry.GetById(auditLog.TableIdValue);\n auditLog.OldData = tempOldData != null ? Newtonsoft.Json.JsonConvert.SerializeObject(tempOldData) : null;\n }\n\n if (attribute.GetType().Name == \"CustomTrackAttribute\")\n {\n if (property.Name == \"BaseLicensingUserId\")\n {\n auditLog.UserId = ValueConversion.ConvertValue(property.GetValue(entity).ToString(), 0);\n }\n }\n }\n }\n\n //********Save the log in db.*********\n new UnitOfWork(Context, null, false).AuditLogRepository.Insert(auditLog);\n }\n catch (Exception ex)\n {\n Logger.LogError(string.Format(\"Error occured in [{0}] method of [{1}]\", Logger.GetCurrentMethod(), this.GetType().Name), ex);\n }\n }\n}\n\nCREATE TABLE [dbo].[AuditLog](\n[AuditId] [BIGINT] IDENTITY(1,1) NOT NULL,\n[TableName] [nvarchar](250) NULL,\n[UserId] [int] NULL,\n[Actions] [nvarchar](1) NULL,\n[OldData] [text] NULL,\n[NewData] [text] NULL,\n[TableIdValue] [BIGINT] NULL,\n[UpdateDate] [datetime] NULL,\n CONSTRAINT [PK_DBAudit] PRIMARY KEY CLUSTERED \n(\n[AuditId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = \nOFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]\n"
},
{
"answer_id": 51973877,
"author": "A_Arnold",
"author_id": 5050431,
"author_profile": "https://Stackoverflow.com/users/5050431",
"pm_score": 0,
"selected": false,
"text": "private object GetPrimaryKeyValue(DbEntityEntry entry)\n {\n var objectStateEntry = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.GetObjectStateEntry(entry.Entity);\n object o = objectStateEntry.EntityKey.EntityKeyValues[0].Value;\n return o;\n }\n\n private bool inExcludeList(string prop)\n {\n string[] excludeList = { \"props\", \"to\", \"exclude\" };\n return excludeList.Any(s => s.Equals(prop));\n }\n\n public int SaveChanges(User user, string UserId)\n {\n var modifiedEntities = ChangeTracker.Entries()\n .Where(p => p.State == EntityState.Modified).ToList();\n var now = DateTime.Now;\n\n foreach (var change in modifiedEntities)\n {\n\n var entityName = ObjectContext.GetObjectType(change.Entity.GetType()).Name;\n var primaryKey = GetPrimaryKeyValue(change);\n var DatabaseValues = change.GetDatabaseValues();\n\n foreach (var prop in change.OriginalValues.PropertyNames)\n {\n if(inExcludeList(prop))\n {\n continue;\n }\n\n string originalValue = DatabaseValues.GetValue<object>(prop)?.ToString();\n string currentValue = change.CurrentValues[prop]?.ToString();\n\n if (originalValue != currentValue)\n {\n ChangeLog log = new ChangeLog()\n {\n EntityName = entityName,\n PrimaryKeyValue = primaryKey.ToString(),\n PropertyName = prop,\n OldValue = originalValue,\n NewValue = currentValue,\n ModifiedByName = user.LastName + \", \" + user.FirstName,\n ModifiedById = UserId,\n ModifiedBy = user,\n ModifiedDate = DateTime.Now\n };\n\n ChangeLogs.Add(log);\n }\n }\n }\n return base.SaveChanges();\n }\n\n\n\npublic class ChangeLog \n {\n public int Id { get; set; }\n public string EntityName { get; set; }\n public string PropertyName { get; set; }\n public string PrimaryKeyValue { get; set; }\n public string OldValue { get; set; }\n public string NewValue { get; set; }\n public string ModifiedByName { get; set; }\n\n\n\n [ForeignKey(\"ModifiedBy\")]\n [DisplayName(\"Modified By\")]\n public string ModifiedById { get; set; }\n public virtual User ModifiedBy { get; set; }\n\n\n [Column(TypeName = \"datetime2\")]\n public DateTime? ModifiedDate { get; set; }\n }\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/968/"
] |
295,719 | <p>We have a custom REST handler on ASP.NET that is configured like this to handle all incoming requests:</p>
<pre><code><add path="*" verb="*" type="REST.RESTProtocolHandler"/>
</code></pre>
<p>However, passing it a pipe character, properly encoded or not at all, triggers a validation error that seems to come from inside ASP.NET.</p>
<p>Accessing <code><a href="http://localhost:8080/%7c" rel="nofollow noreferrer">http://localhost:8080/%7c</a></code> or <code><a href="http://localhost:8080/|" rel="nofollow noreferrer">http://localhost:8080/|</a></code> yields this error:</p>
<blockquote>
<p>[ArgumentException: Illegal characters in path.]
System.IO.Path.CheckInvalidPathChars(String path) +7489125
System.IO.Path.Combine(String path1, String path2) +40
System.Web.Configuration.UserMapPath.GetPhysicalPathForPath(String path, VirtualDirectoryMapping mapping) +114
System.Web.Configuration.UserMapPath.GetPathConfigFilename(String siteID, VirtualPath path, String& directory, String& baseName) +72
System.Web.Configuration.UserMapPath.MapPath(String siteID, VirtualPath path) +30
System.Web.Configuration.UserMapPath.MapPath(String siteID, String path) +31
System.Web.Hosting.HostingEnvironment.MapPathActual(VirtualPath virtualPath, Boolean permitNull) +297
System.Web.Hosting.HostingEnvironment.MapPathInternal(VirtualPath virtualPath, Boolean permitNull) +51
System.Web.CachedPathData.GetConfigPathData(String configPath) +341
System.Web.CachedPathData.GetVirtualPathData(VirtualPath virtualPath, Boolean permitPathsOutsideApp) +110
System.Web.HttpContext.GetFilePathData() +36
System.Web.HttpContext.GetConfigurationPathData() +26
System.Web.Configuration.RuntimeConfig.GetConfig(HttpContext context) +43
System.Web.Configuration.CustomErrorsSection.GetSettings(HttpContext context, Boolean canThrow) +41
System.Web.HttpResponse.ReportRuntimeError(Exception e, Boolean canThrow, Boolean localExecute) +101
System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +383</p>
</blockquote>
<p>No userland code gets executed. Is this a configuration option somewhere? Reproduced on IIS 7 & VS Studio's 2008 devel server.</p>
<p>Stack Overflow seems to handle this error OK, it looks like a dynamically generated 404 MVC page gets rendered for <a href="https://stackoverflow.com/%7c"><a href="https://stackoverflow.com/%7c">https://stackoverflow.com/%7c</a></a>.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 302093,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 1,
"selected": false,
"text": "protected void Application_Error(Object sender, EventArgs e)\n{\n Exception ex = Server.GetLastError();\n //do whatever you want with that exception\n //or get the url from the context, reformat and redirect\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28917/"
] |
295,731 | <p>I have a website built in C#.NET that tends to produce a fairly steady stream of SQL timeouts from various user controls and I want to easily pop some code in to catch all unhandled exceptions and send them to something that can log them and display a friendly message to the user.</p>
<p>How do I, through minimal effort, catch all unhandled exceptions?</p>
<p><a href="https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11">this question</a> seems to say it's impossible, but that doesn't make sense to me (and it's about .NET 1.1 in windows apps): </p>
| [
{
"answer_id": 295739,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "Exception"
},
{
"answer_id": 295803,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 3,
"selected": false,
"text": "AppDomain.CurrentDomain.UnhandledException"
},
{
"answer_id": 295916,
"author": "Dan Powley",
"author_id": 2761,
"author_profile": "https://Stackoverflow.com/users/2761",
"pm_score": 4,
"selected": false,
"text": "void Application_Error(object sender, EventArgs e) \n{ \n // Code that runs when an unhandled error occurs\n log4net.ILog log = log4net.LogManager.GetLogger(typeof(object));\n using (log4net.NDC.Push(this.User.Identity.Name))\n {\n log.Fatal(\"Unhandled Exception\", Server.GetLastError());\n }\n}\n"
},
{
"answer_id": 1197591,
"author": "Jack Marchetti",
"author_id": 117658,
"author_profile": "https://Stackoverflow.com/users/117658",
"pm_score": 1,
"selected": false,
"text": "try {\n conn.Open();\n cmd.ExecuteReader();\n conn.Close();\n} catch (SqlException ex) {\n //do whatever\n}\n try {\n conn.Open();\n cmd.ExecuteReader();\n conn.Close();\n} catch (SqlException ex) {\n //do whatever\n} finally {\n if(conn.State != ConnectionState.Closed)\n conn.Close();\n}\n"
},
{
"answer_id": 1197753,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "// normal form code.\nprivate void Save()\n{\n // you can do stuff before and after. normal scoping rules apply\n saveControl.InvokeSave(\n delegate\n {\n // everywhere the save control is used, this code is different\n // but the class of errors and the stage we are catching them at\n // is the same\n DataContext.SomeStoredProcedure();\n DataContext.SomeOtherStoredProcedure();\n DataContext.SubmitChanges();\n });\n}\n public delegate void SaveControlDelegate();\n\npublic void InvokeSave(SaveControlDelegate saveControlDelegate)\n{ \n // I've changed the code from our code. \n // You'll have to make up your own logic.\n // this just gives an idea of common handling.\n retryButton.Visible = false;\n try\n {\n saveControlDelegate.Invoke();\n }\n catch (SqlTimeoutException ex)\n {\n // perform other logic here.\n statusLabel.Text = \"The server took too long to respond.\";\n retryButton.Visible = true;\n LogSqlTimeoutOnSave(ex);\n }\n // catch other exceptions as necessary. i.e.\n // detect deadlocks\n catch (Exception ex)\n {\n statusLabel.Text = \"An unknown Error occurred\";\n LogGenericExceptionOnSave(ex);\n }\n SetSavedStatus();\n}\n"
},
{
"answer_id": 29119626,
"author": "Michael",
"author_id": 1285871,
"author_profile": "https://Stackoverflow.com/users/1285871",
"pm_score": 0,
"selected": false,
"text": "public class ExceptionHandlingAttribute : ExceptionFilterAttribute\n{\n public override void OnException(HttpActionExecutedContext context)\n {\n var exception = context.Exception;\n if(exception is SqlTimeoutException)\n {\n //do some handling for this type of exception\n }\n }\n}\n [ExceptionHandling]\npublic class HomeController: Controller\n{\n\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2462/"
] |
295,736 | <p>I need to spawn a process in Java (under Linux exclusively) that will continue to run after the JVM has exited. How can I do this? </p>
<p>Basically the Java app should spawn an updater which stops the Java app, updates files and then starts it again.</p>
<p>I'm interested in a hack & slash method to just get it working as well as a better design proposal if you have one :)</p>
| [
{
"answer_id": 295748,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "java.lang.Process"
},
{
"answer_id": 39486055,
"author": "cowls",
"author_id": 992151,
"author_profile": "https://Stackoverflow.com/users/992151",
"pm_score": 2,
"selected": false,
"text": "ProcessBuilder pb = new ProcessBuilder(cmd);\npb.redirectOutput(logFile);\npb.redirectError(logFile);\nProcess p = pb.start();\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295736",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,752 | <p>I am trying to write an installer (by creating a .vdproj) that will work on both Windows Vista and XP. The only thing I am finding is that when I try to run it on Vista, the files that I include in the installer are installed with Read-only permissions for the Users groups. This is a problem because the application needs to read/write from these files. The only way I have been able to get it to work is to either "Run as Administrator" or actually change the permissions. Does anyone know how to make these files be open to anyone to write? Thanks.</p>
| [
{
"answer_id": 295787,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "Environment.GetFolderPath()"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
] |
295,766 | <p>The XML file I want to parse starts with :</p>
<pre><code><!DOCTYPE plist PUBLIC "-//...//DTD PLIST 1.0//EN" "http://www.....dtd">
</code></pre>
<p>So when I start the SAX praser, it tries to access this DTD online, and I get a java.net.UnknownHostException.</p>
<ol>
<li>I cannot modify the XML file before feeding it to the SAX parser</li>
<li>I have to run even with no internet connection</li>
</ol>
<p>How can I change the SAX Parser behaviour so that it does not try to load the DTD ?
Thanks.</p>
<pre><code>javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
factory.setValidating(false);
javax.xml.parsers.SAXParser parser = factory.newSAXParser();
parser.parse(xmlFile, handler);
</code></pre>
| [
{
"answer_id": 295840,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 0,
"selected": false,
"text": "EntityResolver org.xml.sax.EntityResolver customEntityResolver = new DummyEntityResolver();\njavax.xml.parsers.SAXParser parser = factory.newSAXParser();\nparser.getXMLReader().setEntityResolver(customEntityResolver);\nparser.parse(xmlFile, handler);\n"
},
{
"answer_id": 295998,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 4,
"selected": false,
"text": "parse() javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();\nfactory.setValidating(false);\njavax.xml.parsers.SAXParser parser = factory.newSAXParser();\nparser.parse(new java.io.File(\"x.xml\"), new org.xml.sax.helpers.DefaultHandler(){\n public org.xml.sax.InputSource resolveEntity(String publicId, String systemId)\n throws org.xml.sax.SAXException, java.io.IOException {\n System.out.println(\"Ignoring: \" + publicId + \", \" + systemId);\n return new org.xml.sax.InputSource(new java.io.StringReader(\"\"));\n }\n }); \n"
},
{
"answer_id": 7713188,
"author": "Stefano Rosanelli",
"author_id": 987741,
"author_profile": "https://Stackoverflow.com/users/987741",
"pm_score": 1,
"selected": false,
"text": " XMLReader reader =XMLReaderFactory.createXMLReader();\n reader.setEntityResolver(new DummyEntityResolver());\n reader.setContentHandler(handler);\n reader.parse(inputSource);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/155796/"
] |
295,771 | <p>I have a SQL SELECT query which has a LIKE clause containing an underscore, which should specifically look for an underscore, not treat it as a wildcard: </p>
<pre><code>SELECT * FROM my_table WHERE name LIKE '_H9%';
</code></pre>
<p>I understand that I can change the actual clause to '[_]H9%' for this to work as I expect, but the problem is that this clause is being generated by Hibernate.</p>
<p>Is there a way to configure Hibernate to escape all underscores in all queries in this way? Failing that, is there a way to configure SQL Server (2008 in my case) to <em>not</em> treat underscores as wildcards?</p>
| [
{
"answer_id": 423054,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 4,
"selected": true,
"text": "public class EscapingLikeExpression extends LikeExpression {\n public EscapingLikeExpression(String propertyName, String value) {\n super(propertyName, escapeString(value), '!', false);\n }\n\n static String escapeString(String inputString) {\n inputString = inputString.replace(\"_\", \"!_\");\n return inputString;\n }\n\n}\n inputString = inputString.replace(\"!\", \"!!\");\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1174/"
] |
295,772 | <p>I have a *.MDB database file, and I am wondering if it is possible or recommended to work against it using LINQ in C#. I am also wondering what some simple examples would look like.</p>
<p>I don't know a lot about LINQ, but my requirements for this task are pretty simple (I believe). The user will be passing me a file path to Microsoft Access MDB database and I would like to use LINQ to add rows to one of the tables within the database.</p>
| [
{
"answer_id": 2332263,
"author": "Quinten Miller",
"author_id": 264147,
"author_profile": "https://Stackoverflow.com/users/264147",
"pm_score": 1,
"selected": false,
"text": "eICATDataSet.ICSWSbuDataTable tbl = new eICATDataSet.ICSWSbuDataTable();\n\nICSWSbuTableAdapter ta = new ICSWSbuTableAdapter();\nta.Fill(tbl);\n\nvar res = tbl.Select(x => x.ProcedureDate.Year == 2010);\n"
},
{
"answer_id": 15299731,
"author": "jocull",
"author_id": 97964,
"author_profile": "https://Stackoverflow.com/users/97964",
"pm_score": 3,
"selected": false,
"text": "Missing semicolon (;) at end of SQL statement. using System;\nusing System.Collections.Generic;\nusing System.Data.OleDb;\nusing System.IO;\nusing System.Linq;\nusing Linq2Access.Data;\n\nnamespace Linq2Access\n{\n class Program\n {\n static readonly string AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);\n static readonly string DbPath = Path.Combine(AppPath, \"Data\", \"database.accdb\");\n static readonly string DbConnString = @\"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='\" + DbPath + \"';Persist Security Info=False;\";\n\n static void Main(string[] args)\n {\n if (!File.Exists(DbPath))\n throw new Exception(\"Database file does not exist!\");\n\n using (OleDbConnection connection = new OleDbConnection(DbConnString))\n using (DataRepositoryDataContext db = new DataRepositoryDataContext(connection))\n {\n List<dbProject> projects = new List<dbProject>();\n for (int i = 1; i <= 10; i++)\n {\n dbProject p = new dbProject() { Title = \"Project #\" + i };\n for (int j = 1; j <= 10; j++)\n {\n dbTask t = new dbTask() { Title = \"Task #\" + (i * j) };\n p.dbTasks.Add(t);\n }\n projects.Add(p);\n }\n\n try\n {\n //This will fail to submit\n db.dbProjects.InsertAllOnSubmit(projects);\n db.SubmitChanges();\n Console.WriteLine(\"Write succeeded! {0} projects, {1} tasks inserted\",\n projects.Count,\n projects.Sum(x => x.dbTasks.Count));\n }\n catch(Exception ex)\n {\n Console.WriteLine(\"Write FAILED. Details:\");\n Console.WriteLine(ex);\n Console.WriteLine();\n }\n\n try\n {\n //However, if you create the items manually in Access they seem to query fine\n var projectsFromDb = db.dbProjects.Where(x => x.Title.Contains(\"#1\"))\n .OrderBy(x => x.ProjectID)\n .ToList();\n\n Console.WriteLine(\"Query succeeded! {0} Projects, {1} Tasks\",\n projectsFromDb.Count,\n projectsFromDb.Sum(x => x.dbTasks.Count));\n }\n catch (Exception ex)\n {\n Console.WriteLine(\"Query FAILED. Details:\");\n Console.WriteLine(ex);\n Console.WriteLine();\n }\n\n Console.WriteLine();\n Console.WriteLine(\"Press any key to continue...\");\n Console.ReadKey();\n }\n }\n }\n}\n"
},
{
"answer_id": 46945250,
"author": "Hannington Mambo",
"author_id": 1909689,
"author_profile": "https://Stackoverflow.com/users/1909689",
"pm_score": 1,
"selected": false,
"text": "DataGridView Private Sub ResetForm()\n\n Try\n\n Using db As New AccessDataClassesDataContext(ACCCon)\n\n Dim rows = (From row In db.AccountTypes\n Where row.AccountTypeID > 1\n Order By row.AccountTypeID Ascending\n Select row).ToList()\n Me.DataGridView1.DataSource = rows\n\n End Using\n\n Catch ex As Exception\n MessageBox.Show(\"Error: \" & vbCr & ex.ToString, \"Data Error\", MessageBoxButtons.OK)\n End Try\n\nEnd Sub\n Try\n\n If _accountTypeID = 0 Then\n Exit Sub\n End If\n\n\n Using db As New AccessDataClassesDataContext(ACCCon)\n\n 'Dim rows = (From row In db.AccountTypes\n ' Where row.AccountTypeID = _accountTypeID\n ' Order By row.AccountTypeID Ascending\n ' Select row.AccountTypeID, row.AccountType, row.LastUpdated).ToList()\n Dim rows = (From row In db.AccountTypes\n Where row.AccountTypeID = _accountTypeID\n Select row).ToList()\n\n For Each s In rows\n\n Me.AccountTypeIDTextBox.Text = s.AccountTypeID\n Me.myGuidTextBox.Text = s.myGuid\n Me.AccountTypeTextBox.Text = s.AccountType\n Me.AcHeadIDTextBox.Text = s.AcHeadID\n Me.DescriptionTextBox.Text = s.Description\n Me.LastUpdatedDateTimePicker.Value = s.LastUpdated\n\n Next\n\n End Using\n\n Catch ex As Exception\n\n End Try\n\nEnd Sub\n Dim success As Boolean = False\n Dim row As New AccountType\n\n Using db As New AccessDataClassesDataContext(ACCCon)\n\n If _accountTypeID > 0 Then\n\n row = (From r In db.AccountTypes\n Where r.AccountTypeID = _accountTypeID).ToList()(0)\n\n If String.IsNullOrEmpty(row.AccountTypeID) Then\n MessageBox.Show(\"Requested record not found\", \"Update Customer Error\")\n Return success\n End If\n\n End If\n\n Try\n\n With row\n .myGuid = Me.myGuidTextBox.Text\n .AccountType = Me.AccountTypeTextBox.Text\n .Description = Me.DescriptionTextBox.Text\n .AcHeadID = Me.AcHeadIDTextBox.Text\n .LastUpdated = Date.Parse(Date.Now())\n End With\n\n\n If _accountTypeID = 0 Then db.AccountTypes.InsertOnSubmit(row)\n db.SubmitChanges()\n\n success = True\n\n Catch ex As Exception\n MessageBox.Show(\"Error saving to Customer: \" & vbCr & ex.ToString, \"Save Data Error\")\n End Try\n\n End Using\n\n Return success\n\nEnd Function\n If _accountTypeID = 0 Then db.AccountTypes.InsertOnSubmit(row)\n db.SubmitChanges()\n Dim cmd As IDbCommand\n\n cmd = Me.Connection.CreateCommand()\n cmd.Transaction = Me.Transaction\n cmd.CommandText = query\n\n If myGuid.Trim.Length < 36 Then myGuid = UCase(System.Guid.NewGuid.ToString())\n cmd.Parameters.Add(New OleDbParameter(\"myGuid\", row.myGuid))\n cmd.Parameters.Add(New OleDbParameter(\"AccountType\", row.AccountType))\n cmd.Parameters.Add(New OleDbParameter(\"Description\", row.Description))\n cmd.Parameters.Add(New OleDbParameter(\"AcHeadID\", row.AcHeadID))\n cmd.Parameters.Add(New OleDbParameter(\"LastUpdated\", Date.Now))\n If AccountTypeID > 0 Then cmd.Parameters.Add(New OleDbParameter(\"AccountTypeID\", row.AccountTypeID))\n\n If Connection.State = ConnectionState.Closed Then Connection.Open()\n\n result = cmd.ExecuteNonQuery()\n\n cmd = Me.Connection.CreateCommand()\n cmd.Transaction = Me.Transaction\n cmd.CommandText = \"SELECT @@IDENTITY\"\n result = Convert.ToInt32(cmd.ExecuteScalar())\n Private Sub DelButton_Click(sender As Object, e As EventArgs) Handles DelButton.Click\n Using db As New AccessDataClassesDataContext(ACCCon)\n\n Dim AccountTypeID As Integer = Me.DataGridView1.CurrentRow.Cells(0).Value\n Dim row = From r In db.AccountTypes Where r.AccountTypeID = AccountTypeID\n\n For Each detail In row\n db.AccountTypes.DeleteOnSubmit(detail)\n Next\n\n Try\n db.SubmitChanges()\n Catch ex As Exception\n ' Provide for exceptions.\n MsgBox(ex)\n End Try\n\n End Using\n\nEnd Sub\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506/"
] |
295,773 | <p>I have a basic ajax application, which will not work, instead the php code is displayed in the browser. The javascript and html seem fine. I have copied the code verbatim from here:</p>
<p><a href="http://arief.aeroven.com/2008/07/30/first-ajax-script-tutorial-connecting-ajax-contain-pure-htmlphpand-javascript-to-mysql-database/" rel="nofollow noreferrer">http://arief.aeroven.com/2008/07/30/first-ajax-script-tutorial-connecting-ajax-contain-pure-htmlphpand-javascript-to-mysql-database/</a></p>
<p>and this is the php:</p>
<pre><code><?
session_start();
//start the session
$cmd = $_GET["cmd"];
$con = mysql_connect('localhost', 'root', 'indosat');
if (!con) {
die('Connection to MySQL server failed: ' . mysql_error());
//show error message (mysql_error) if connection failed
}
mysql_select_db('ajax', $con);
//select the database, in this case our database name is "ajax"
if ($cmd === 'GetEmployee') //set command value (executed from javascript ajaxlib.js)
{
sleep(10);
//give delay about 10 seconds before execute the command
//we use this sleep function so we can see the loading animation
//you can edit/remove
echo "<table border='1' width='100%'>
<tr>
<th>EmpNo</th>
<th>fName</th>
<th>lName</th>
<th>Age</th>
</tr>";
//print a table to browser to show the values
$sql = "select * from employee";
//this is query to show all records
$result = mysql_query($sql);
//execute the query & fill it to $result variable
while ($row = mysql_fetch_array($result)) {
echo "<tr>
<td>" . $row['IdEmp'] . "</td>
<td>" . $row['fName'] . "</td>
<td> " . $row['lName'] . "</td>
<td>" . $row['Age'] . "</td>
</tr>";
//print the record to the table
}
echo '</table>';
//close the table
}
mysql_close($con);
//close the mysql connection
?>
</code></pre>
<p>I don't see what the problem could be</p>
<p>edit: it is NOT the shorttags. they are enabled, andusing "long" tags makes no difference.</p>
| [
{
"answer_id": 295784,
"author": "DreamWerx",
"author_id": 15487,
"author_profile": "https://Stackoverflow.com/users/15487",
"pm_score": 2,
"selected": false,
"text": "\"<?php\""
},
{
"answer_id": 295909,
"author": "Tom",
"author_id": 26155,
"author_profile": "https://Stackoverflow.com/users/26155",
"pm_score": 1,
"selected": true,
"text": "<?php echo phpinfo(); ?> DocumentRoot"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
295,781 | <p>I'm sure there is a quick and easy way to calculate the sum of a column of values on Unix systems (using something like <code>awk</code> or <code>xargs</code> perhaps), but writing a shell script to parse the rows line by line is the only thing that comes to mind at the moment.</p>
<p>For example, what's the simplest way to modify the command below to compute and display the total for the SEGSZ column (70300)?</p>
<pre><code>ipcs -mb | head -6
IPC status from /dev/kmem as of Mon Nov 17 08:58:17 2008
T ID KEY MODE OWNER GROUP SEGSZ
Shared Memory:
m 0 0x411c322e --rw-rw-rw- root root 348
m 1 0x4e0c0002 --rw-rw-rw- root root 61760
m 2 0x412013f5 --rw-rw-rw- root root 8192
</code></pre>
| [
{
"answer_id": 295812,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 1,
"selected": false,
"text": "cut grep bc tr \\n cat <whatever> | cut -d'\\t` -f7 | grep -v <appropriate-character-class> | tr '\\n' ' ' | xargs script-that-adds-arguments\n cut man"
},
{
"answer_id": 295817,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "ipcs -mb | tail +4 | awk '{ sum += $7 } END { print sum }'\n ipcs -mb | awk 'NR > 3 { sum += $7 } END { print sum }'\n Jouni K. ipcs -mb | awk 'NR > 3 { print $7 }' | paste -sd+ | bc\n"
},
{
"answer_id": 295818,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\ntext= file(\"the_file\",\"r\")\ntotal= 0\nfor line in text:\n data = line.split()\n if data[0] in ('T', 'Shared', 'IPC'): continue\n print line\n segsize= int(data[6])\n total += segsize\nprint total\n import sys\ntotal = 0\nfor line in sys.stdin:\n ...etc...\n import sys\ntotal = 0\nfor line in sys.stdin.readlines()[3:]:\n total += int(line.split()[6])\nprint total\n import sys; print sum( [int(line.split()[6]) for line in sys.stdin.splitlines()[3:]] )\n"
},
{
"answer_id": 295872,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 1,
"selected": false,
"text": "ipcs | awk '\nBEGIN { sum = 0 }\n/0x000000/ { sum = sum + $2 }\nEND {print sum}'\n"
},
{
"answer_id": 506479,
"author": "user61853",
"author_id": 61853,
"author_profile": "https://Stackoverflow.com/users/61853",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/awk -f\n# Sum up numerical values by column (white-space separated)\n#\n# Usage: $0 [file ...]\n#\n# stern, 1999-2005\n\n{\n for(i = 1; i <= NF; ++i) {\n scale = 1\n if ($i ~ /[kK]$/) { scale = 1000 }\n if ($i ~ /[mM]$/) { scale = 1000*1000 }\n if ($i ~ /[gG]$/) { scale = 1000*1000*1000 }\n col[i] += scale * $i;\n }\n if (NF > maxnf) maxnf = NF;\n}\n\nEND {\n for(i = 1; i <= maxnf; ++i) { printf \" %.10g\", col[i] }\n print \"\";\n}\n $ head /etc/passwd | addcol -F:\n0 0 45 39 0 0 0\n"
},
{
"answer_id": 643174,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "df -h -B 1M | grep dev/sda | tr -s ' '| cut -d' ' -f3 |python -c \"import sys; print sum([int(num) for num in sys.stdin.readlines()])\"\n df -h -B 1M | python -c \"import sys; print sum([int(l.split()[2]) for l in sys.stdin.readlines() if '/dev/sda' in l])\"\n"
},
{
"answer_id": 2956944,
"author": "Peterino",
"author_id": 202834,
"author_profile": "https://Stackoverflow.com/users/202834",
"pm_score": 4,
"selected": false,
"text": "ipcs -mb | grep -w '^m ' | sed 's/^.*\\s//' | xargs | tr ' ' + | bc echo $(( $(ipcs -mb | grep -w '^m ' | sed 's/^.*\\s//' | xargs | tr ' ' +) )) SUM=$(( $(ipcs -mb | grep -w '^m ' | sed 's/^.*\\s//' | xargs | tr ' ' +) )) (( SUM=$(ipcs -mb | grep -w '^m ' | sed 's/^.*\\s//' | xargs | tr ' ' +) ))"
},
{
"answer_id": 28551661,
"author": "Alexander Stumpf",
"author_id": 2165720,
"author_profile": "https://Stackoverflow.com/users/2165720",
"pm_score": 2,
"selected": false,
"text": "+ ipcs df # df\nFilesystem 1K-blocks Used Available Use% Mounted on\nrootfs 33027952 4037420 27312812 13% /\nudev 10240 0 10240 0% /dev\ntmpfs 102108 108 102000 1% /run\n/dev/xvda1 33027952 4037420 27312812 13% /\ntmpfs 5120 0 5120 0% /run/lock\ntmpfs 204200 0 204200 0% /run/shm\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client1/web1/log\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client1/web2/log\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client1/web3/log\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client1/web4/log\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client2/web5/log\n/dev/xvda1 33027952 4037420 27312812 13% /var/www/clients/client2/web6/log\n# df | tail -n +2 | tr -s ' ' | cut -d ' ' -f 2 | paste -s -d+ | bc\n264545284\n"
},
{
"answer_id": 53010034,
"author": "Socowi",
"author_id": 6770384,
"author_profile": "https://Stackoverflow.com/users/6770384",
"pm_score": 0,
"selected": false,
"text": "tail +4 ipcs -mb | tail +4 | datamash -W sum 7\n -W"
},
{
"answer_id": 53885166,
"author": "gerrit",
"author_id": 974555,
"author_profile": "https://Stackoverflow.com/users/974555",
"pm_score": 0,
"selected": false,
"text": "input_command | awk '{s1+=$1;s2+=$2;s3+=$3;s4+=$4;s5+=$5}END{print s1,s2,s3,s4,s5}'\n"
},
{
"answer_id": 63537416,
"author": "druid62",
"author_id": 11091125,
"author_profile": "https://Stackoverflow.com/users/11091125",
"pm_score": 0,
"selected": false,
"text": "perldoc perlrun perldoc perlvar $ df |perl -aE'$.<2or$u+=$F[2]}{say\"Used: $u\"'\nUsed: 129016836\n $ df -h |perl -anE'$|=1;\n BEGIN{%M=(\"\"=>1,k=>1e3,K=>2**10,M=>2**20,G=>2**30,T=>2**40);%D=reverse%M}\n print;\n if($.<2){@V=map length(),/\\s*+[^a-z]\\S*(?:\\s+[a-z]+)*/g;next} # parse header\n ($w=($_==$#V)+length($F[$_])-$V[$_])>0 and do{$V[$_]+=$w;$_<$#V and $V[$_+1]-=$w} for 0..$#F; # optimize column widths\n $S[$_]+=($F[$_]=~/^(\\d+(?:[.]\\d*)?)([kKMGT])?$/aa?$1*$M{($D||=$2)&&$2}:-Inf)for 0..$#F; # scale numeric values\n}{ # show results\n say join(\"\",map+(\"-\"x($V[$_]-1)).($S[$_]<0?\"^\":\"+\"),0..$#V);\n $V[$_]+=$V[$_-1]for 1..$#V;\n if($D){for$s(@S){@s=sort{$b<=>$a}grep{$_<$s}keys%D and$s=sprintf\"%.1f%s\",$s/$s[0],$D{$s[0]}}}\n say sprintf+(\"%s%*s\"x@S),map{((!$p||($_>0 and length($S[$_])>=($w=($V[$_]-$V[$_-1])))?(($q?\"\\n\":(($p=$q=1)&&\"\")),$V[$_]):(\"\",0+$w)),$S[$_])}grep{$S[$_]!=-Inf}0..$#S;\n'\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17035/"
] |
295,798 | <p>I'm looking for a module or some way to obtain the information about the content of a file. </p>
<p>The same sort of thing that the Linux "file" command does, but in Perl language.</p>
| [
{
"answer_id": 296070,
"author": "David Ameller",
"author_id": 19689,
"author_profile": "https://Stackoverflow.com/users/19689",
"pm_score": -1,
"selected": false,
"text": "$res = `file a.txt`;\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19689/"
] |
295,811 | <p>I have a .jar file that i've placed in my D:\Coldfusion8\wwwroot\web-inf\lib\ directory. The file is abcdef.jar</p>
<p>This is my first time doing this, not sure what the path should be in my createObject().</p>
<pre><code><cfset abcObj = createObject("java","com.abcdef") />
<cfset result = acbObj.doStuff("123456") />
</code></pre>
<p>But when I run it, I get </p>
<pre><code>Object Instantiation Exception.
Class not found: com.vp4jo_b
</code></pre>
<p>What am I missing in the path?</p>
| [
{
"answer_id": 295918,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "CreateObject()"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
295,827 | <p><strong>Background</strong></p>
<p>We have a web application in which several developers have written several .js files that manipulate the DOM and the problem of duplicate function names has crept into our application.</p>
<p><strong>Question</strong></p>
<p>Can anyone recommend a tool that will warn us when we accidentally write a web page with two javascript functions with the same name? </p>
<p><strong>Example</strong></p>
<p><em>HTML page</em></p>
<pre><code><script language="JavaScript" src="test.js" type="text/javascript"></script>
<script>function foo() {alert('bar');}</script>
</code></pre>
<p><em>test.js</em></p>
<pre><code>function foo() {alert('foo');}
</code></pre>
<p>Since foo() is declared twice in the page, apparently only the one that takes precedence is loaded. </p>
<p>The tools I've used seem to ignore this. Firebug only shows the loaded function. Netbeans will show both functions in navigator (without a warning), but only looks at one file at a time (ie, I can't point it at the HTML file and see it and the .js at the same time.) and web developer extensions allows me to look at everything at once, but no errors or warnings. Firefox's error console also throws no warning or error. Neither does IE.</p>
<p>Thanks!</p>
| [
{
"answer_id": 296393,
"author": "picardo",
"author_id": 32816,
"author_profile": "https://Stackoverflow.com/users/32816",
"pm_score": 4,
"selected": true,
"text": "var myNamespace = function (){\n var myPrivateProperty;\n var myPrivateFunction = function(){};\n return{\n\n myPublicProperty: '',\n myPublicFunction: function(){}\n\n\n }\n\n }();\n myNamespace.myPublicFunction();\n myNamespace.myPublicProperty;\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1181/"
] |
295,832 | <p>Consider the following code in VB9:</p>
<pre><code>Dim text = "Line1<br/>Line2"
Dim markup = <span><%= text %></span>.ToString
</code></pre>
<p>While I was hoping markup would end up being <code><span>Line1<br/>Line2</span></code>, it actually evaluates to <code><span>Line1&lt;br/&gt;Line2</span></code>.</p>
<p>Is there any way to get the value of the variable not to be HTML encoded?</p>
<p>P.S.: This is an oversimplified example of what I'm trying to do. I know this could be rewritten a number of ways to make it work, but the way my code is constructed, un-encoding the variable would be optimal. If that's not possible, then I'll go down a different road.</p>
<p>More detail: The "text" is coming from a database, where a user can enter free-form text, with carriage returns. The output is HTML, so somehow I need to get the value from the database and convert the carriage returns to line breaks.</p>
| [
{
"answer_id": 295891,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": true,
"text": "<br/> Dim text2 = <a>Line<br/>Line</a>\nDim markup2 = <span><%= text2 %></span>.ToString\n <a> Dim text = \"Line1<br/>Line2\"\nDim text2 = XElement.Parse(\"<a>\" + text + \"</a>\")\nDim markup = <span><%= text2.Nodes %></span>.ToString\n"
},
{
"answer_id": 355140,
"author": "Robin Rodricks",
"author_id": 41021,
"author_profile": "https://Stackoverflow.com/users/41021",
"pm_score": 1,
"selected": false,
"text": "Dim markup As XElement = <span>Line1<br/>Line2</span>\n"
},
{
"answer_id": 72134160,
"author": "Brain2000",
"author_id": 231839,
"author_profile": "https://Stackoverflow.com/users/231839",
"pm_score": 0,
"selected": false,
"text": "Dim markup = <span><%= text %></span>.ToHTML()\n ''' <summary>\n''' Convert an XElement to a string. Differences between this and .ToString():<br />\n''' 1) Will not throw errors on invalid characters<br />\n''' 2) Will not escape characters, such as &<br />\n''' 3) Will not include <![CDATA[ ]]> wrappers around text<br />\n''' 4) Works with .XElementRaw( ) extension to add a \"raw\" string (i.e. malformed HTML) directly into the flow\n''' </summary>\n''' <param name=\"myElement\"></param>\n''' <returns></returns>\n<Extension()>\nPublic Function ToHTML(ByVal myElement As XElement, Optional OmitXmlDeclaration As Boolean = True) As String\n 'set up XSL transform, set checkCharacters to false\n Static firstTime As Boolean = True\n Static xslt As Xsl.XslCompiledTransform = New Xsl.XslCompiledTransform()\n Static settings As XmlWriterSettings\n\n 'if element is null then it cannot contain any HTML\n If myElement Is Nothing Then Return \"\"\n\n If firstTime Then\n SyncLock xslt\n If firstTime Then\n Dim xslDefinition As XElement = <xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output media-type=\"text/html\" method=\"html\" omit-xml-declaration=\"yes\"/>\n <xsl:template match=\"/|*|@*|comment()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n </xsl:template>\n <xsl:template match=\"processing-instruction('pcr1Raw')\">\n <xsl:value-of select=\".\" disable-output-escaping=\"yes\"/>\n </xsl:template>\n <xsl:template match=\"text()\">\n <xsl:value-of select=\".\" disable-output-escaping=\"no\"/>\n </xsl:template>\n </xsl:stylesheet>\n\n xslt.Load(xslDefinition.CreateReader())\n settings = xslt.OutputSettings.Clone() 'need clone or else most properties are readonly\n settings.CheckCharacters = False\n settings.DoNotEscapeUriAttributes = True\n settings.NewLineOnAttributes = False\n settings.NewLineHandling = NewLineHandling.None\n settings.Indent = False\n settings.WriteEndDocumentOnClose = False\n settings.ConformanceLevel = ConformanceLevel.Fragment\n\n firstTime = False\n End If\n End SyncLock\n End If\n\n 'now run the actual transform\n Dim sb = New Text.StringBuilder()\n Using w = XmlWriter.Create(sb, settings)\n xslt.Transform(myElement.CreateReader(), w)\n End Using\n\n If OmitXmlDeclaration = False Then\n Dim decl As New XDeclaration(\"1.0\", \"utf-8\", \"yes\")\n Return decl.ToString() & vbCrLf & sb.ToString()\n Else\n Return sb.ToString()\n End If\nEnd Function\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
295,833 | <p>Could someone explain why this works in C#.NET 2.0:</p>
<pre><code> Nullable<DateTime> foo;
if (true)
foo = null;
else
foo = new DateTime(0);
</code></pre>
<p>...but this doesn't:</p>
<pre><code> Nullable<DateTime> foo;
foo = true ? null : new DateTime(0);
</code></pre>
<p>The latter form gives me an compile error "Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'."</p>
<p>Not that I can't use the former, but the second style is more consistent with the rest of my code.</p>
| [
{
"answer_id": 295842,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 9,
"selected": true,
"text": "null DateTime DateTime? foo;\nfoo = true ? (DateTime?)null : new DateTime(0);\n Nullable<DateTime> DateTime?"
},
{
"answer_id": 295859,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "??\n // Left hand is the nullable type, righthand is default if the type is null.\nNullable<DateTime> foo;\nDateTime value = foo ?? new DateTime(0);\n"
},
{
"answer_id": 12144593,
"author": "newfurniturey",
"author_id": 1518087,
"author_profile": "https://Stackoverflow.com/users/1518087",
"pm_score": 2,
"selected": false,
"text": "default Nullable<DateTime> foo;\nfoo = true ? default(DateTime) : new DateTime(0);\n DateTime? foo;\nfoo = true ? default(DateTime) : new DateTime(0);\n default nullable null DateTime foo;\nfoo = true ? default(DateTime) : new DateTime(0);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38258/"
] |
295,836 | <p>When using CDT I would like to have std::string show up in the 'variable' debug window with the string it contains. For instance if it is currently holding the word <em>"history"</em> I would like to see <strong>history</strong> in the debugger window labeled "variables". </p>
<p>I think that there is a general way to have it drill down into objects but I can't put my finger on it. Does anyone out there know how to do this?</p>
<p>This would also be useful for me to use when outputting just a single field from a complex object.</p>
<p>Thanks,
Bill</p>
| [
{
"answer_id": 444448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "up print std::string"
},
{
"answer_id": 7463960,
"author": "Chris Seddon",
"author_id": 951592,
"author_profile": "https://Stackoverflow.com/users/951592",
"pm_score": 1,
"selected": false,
"text": "svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python"
},
{
"answer_id": 14265532,
"author": "William Symionow",
"author_id": 1683291,
"author_profile": "https://Stackoverflow.com/users/1683291",
"pm_score": 1,
"selected": false,
"text": " MinGw-get.exe install gdb-python\n PYTHONPATH should be C:\\Python27\\Lib (or similar)\n PYTHONHOME should be C:\\Python27\n %PYTHONHOME%;...\n python\nimport sys\nsys.path.insert(0, 'C:/MinGW/share/gcc-4.6.1/python') \nfrom libstdcxx.v6.printers import register_libstdcxx_printers\nregister_libstdcxx_printers (None)\nend\n C:\\MinGW\\bin\\gdb-python27.exe .gdbinit --OR--\n 835,059 4^done\n835,059 (gdb) \n835,059 5-enable-pretty-printing\n835,069 5^done\n....\n835,129 12^done\n835,129 (gdb) \n835,129 13source C:\\MinGW\\bin\\.gdbinit\n835,139 &\"source C:\\\\MinGW\\\\bin\\\\.gdbinit\\n\"\n835,142 13^done\n835,142 (gdb) \n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1265473/"
] |
295,839 | <p>I am using following code to embed files, video with <code>.wmv</code> extension, that is not working in Firefox. It's working fine in IE.</p>
<pre><code>document.getElementById("QuestionMedia").innerHTML +=
'<OBJECT ID="MediaPlayer" WIDTH="350" HEIGHT="280" CLASSID="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"STANDBY="Loading Windows Media Player components..." TYPE="application/x-oleobject">' +
'<PARAM NAME="FileName" VALUE="video/' + Question.Media + '">' +
'<PARAM name="autostart" VALUE="false">' +
'<PARAM name="ShowControls" VALUE="true">' +
'<param name="ShowStatusBar" value="false">' +
'<PARAM name="ShowDisplay" VALUE="false">' +
'<EMBED TYPE="video/x-ms-wmv " SRC="video/' + Question.Media + '" NAME="MediaPlayer" WIDTH="350" HEIGHT="280" ShowControls="1" ShowStatusBar="0" ShowDisplay="0" autostart="1"> </EMBED>' +
'</OBJECT>';
</code></pre>
<p>Please let me know what would I do to make it work..?</p>
| [
{
"answer_id": 405517,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<!-- begin embedded WindowsMedia file... -->\n<table border='0' cellpadding='0' align=\"center\">\n <tr><td>\n <OBJECT id='mediaPlayer' width=\"704\" height=\"573\" classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>\n <param name='fileName' value=\"../content/Video/video.wmv\">\n <param name='animationatStart' value='true'>\n <param name='transparentatStart' value='true'>\n <param name='autoStart' value=\"true\"> \n <param name='showControls' value=\"true\"> <param name='loop' value=\"true\">\n <EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols=\"true\" showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width=\"704\" height=\"573\" src=\"../content/Video/video.wmv\" autostart=\"true\" designtimesp='5311' loop=\"true\">\n </EMBED>\n </OBJECT>\n </td></tr>\n<!-- ...end embedded WindowsMedia file -->\n<!-- begin link to launch external media player... -->\n <tr><td align='center'>\n </td></tr>\n</table>\n"
},
{
"answer_id": 447130,
"author": "Devon",
"author_id": 13850,
"author_profile": "https://Stackoverflow.com/users/13850",
"pm_score": 0,
"selected": false,
"text": "<embed src=\"/media/video.wmv\">\n <embed src=\"http://mysite.com/media/video.wmv\">\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38260/"
] |
295,849 | <p>In Perl</p>
<pre><code>print "a" x 3; # aaa
</code></pre>
<p>In C# </p>
<pre><code>Console.WriteLine( ??? )
</code></pre>
| [
{
"answer_id": 295856,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "new string('a',3) Enumerable.Repeat(\"a\",3) static void Main()\n {\n string foo = \"foo\";\n string bar = foo.Repeat(3);\n }\n // stuff this bit away in some class library somewhere...\n static string Repeat(this string value, int count)\n {\n if (count < 0) throw new ArgumentOutOfRangeException(\"count\");\n if (string.IsNullOrEmpty(value)) return value; // GIGO \n if (count == 0) return \"\";\n StringBuilder sb = new StringBuilder(value.Length * count);\n for (int i = 0; i < count; i++)\n {\n sb.Append(value);\n }\n return sb.ToString();\n }\n"
},
{
"answer_id": 295857,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 3,
"selected": false,
"text": "Console.WriteLine(new string('a', 3))\n"
},
{
"answer_id": 295959,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": -1,
"selected": false,
"text": "static class StringHelpers\n{\n public static string Repeat(this string Template, int Count)\n {\n string Combined = Template;\n while (Count > 1) {\n Combined += Template;\n Count--;\n }\n return Combined;\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n string s = \"abc\";\n Console.WriteLine(s.Repeat(3));\n Console.ReadKey();\n }\n"
},
{
"answer_id": 720909,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 3,
"selected": false,
"text": "public static string Repeat(string value, int count)\n{\n return new StringBuilder().Insert(0, value, count).ToString();\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
] |
295,860 | <p>As a primarily Windows developer, perhaps I'm missing something cultural in the Linux community, but it has always confused me.</p>
<p>When downloading something that the files are first put into a <code>.tar</code> archive then <em>zipped</em>. Why the two-step process? Doesn't <em>zipping</em> achieve the file grouping? Is there some other benefit that I'm not aware of?</p>
| [
{
"answer_id": 295865,
"author": "Stewart Johnson",
"author_id": 6408,
"author_profile": "https://Stackoverflow.com/users/6408",
"pm_score": 8,
"selected": true,
"text": "bzip gzip zip pkzip bzip gzip"
},
{
"answer_id": 295913,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "tar tar -czf output.tar.gz directory1 ...\n\ntar -cjf output.tar.bz2 directory2 ...\n -c -d tar -cf output.tar.xxx --use-compress-program=xxx directory1 ...\n gzip bzip2 tar tar -xf output.tar.gz\ntar -xf output.tgz # A synonym for the .tar.gz extension\ntar -xf output.tar.bz2\n cpio tar pack compress pack gzip zip bzip2 gzip cpio tar -T - cpio cpio cpio cd /old/location; find . -depth -print | cpio -pvdumB /new/place\n -depth find rm -fr /new/place -depth cpio"
},
{
"answer_id": 296011,
"author": "Astra",
"author_id": 5862,
"author_profile": "https://Stackoverflow.com/users/5862",
"pm_score": 3,
"selected": false,
"text": "tar -cfvj destination.tar.bz2 *.files tar -cfvz destination.tar.gz *.files tar -xfvj archive.tar.bz2 -C destination_path tar -xfvz archive.tar.gz -C destination_path"
},
{
"answer_id": 296642,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 4,
"selected": false,
"text": "tar gzip files.gz.tar pkzip"
},
{
"answer_id": 15491081,
"author": "mikyra",
"author_id": 2056411,
"author_profile": "https://Stackoverflow.com/users/2056411",
"pm_score": 2,
"selected": false,
"text": "tar tar gzip bz2 xz tar tar tar tar --i-hope-you-rember-this-one --this-time-its-another-one --if-you-had-used-tool-bs-switch-your-files-would-have-been-deleted-now"
},
{
"answer_id": 50012434,
"author": "WinEunuuchs2Unix",
"author_id": 6929343,
"author_profile": "https://Stackoverflow.com/users/6929343",
"pm_score": 0,
"selected": false,
"text": "tar setup.exe install.exe .dll .deb .deb sudo apt install <package_name>\n .deb .tar.gz apt"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/767/"
] |
295,861 | <p>Being a Windows developer I'm currently working on my own project using LAMP. I understand what I need to know of PHP and MySQL, but Linux looks huge and it's not clear where to start and what is enough given my goals.
And my goals are to grasp general concepts, being able to deploy the project to a hosting provider and to be able to monitor the site's performance in order to spot problems, load issues, etc.</p>
<p>I know, the best solution is to get a Linux administrator to do that, but before I can do that I need to do it myself.</p>
| [
{
"answer_id": 296057,
"author": "Astra",
"author_id": 5862,
"author_profile": "https://Stackoverflow.com/users/5862",
"pm_score": 1,
"selected": false,
"text": "sudo /etc/init.d/apache stop sudo /etc/init.d/apache start ps -aux sudo kill -s TERM <process_id> sudo apt-get install php5-cli sudo apt-get update && sudo apt-get upgrade"
},
{
"answer_id": 296069,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "mod_php echo $PATH"
},
{
"answer_id": 296368,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 1,
"selected": false,
"text": "$PATH history cd ls rm tail kill ps top /proc sed s,orig,repl,g iptables netstat traceroute man info --help pacman -S <name> apt-get install <name> /etc/init.d /etc/rc.d quota /etc/fstab df useradd groupadd /etc/passwd /etc/group syslog dmesg hdparm"
},
{
"answer_id": 297054,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 1,
"selected": false,
"text": "vimtutor"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28098/"
] |
295,877 |
<p>I'd like to group the digits in a double by thousands, but also output however number of decimals are actually in the number. I cannot figure out the format string. </p>
<pre class="lang-cs prettyprint-override"><code> 1000 => 1,000
100000 => 100,000
123.456 => 123.456
100000.21 => 100,000.21
100200.123456 => 100,200.123456
</code></pre>
<p>Disclaimers (it's not as straight forward as you think): </p>
<ul>
<li>Please do not point me to <a href="https://stackoverflow.com/questions/105770/net-stringformat-to-add-commas-in-thousands-place-for-a-number">this question</a> it does not answer my question</li>
<li>Please do not point me to <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="nofollow noreferrer">MS</a><a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx#" rel="nofollow noreferrer">DN</a>, the articles have not helped me. (If you believe I'm reading them incorrectly, read them yourself and post the correct answer)</li>
<li><code>.ToString("n")</code> does not work, it rounds the digits</li>
</ul>
| [
{
"answer_id": 295902,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "Dim vals() As Double = {1000, 100000, 123.456, 100000.21, 100200.123456}\nFor Each val As Double in vals\n Console.WriteLine(val.ToString(\"###,###.#########\"))\nNext val\n double[] vals = new double[] {1000, 100000, 123.456, 100000.21, 100200.123456};\nforeach (double val in vals)\n{\n Console.WriteLine(val.ToString(\"###,###.#########\"));\n}\n"
},
{
"answer_id": 295905,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": true,
"text": "public void Code(params string[] args)\n{\n Print(1000);\n Print(100000);\n Print(123.456);\n Print(100000.21 );\n Print(100200.123456);\n}\n\nvoid Print(double n)\n{\n Console.WriteLine(\"{0:###,###.#######}\", n);\n}\n\n1,000\n100,000\n123.456\n100,000.21\n100,200.123456\n"
},
{
"answer_id": 295947,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 0,
"selected": false,
"text": "public static string FormatNumber(double num)\n{\n string s = num.ToString();\n string result = \"\";\n\n if(s.IndexOf('.') != -1)\n {\n result = s.Substring(s.IndexOf('.'));\n s = s.Substring(0, s.IndexOf('.'));\n }\n\n while (s.Length > 3)\n {\n result = \",\" + s.Substring(s.Length - 3);\n s = s.Substring(0, s.Length - 3);\n }\n if (s.Length == 0)\n return result.Substring(1);\n return s + result;\n}\n"
},
{
"answer_id": 6114156,
"author": "Rich Newman",
"author_id": 768148,
"author_profile": "https://Stackoverflow.com/users/768148",
"pm_score": 2,
"selected": false,
"text": "\"#,##0.#################\" double[] vals = new double[] { 0.0, 0.1234, -0.1234, 1.0, \n 123456789.123456, 123456789.0, \n 0.123456789123456 };\nforeach (double val in vals) \n{ \n Console.WriteLine(val + \": \" + val.ToString(\"#,##0.#################\")); \n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8435/"
] |
295,897 | <p>We have 50+ Java batch processes that run at different times of the day. They run on a Solaris box, and are started via cron. Currently, the only way we only know if they succeed or fail is by an email generated at the end of each batch process. We have a support team that monitors these emails. Recently, we've had issues with emails not being received, even though the batches are running. There must be a better way.</p>
<p>Without having to reinvent the wheel, are there any open source batch monitoring applications?</p>
<p>And a more general question, what is the best way to monitor batch processes?</p>
| [
{
"answer_id": 295941,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 3,
"selected": true,
"text": "Schedule Tasks cron"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29962/"
] |
295,900 | <p>I am using a System.Random object which is instantiated with a fixed seed all thoughout the application. I am calling the NextDouble method and after some time passed I am getting 0.0 as result.</p>
<p>Is there any remedy to this, has anyone else encountered this ?</p>
<p>EDIT: I have one seed for the whole run which is set to 1000 for convience sake. The random.NextDouble is called several hundred thousand times. It is an optimizer application and could run for couple hours, but this actually happens after 10-0 mins of execution. I have recently added little bit more random calls to the app.</p>
| [
{
"answer_id": 295955,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 5,
"selected": true,
"text": "class ThreadSafeRandom\n{\n private static Random random = new Random();\n\n public static int Next()\n {\n lock (random)\n {\n return random.Next();\n }\n }\n}"
},
{
"answer_id": 295957,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 2,
"selected": false,
"text": "Private Shared _rnd As System.Random()\nPublic Shared Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer\n If _rnd Is Nothing Then\n _rnd = New System.Random()\n End If\n Return rnd.Next(low, high)\nEnd Function\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] |
295,919 | <p>I can't seem to figure out what I am doing wrong here. I publish my website to my server and when I try to run it I get the following exception:</p>
<blockquote>
<p>Could not load the assembly 'App_Web_kh7-x3ka'. Make sure that it is compiled before accessing the page.</p>
</blockquote>
<p>Has anyone else ever encountered this?</p>
| [
{
"answer_id": 296289,
"author": "ChrisAnnODell",
"author_id": 1758,
"author_profile": "https://Stackoverflow.com/users/1758",
"pm_score": 6,
"selected": true,
"text": "<%@Page /> inherits=\"yourPageClass, App_Web_kh7-x3ka\" App_Web_XXXX CodeFile=\"yourPageFile.aspx.cs\" <%@Page /> App_Web_XXXX"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20748/"
] |
295,920 | <p>Is there a way to prematurely abort a transaction? Say, I have sent a command to the database which runs five minutes and after four, I want to abort it.</p>
<p>Does JDBC define a way to send a "stop whatever you are doing on this connection" signal to the DB?</p>
| [
{
"answer_id": 295950,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 4,
"selected": false,
"text": "java.sql.Statement.setQueryTimeout(seconds)\n SQLException execute()"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295920",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34088/"
] |
295,925 | <pre><code>/* I start with this: */
<Report>
<prop1>4</prop1>
<prop2>2255</prop2>
<prop3>true</prop3>
<prop4>false</prop4>
<prop5>true</prop5>
</Report>
/* I want this result (change the value of node "prop5"): */
<Report>
<prop1>4</prop1>
<prop2>2255</prop2>
<prop3>true</prop3>
<prop4>false</prop4>
<prop5>false</prop5>
</Report>
/* I tried this: */
var reportXML:XML =
<Report>
<prop1>4</prop1>
<prop2>2255</prop2>
<prop3>true</prop3>
<prop4>false</prop4>
<prop5>true</prop5>
</Report>;
var myArray:Array = [{xmlNodeName: "prop5", value: false}];
for each (var item:Object in myArray)
{
report.xml[item.xmlNodeName] = item.value.toString();
}
/* But this just adds a new node, resulting in this: */
<Report>
<prop1>4</prop1>
<prop2>2255</prop2>
<prop3>true</prop3>
<prop4>false</prop4>
<prop5>true</prop5>
<prop5>false</prop5>
</Report>;
</code></pre>
| [
{
"answer_id": 295932,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": -1,
"selected": false,
"text": "report.prop5[0] = false;\n"
},
{
"answer_id": 296859,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 1,
"selected": false,
"text": "private var reportXML:XML = \n <Report>\n <prop1>4</prop1>\n <prop2>2255</prop2>\n <prop3>true</prop3>\n <prop4>false</prop4>\n <prop5>true</prop5>\n </Report>;\n\nprivate function changeXML():void {\n reportXML.prop5[0] = 'false';\n trace(reportXML.prop5); // traces 'false'\n}\n"
},
{
"answer_id": 333118,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 4,
"selected": true,
"text": " var reportXML:XML = \n <Report>\n <prop1>4</prop1> \n <prop2>2255</prop2> \n <prop3>true</prop3> \n <prop4>false</prop4> \n <prop5>true</prop5> \n </Report>;\n\n var myArray:Array = [{xmlNodeName: \"prop5\", value: false}];\n\n for each (var item:Object in myArray)\n {\n reportXML[item.xmlNodeName] = item.value.toString();\n }\n\n trace(reportXML);\n"
},
{
"answer_id": 3938615,
"author": "manu",
"author_id": 476430,
"author_profile": "https://Stackoverflow.com/users/476430",
"pm_score": 1,
"selected": false,
"text": "var node:XML\ninp = new textfield(style, node.text());\ninp.addEventListener(TextEvent.TEXT_INPUT, change, false, 0, true);\naddChild(inp);\n\nprivate function change(e:TextEvent):void\n {\n XML(node.parent())[node.name()][node.childIndex()] = inp.text+e.text;\n }\n"
},
{
"answer_id": 4668463,
"author": "Jawdy",
"author_id": 504637,
"author_profile": "https://Stackoverflow.com/users/504637",
"pm_score": 2,
"selected": false,
"text": "var tempString:String = \"<XML_PARENT><SOME_SUB_NODE>\";\ntempString += \"<SOMETHING_ELSE value=\\\"\" + someTextField.text + \"\\\"/>\";\ntempString += \"</SOME_SUB_NODE></XML_PARENT>\";\n\nvar xmlObj:XML = new XML( tempString );\n <XML_PARENT>\n <SOME_SUB_NODE>\n <SOMETHING_ELSE value=\"\"/>\n </SOME_SUB_NODE>\n<XML_PARENT>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31298/"
] |
295,936 | <p>How could I setup a nice indice on <code>cap:deploy</code>?</p>
<p>I want the remote server to nice the <code>cp</code> commands like so: </p>
<pre><code>nice -n 19 cp ...
</code></pre>
| [
{
"answer_id": 295932,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": -1,
"selected": false,
"text": "report.prop5[0] = false;\n"
},
{
"answer_id": 296859,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 1,
"selected": false,
"text": "private var reportXML:XML = \n <Report>\n <prop1>4</prop1>\n <prop2>2255</prop2>\n <prop3>true</prop3>\n <prop4>false</prop4>\n <prop5>true</prop5>\n </Report>;\n\nprivate function changeXML():void {\n reportXML.prop5[0] = 'false';\n trace(reportXML.prop5); // traces 'false'\n}\n"
},
{
"answer_id": 333118,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 4,
"selected": true,
"text": " var reportXML:XML = \n <Report>\n <prop1>4</prop1> \n <prop2>2255</prop2> \n <prop3>true</prop3> \n <prop4>false</prop4> \n <prop5>true</prop5> \n </Report>;\n\n var myArray:Array = [{xmlNodeName: \"prop5\", value: false}];\n\n for each (var item:Object in myArray)\n {\n reportXML[item.xmlNodeName] = item.value.toString();\n }\n\n trace(reportXML);\n"
},
{
"answer_id": 3938615,
"author": "manu",
"author_id": 476430,
"author_profile": "https://Stackoverflow.com/users/476430",
"pm_score": 1,
"selected": false,
"text": "var node:XML\ninp = new textfield(style, node.text());\ninp.addEventListener(TextEvent.TEXT_INPUT, change, false, 0, true);\naddChild(inp);\n\nprivate function change(e:TextEvent):void\n {\n XML(node.parent())[node.name()][node.childIndex()] = inp.text+e.text;\n }\n"
},
{
"answer_id": 4668463,
"author": "Jawdy",
"author_id": 504637,
"author_profile": "https://Stackoverflow.com/users/504637",
"pm_score": 2,
"selected": false,
"text": "var tempString:String = \"<XML_PARENT><SOME_SUB_NODE>\";\ntempString += \"<SOMETHING_ELSE value=\\\"\" + someTextField.text + \"\\\"/>\";\ntempString += \"</SOME_SUB_NODE></XML_PARENT>\";\n\nvar xmlObj:XML = new XML( tempString );\n <XML_PARENT>\n <SOME_SUB_NODE>\n <SOMETHING_ELSE value=\"\"/>\n </SOME_SUB_NODE>\n<XML_PARENT>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,938 | <p>I have an issue with EMMA where it is correctly covering all my various Java projects except one.
I am puzzled as to why this occurs as the ANT script appears to be correct. The following expected output is given:</p>
<pre><code> [echo] c:\cc_local_home\emmadata\ProjectName
[instr] processing instrumentation path ...
[instr] instrumentation path processed in 1876 ms
[instr] [84 class(es) instrumented, 0 resource(s) copied]
[instr] metadata merged into [c:\cc_local_home\data\2008-11-17_14.35.19\coverage.emma] {in 62 ms}
</code></pre>
<p>The above is generated by the following piece of ANT script:</p>
<pre><code><target name="emma" depends="init" if="use.emma">
<echo message="${emma.bin}" />
<emma enabled="true">
<instr instrpath="${test.bin}" destdir="${emma.bin}" metadatafile="${test.data.dir}/coverage.emma" merge="true">
<filter excludes="*Test*,*test*" />
<filter excludes="*Exception" />
<filter excludes="*AppConstants" />
</instr>
</emma>
</target>
</code></pre>
<p>After the JUnit tests are run, the following is logged.</p>
<p>emma.report:
[report] processing input files ...<br>
[report] 1 file(s) read and merged in 16 ms<br>
[report] nothing to do: no runtime coverage data found in any of the data files </p>
<p>And no coverage report is generated.</p>
<p>I am certain that the coverage.emma files are being linked correctly so why is EMMA not covering the code?</p>
<p>The <code>emma.report</code> task looks like the following:</p>
<pre><code><target name="emma.report" if="use.emma">
<emma enabled="true">
<report sourcepath="${test.reports.dir}">
<infileset dir="${test.data.dir}" includes="*.emma" />
<html outfile="${test.reports.dir}/coverage.html" />
</report>
</emma>
</target>
</code></pre>
| [
{
"answer_id": 295966,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "<emma.report> Ant -verbose"
},
{
"answer_id": 296355,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<target name=\"emma.report\" if=\"use.emma\">\n <emma enabled=\"true\">\n <report sourcepath=\"${test.reports.dir}\"> \n <infileset dir=\"${test.data.dir}\" includes=\"*.emma\" /> \n <html outfile=\"${test.reports.dir}/coverage.html\" /> \n </report>\n </emma>\n</target>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
295,939 | <p>Is there a way to print out the diffs like they show when you open them with "gvim -d", with all the common code folded away and only the diffs showing in context? I tried the print menu option, but it printed the entire file that I was currently "in", rather than printing the folded diffs.</p>
| [
{
"answer_id": 298775,
"author": "Gowri",
"author_id": 3253,
"author_profile": "https://Stackoverflow.com/users/3253",
"pm_score": 3,
"selected": true,
"text": ":he convert-to-HTML\n"
},
{
"answer_id": 9908506,
"author": "codeape",
"author_id": 3571,
"author_profile": "https://Stackoverflow.com/users/3571",
"pm_score": 2,
"selected": false,
"text": "$ diff -y --suppress-common-lines oldfile newfile | \\\n a2ps -l 130 --columns 1\n"
},
{
"answer_id": 9914814,
"author": "ZyX",
"author_id": 273566,
"author_profile": "https://Stackoverflow.com/users/273566",
"pm_score": 1,
"selected": false,
"text": "TOhtml g:html_diff_one_file :Format diffformat :Format d"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3333/"
] |
295,948 | <p>Sometimes when running selenium, it displays a message similar to:</p>
<blockquote>
<p>WARN - Invalid length: Content-Length=798242 written=8192</p>
</blockquote>
<p>And then Selenium stops responding. The website under automation runs on ASP.NET, and served up via IIS.</p>
<p>How do I prevent Selenium from stopping due to whatever error this is?</p>
| [
{
"answer_id": 5122222,
"author": "Wesley Wiser",
"author_id": 124538,
"author_profile": "https://Stackoverflow.com/users/124538",
"pm_score": 0,
"selected": false,
"text": "Response.ClearContent();\nstring data = GetSomeData();\nResponse.Write(data);\nResponse.Flush();\nResponse.Close();\n Response.AddHeader(\"Content-Length\", data.Length.ToString());\n Response.ClearContent();\nstring data = GetSomeData();\nResponse.AddHeader(\"Content-Length\", data.Length.ToString());\nResponse.Write(data);\nResponse.Flush();\nResponse.Close();\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13172/"
] |
295,952 | <p>Suppose I want to create a set of observers based on type. That is to say, when they are notified of an event, they are told the type of one of the arguments and then decides whether or not to act based on if it can operate on that type.</p>
<p>Are there any simple ways to do this? I figured this would be fairly simple to do with generics, but that seems to be turning out to be harder than I imagined. And I would prefer not to have to deal with casting a bunch of references to object if I can avoid it.</p>
<p>Where I'm getting stuck is in doing this:</p>
<pre><code>public delegate void NotifyDelegate<T>(IEnumerator<T> loadable, NotifyArgs na);
interface IObserver
{
void Notify<T>(IEnumerator<T> loadable, NotifyArgs na);
}
class Subject
{
NotifyDelegate notifier; //won't compile: needs type args
void Register(IObserver o)
{
notifier += o.Notify;
}
}
</code></pre>
<p>Of course, I could make the Subject generic as well, but then I have to have a separate Subject for each type. Does anyone have any advice here? Is there some piece of functionality that I'm missing somewhere or am I overcomplicating this?</p>
<p><strong>UPDATE</strong>: I did oversimplify the arguments that Notify and NotifyDelegate take. Instead of this:</p>
<pre><code>public delegate void NotifyDelegate<T>(NotifyArgs na);
</code></pre>
<p>I'm actually wanting to do something like this:</p>
<pre><code>public delegate void NotifyDelegate<T>(IEnumerator<T> loadable, NotifyArgs na);
</code></pre>
<p>What I'm basically trying to pass back and forth is data from a database. Sorry if the previous code sample confused anyone.</p>
| [
{
"answer_id": 296004,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 3,
"selected": true,
"text": "interface IObserver\n{\n}\n\nclass Subject\n{\n public Subject ()\n {\n m_observers = new List<IObserver> ();\n }\n\n public void Register (IObserver o)\n {\n m_observers.Add (o);\n }\n\n List<IObserver>\n m_observers;\n}\n public void NotifyObservers (object param)\n {\n foreach (IObserver observer in m_observers)\n {\n foreach (MethodInfo method in observer.GetType ().GetMethods (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance))\n {\n if (method.Name == \"Notify\")\n {\n ParameterInfo []\n parameters = method.GetParameters ();\n\n if (parameters.Length == 1 && parameters [0].ParameterType == param.GetType ())\n {\n method.Invoke (observer, new object [] { param });\n break;\n }\n }\n }\n }\n }\n class Observer : IObserver\n{\n public Observer (Subject s)\n {\n s.Register (this);\n }\n\n void Notify (float value)\n {\n System.Diagnostics.Trace.WriteLine (\"float value = \" + value);\n }\n\n void Notify (int value)\n {\n System.Diagnostics.Trace.WriteLine (\"int value = \" + value);\n }\n}\n\nstatic void Main (string [] args)\n{\n Subject\n s = new Subject ();\n\n Observer\n o = new Observer (s);\n\n float\n v1 = 3.14f;\n\n int\n v2 = 42;\n\n System.Diagnostics.Trace.WriteLine (\"sending float\");\n s.NotifyObservers (v1);\n System.Diagnostics.Trace.WriteLine (\"sending int\");\n s.NotifyObservers (v2);\n}\n"
},
{
"answer_id": 296500,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "interface IObserver\n{\n void Notify(NotifyArgs na);\n bool SupportsType(Type t);\n}\n\nclass Subject\n{\n List<IObserver> observers;\n\n void Register(IObserver o)\n { observers.Add(o);\n }\n\n void OnNotify(Type t, NotifyArgs args)\n {\n foreach (IObserver o in observers) \n {\n if (o.SupportsType(t)) o.Notify(args));\n }\n }\n}\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
295,956 | <p>I have a JEdit (BeanShell) macro which opens a specific file then immediately saves the file to my c:\temp folder (so that I don't accidentally update the real file).</p>
<p>Here is the bean shell code:</p>
<pre><code>logFilePath = "c:\\temp\\aj.txt";
jEdit.openFile( view , logFilePath );
_buffer = jEdit.getBuffer(logFilePath);
_buffer.save(view,"c:\\temp\\backup.txt",true);
</code></pre>
<p>This gives me the following error:</p>
<pre><code>I/O Error
Each buffer can only execute one input/output operation at a time.
Please wait until the current operation finishes
(or abort it in the I/O progress monitor) before starting another one.
</code></pre>
<p>I have tried adding a while loop to wait until <code> buffer.isLoaded() </code> is true, but that just goes into an infinite loop.<br />
What does seem to work is popping up a message box (<code> Macros.message </code>). However, I really don't want to have this unnecessary dialogue.</p>
<p>I don't know much java, so please tell me if I'm making a rookie mistake.</p>
<h2>Update:</h2>
<p>Added my own answer to show the code pointed to from <a href="https://stackoverflow.com/users/34009/serhii">Serhii's answer</a>.</p>
| [
{
"answer_id": 296361,
"author": "Serxipc",
"author_id": 34009,
"author_profile": "https://Stackoverflow.com/users/34009",
"pm_score": 3,
"selected": true,
"text": "VFSManager.waitForRequests();"
},
{
"answer_id": 298291,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 2,
"selected": false,
"text": " VFSManager.waitForRequests(); jEdit.openFile() logFilePath = \"c:\\\\temp\\\\aj.txt\";\njEdit.openFile( view , logFilePath );\n\nVFSManager.waitForRequests();\n\n/* \n VFSManager.waitForRequests();\n\n jEdit waits then for the file to be completely loaded before continuing \n ... It's designed for waiting on all 'pending I/O requests'\".\n*/\n\n_buffer = jEdit.getBuffer(logFilePath);\n_buffer.save(view,\"c:\\\\temp\\\\backup.txt\",true);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7211/"
] |
295,990 | <p>I'm trying to implement a stateful web service in PHP using the SOAP extension. (Yes I know that web services are supposed to be stateless; all I really care to persist is some form of a session ID so I don't need to authenticate with every call to the service). PHP.net's API documentation is somewhat lacking on this, and there isn't much else written on it.</p>
<p>I found one page that discusses it (<a href="http://bytes.com/forum/thread160816.html" rel="nofollow noreferrer">http://bytes.com/forum/thread160816.html</a>) and implemented the code as a test. I built a small .NET application that consumes the web service and calls each function and displays the result. From what I've read, the PHP SOAP extension will persist class variables between calls as long as the functionality is encapsulated in a class using the setClass() function and the setPersistence() function is passed SOAP_PERSISTENCE_SESSION.</p>
<p>Here is my code:</p>
<pre><code><?php
class User
{
var $name = "Initial value";
function setName($name)
{
$this->name = $name;
// Tried this too.
// $this->name = "Set to string constant" ;
}
function getName()
{
// This always returns "Initial value"
return $this->name;
}
}
// Tried placing session_start() in several places
// before $server->handle()...
// One guy says this doesn't need to be called.
// I assume it depends on if session autostart is on.
session_start();
$server = new SoapServer(null, array('uri' => 'http://localhost/'));
$server->setClass('User');
$server->setPersistence(SOAP_PERSISTENCE_SESSION);
$server->handle();
?>
</code></pre>
<p>The problem I run into is that $name is not persisted between calls -- I always get the initialized value and not the value I assign to setName(). As I stated, I'm trying to persist a session ID after authenticating against a database -- if anyone has a better way to do this I'm open to suggestions; however, I would still like to solve the general case. Anyone have any ideas?</p>
| [
{
"answer_id": 297525,
"author": "Steve Kalemkiewicz",
"author_id": 38151,
"author_profile": "https://Stackoverflow.com/users/38151",
"pm_score": 2,
"selected": true,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WsTest\n{\n public partial class PhpWsForm : Form\n {\n private localhost.MyWebService ws;\n\n public PhpWsForm()\n {\n InitializeComponent();\n ws = new WsTest.localhost.MyWebService();\n\n // The line below is the part that I forgot!\n ws.CookieContainer = new System.Net.CookieContainer();\n }\n\n private void butSetVal_Click(object sender, EventArgs e)\n {\n ws.setName(txtSetVal.Text);\n }\n\n private void butGetVal_Click(object sender, EventArgs e)\n {\n txtGetVal.Text = ws.getName();\n }\n }\n}\n"
},
{
"answer_id": 10139147,
"author": "Arvind Bhardwaj",
"author_id": 942296,
"author_profile": "https://Stackoverflow.com/users/942296",
"pm_score": 0,
"selected": false,
"text": "$client = SoapClient(\"some.wsdl\", array('trace' => 1));\n$result = $client->SomeFunction();\n$headers = $client->__getLastResponseHeaders();\n $headers $headers //$client->__setCookie($cookieName, $cookieValue);\n$client->__setCookie('ASP.NET_SessionId', $cookieValue);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38151/"
] |
295,992 | <pre><code>var i : integer;
i := 1234567;
</code></pre>
<p>Given the above, I want the string "1,234,567" as output (assuming UK locale). IntToStr just gives me "1234567". I'm sure there's a one-liner for this, but I can't find it...</p>
| [
{
"answer_id": 296047,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 5,
"selected": true,
"text": "Label1.Caption := Format('%.0n', [i + 0.0]);\n"
},
{
"answer_id": 296093,
"author": "Mark",
"author_id": 28989,
"author_profile": "https://Stackoverflow.com/users/28989",
"pm_score": -1,
"selected": false,
"text": "stringreplace(format('%n',[1234567.0]),'.00','',[]);\n"
},
{
"answer_id": 296894,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 4,
"selected": false,
"text": "function FormatIntFromLCID(const AValue: Integer; const LCID: Integer = LOCALE_SYSTEM_DEFAULT): string;\nvar\n AFormatSettings: TFormatSettings;\nbegin\n GetLocaleFormatSettings(LCID, AFormatSettings);\n Result := FormatFloat('#,##0',AValue, AFormatSettings);\nend;\n"
},
{
"answer_id": 61788374,
"author": "Mark Patterson",
"author_id": 1087046,
"author_profile": "https://Stackoverflow.com/users/1087046",
"pm_score": 0,
"selected": false,
"text": "function dn(i: integer): string; \nbegin \n result := format('%.0n', [i.ToDouble]) \nend;\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
295,993 | <p>I'm actual looking for a way to get notified about any changes on a SharePoint group. First I though I would be able to this by attaching a event handler to some kind of group list. But unfortunately there are no such list representing SharePoint groups. </p>
<p>My second attempt was to bind a event handler to the content type SharePointGroup but this didn't work either. </p>
<p>So are there any other options to get notified about events on a SharePoint group?</p>
<p><strong>EDIT:</strong></p>
<p>Thanks for the reply so far.</p>
<p>I forgot to mention that I've already googled and read about the user information list. Sorry.</p>
<p>First I found a forum entry where they post the relative URL to the user information list (_catalogs/users/simple.aspx). When I'm using this link to see the list,it only contains users and no groups. I don't know but perhaps this link does some filtering on the list.</p>
<p>The other information I found about in several blog and forum posts was that a event handler attached to the user information list are not fired up on an events. I have to admit after reading that it doesn't work so many times and even on MSDN (<a href="http://msdn.microsoft.com/en-us/library/aa979520.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa979520.aspx</a>), I didn't try it on my own.</p>
<p>The problem attaching the event handler to the content type wasn't the attaching thing, the handler simply didn't get fired when I for example changed a group name or deleted a user from the group. I don't have an idea why the handler doesn't get called I pretty sure I implemented the right methods and attached them to the right events.</p>
<p><strong>Any other suggestions how to get informed about changes on SharePoint groups?</strong></p>
| [
{
"answer_id": 2804746,
"author": "Dave Cornall",
"author_id": 337495,
"author_profile": "https://Stackoverflow.com/users/337495",
"pm_score": 2,
"selected": false,
"text": " wssQuery = new SPAuditQuery(site);\n wssQuery.AddEventRestriction(SPAuditEventType.SecGroupMemberAdd);\n wssQuery.AddEventRestriction(SPAuditEventType.SecGroupMemberDel);\n wssQuery.SetRangeStart(startTime.AddMinutes(-16));\n auditCol = site.Audit.GetEntries(wssQuery);\n\n\n\n\n foreach (SPAuditEntry entry in auditCol)\n {\n xml.LoadXml(\"<event>\" + entry.EventData + \"</event>\");\n\n int userId = Int32.Parse(xml.SelectSingleNode(\"/event/user\").InnerText);\n int groupId = Int32.Parse(xml.SelectSingleNode(\"/event/groupid\").InnerText);\n\n if (entry.Event == SPAuditEventType.SecGroupMemberAdd)\n {\n // Do Stuff\n }\n\n if (entry.Event == SPAuditEventType.SecGroupMemberDel)\n {\n // Do Stuff\n }\n\n\n }\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19601/"
] |
295,994 | <p>We had a discussion here at work regarding why <em>fread()</em> and <em>fwrite()</em> take a size per member and count and return the number of members read/written rather than just taking a buffer and size. The only use for it we could come up with is if you want to read/write an array of structures which aren't evenly divisible by the platform alignment and hence have been padded but that can't be so common as to warrant this choice in design.</p>
<p>From <a href="https://man7.org/linux/man-pages/man3/fread.3.html" rel="noreferrer">fread(3)</a>:</p>
<blockquote>
<p>The function fread() reads nmemb elements of data, each size bytes long,
from the stream pointed to by stream, storing them at the location given
by ptr.</p>
</blockquote>
<blockquote>
<p>The function fwrite() writes nmemb elements of data, each size bytes
long, to the stream pointed to by stream, obtaining them from the location
given by ptr.</p>
</blockquote>
<blockquote>
<p>fread() and fwrite() return the number of items successfully read or written
(i.e., not the number of characters). If an error occurs, or the
end-of-file is reached, the return value is a short item count (or zero).</p>
</blockquote>
| [
{
"answer_id": 296018,
"author": "Peter Miehle",
"author_id": 27800,
"author_profile": "https://Stackoverflow.com/users/27800",
"pm_score": 6,
"selected": false,
"text": "fread(buf, 1000, 1, stream) fread(buf, 1, 1000, stream)"
},
{
"answer_id": 296305,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "size_t fread_buf( void* ptr, size_t size, FILE* stream)\n{\n return fread( ptr, 1, size, stream);\n}\n\n\nsize_t fwrite_buf( void const* ptr, size_t size, FILE* stream)\n{\n return fwrite( ptr, 1, size, stream);\n}\n fread() fwrite() fread() fwrite() fgetc() fputc() fread() size size - 1 fread(buf, 1, size * n, stream); fread(buf, size, n, stream); fread() fwrite()"
},
{
"answer_id": 10208277,
"author": "Vanuan",
"author_id": 99024,
"author_profile": "https://Stackoverflow.com/users/99024",
"pm_score": -1,
"selected": false,
"text": "int intArray[10];\nfwrite(intArray, sizeof(int), 10, fd);\n int intArray[10];\nfwrite(intArray, sizeof(int)*10, fd);\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22247/"
] |
295,996 | <p>From a couple of preliminary tests it seems that <a href="http://msdn.microsoft.com/en-us/library/ms633497.aspx" rel="noreferrer"><code>EnumWindows</code></a> always returns windows in reverse instantiation order, i.e. most recently instantiated window first. Is that a valid observation? If so, is it true across all versions of Windows? And is this a reliable assumption, i.e. is that behaviour documented somewhere?</p>
<hr>
<p>Context: <em>I'm dealing with a situation where I am triggering a third-party application to open several non-modal windows and I need to send some window messages to those windows once they're open, yet I have no sure-fire way of identifying them as neither their window classes nor their captions will differ and I also do not know their expected coordinates. However, if I could rely on the above behaviour of <code>EnumWindows</code> I could simply use the first handle returned by <code>EnumWindows</code> whose class and caption match my expectation. That still leaves some hypothetical loop holes but I think it will be good enough. Alternative suggestions welcome nevertheless.</em></p>
| [
{
"answer_id": 296014,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 6,
"selected": true,
"text": "WS_EX_TOPMOST WS_EX_TOPMOST set WS_EX_TOPMOST WS_EX_TOPMOST EnumWindows EnumWindows GetWindowThreadProcessID SetWindowsHookEx() CBTProc EnumWindows EnumWindows EnumWindowsProc EnumChildWindows EnumWindows EnumWindows EnumThreadWindows"
},
{
"answer_id": 296048,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "EnumWindowProc"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/295996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9784/"
] |
296,001 | <p>Since I'm sure many people have different standard, I've made this post a community wiki.</p>
<p>My question is, what's a good naming scheme for table aliases? I've been using the first letter of every word from the table name, but it's been getting quite unreadable. Here's a quick example.</p>
<pre><code>FROM incidents i
FROM cause_attack ca
FROM obscure_table ot
</code></pre>
<p>Thank you.</p>
| [
{
"answer_id": 296022,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "'RelObjectProperty' 'rop' SELECT\n p.Name PropertyName,\n o.Name ObjectName,\n rop.Value PropertyValue\nFROM\n Property p\n INNER JOIN RelObjectProperty rop ON rop.PropertyId = p.Id\n INNER JOIN Object o ON rop.ObjectId = o.Id\nWHERE\n o.Id = 10\n 'RelObjectPresentation' 'rop' 'ropr' 'ropr' 'rop'"
},
{
"answer_id": 296028,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "-- Find Highest paid Emplyees in Each Division ..... \nSelect * From Employee oE -- For outer Employee table\nWhere Salary = (Select Max(Salary) \n From Employee iE\n Where DivisionId = oE.DivisionId) \n"
},
{
"answer_id": 296041,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "fact_ dim_ cdim_ lkup_ LOOKUP_TRANSACTION_TYPE lkup_TT SYSTEM_SUBSYSTEM_ENTITY_TYPE"
},
{
"answer_id": 296043,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": -1,
"selected": false,
"text": "PER_PERSON\n PER_ID\n PER_NameFirst\n PER_NameLast\n ...\nCAT_CAT\n CAT_ID\n CAT_Name\n CAT_Breed\n ...\nDOG_DOG\n DOG_ID\n DOG_Name\n DOG_Breed\n ...\nPERCD_PERSON_CAT_DOG (for the join data)\n PERCD_ID\n PERCD_PER_ID\n PERCD_CAT_ID\n PERCD_DOG_ID\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/296001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25371/"
] |
296,003 | <p>Does any one know the best way to deploy a resource file to the App_GlobalResource folder of the web application when a feature is activated?</p>
| [
{
"answer_id": 296488,
"author": "Lars Fastrup",
"author_id": 27393,
"author_profile": "https://Stackoverflow.com/users/27393",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Solution SolutionId=\"{185E973C-3A10-4e2a-9E0F-DC14414551F9}\" \n xmlns=\"http://schemas.microsoft.com/sharepoint/\" \n DeploymentServerType=\"WebFrontEnd\">\n\n <ApplicationResourceFiles>\n <ApplicationResourceFile Location=\"yourappname.resx\"/>\n <ApplicationResourceFile Location=\"yourappname.en-US.resx\"/>\n </ApplicationResourceFiles>\n\n ...\n</Solution>\n"
},
{
"answer_id": 557917,
"author": "webwires",
"author_id": 13135,
"author_profile": "https://Stackoverflow.com/users/13135",
"pm_score": 3,
"selected": true,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Solution SolutionId=\"{185E973C-3A10-4e2a-9E0F-DC14414551F9}\"\n xmlns=\"http://schemas.microsoft.com/sharepoint/\"\n DeploymentServerType=\"WebFrontEnd\">\n <ApplicationResourceFiles>\n <ApplicationResourceFile Location=\"yourappname.resx\"/>\n <ApplicationResourceFile Location=\"yourappname.en-US.resx\"/>\n </ApplicationResourceFiles> ...\n</Solution>\n string appPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath);\nResourceManager resX = ResourceManager.CreateFileBasedResourceManager(\"ResourceFileName\", appPath + \"resources\", null);\n\nSPSecurity.RunWithElevatedPrivileges(delegate()\n{\n AddResource(resX, \"DefaultTextBoxLabelText\");\n"
},
{
"answer_id": 11216731,
"author": "Jenn",
"author_id": 818004,
"author_profile": "https://Stackoverflow.com/users/818004",
"pm_score": 2,
"selected": false,
"text": "<Solution SolutionId=\"{8a2f91f2-db85-4eb3-8e7c-330f05246e1a}\"\n DeploymentServerType=\"WebFrontEnd\"\n xmlns=\"http://schemas.microsoft.com/sharepoint/\">\n <ApplicationResourceFiles>\n <App_GlobalResourceFile Location=\"yourResourceFile.resx\"/>\n </ApplicationResourceFiles>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/296003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13135/"
] |
296,015 | <p>Please consider the following example. Note that in the real-word, the binding source will likely be a data object. I'm using a <code>TextBlock</code> for simplicity.</p>
<pre><code><Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel Margin="20">
<Label>Enter a Name:</Label>
<TextBox x:Name="txt_Name" Text="{Binding ElementName=display_name, Path=Text, UpdateSourceTrigger=LostFocus}" />
<Label>The name you entered:</Label>
<TextBlock x:Name="display_name" />
<Button x:Name="btn_Save" Click="SaveClick">_Save</Button>
</StackPanel>
</Window>
</code></pre>
<pre class="lang-vb prettyprint-override"><code>Class Window1
Private Sub SaveClick(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
MessageBox.Show("Saving your name as: " & display_name.Text)
End Sub
End Class
</code></pre>
<p>In the example above, if I enter the name <code>"Joe"</code> into the <code>TextBox</code> and click the "Save" button, the <code>TextBlock</code> is updated upon <code>LostFocus</code> and the data is "saved" properly. All is good.</p>
<p>However, if I then enter <code>"Bob"</code> in the <code>TextBox</code> and use my access key (Alt-S) to save, the <code>TextBlock</code> is not updated because the <code>LostFocus</code> event on the <code>TextBox</code> is not fired. As a result, my binding source is not updated and the wrong value (i.e., <code>"Joe"</code>) is saved.</p>
<p>In most WPF <code>TextBox</code> data entry fields, you'll want to do your validation upon <code>LostFocus</code> (not <code>PropertyChanged</code>); however, if the <code>LostFocus</code> event does not fire (and thus the binding is not updated) when an access key is used, how do we validate the entry? In WinForms we have the <code>Validating</code> and <code>Validated</code> events, but they are absent in WPF.</p>
| [
{
"answer_id": 296092,
"author": "Sam Meldrum",
"author_id": 16005,
"author_profile": "https://Stackoverflow.com/users/16005",
"pm_score": 2,
"selected": false,
"text": "txt_Name.GetBindingExpression(TextBox.TextProperty).UpdateTarget();\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/296015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
296,020 | <p>How can I create a table that has its first row and first column both locked, as in Excel, when you activate 'freeze panes'? I need the table to both scroll horizontally and vertically (a lot of solutions for this exist, but only allow vertical scrolling).</p>
<p>So, when you scroll down in the table, the first row will stay put, since it will have the column headings. This may end up being in a <code>thead</code>, or it may not, whatever makes the solution easier.</p>
<p>When you scroll right, the first column stays put, since it holds the labels for the rows.</p>
<p>I'm pretty certain this is impossible with CSS alone, but can anyone point me toward a JavaScript solution? It needs to work in all major browsers.</p>
| [
{
"answer_id": 296030,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "overflow: scroll; <div>"
},
{
"answer_id": 296063,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<head>\n <meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\n <meta name=\"robots\" content=\"noindex, nofollow\">\n <meta name=\"googlebot\" content=\"noindex, nofollow\">\n <script type=\"text/javascript\" src=\"/js/lib/dummy.js\"></script>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"/css/result-light.css\">\n <style type=\"text/css\">\n /* Scrollable Content Height */\n.scrollContent {\n height:100px;\n overflow-x:hidden;\n overflow-y:auto;\n}\n.scrollContent tr {\n height: auto;\n white-space: nowrap;\n}\n\n/* Prevent Mozilla scrollbar from hiding right-most cell content */\n.scrollContent tr td:last-child {\n padding-right: 20px;\n}\n\n/* Fixed Header Height */\n.fixedHeader tr {\n position: relative;\n height: auto;\n}\n\n/* Put border around entire table */\ndiv.TableContainer {\n border: 1px solid #7DA87D;\n}\n\n/* Table Header formatting */\n.headerFormat {\n background-color: white;\n color: #FFFFFF;\n margin: 3px;\n padding: 1px;\n white-space: nowrap;\n font-family: Helvetica;\n font-size: 16px;\n text-decoration: none;\n font-weight: bold;\n}\n.headerFormat tr td {\n border: 1px solid #000000;\n background-color: #7DA87D;\n}\n\n/* Table Body (Scrollable Content) formatting */\n.bodyFormat tr td {\n color: #000000;\n margin: 3px;\n padding: 1px;\n border: 0px none;\n font-family: Helvetica;\n font-size: 12px;\n}\n\n/* Use to set different color for alternating rows */\n.alternateRow {\n background-color: #E0F1E0;\n}\n\n/* Styles used for SORTING */\n.point {\n cursor:pointer;\n}\ntd.sortedColumn {\n background-color: #E0F1E0;\n}\n\ntr.alternateRow td.sortedColumn {\n background-color: #c5e5c5;\n}\n.total {\n background-color: #FED362;\n color: #000000;\n white-space: nowrap;\n font-size: 12px;\n text-decoration: none;\n}\n </style>\n\n <title></title>\n<script type='text/javascript'>//<![CDATA[\n\n/* This script and many more are available free online at\nThe JavaScript Source :: http://www.javascriptsource.com\nCreated by: Stan Slaughter :: http://www.stansight.com/ */\n\n/* ======================================================\nGeneric Table Sort\n\nBasic Concept: A table can be sorted by clicking on the title of any\ncolumn in the table, toggling between ascending and descending sorts.\n\n\nAssumptions:\n\n* The first row of the table contains column titles that are \"clicked\"\n to sort the table\n\n* The images 'desc.gif','asc.gif','none.gif','sorting.gif' exist\n\n* The img tag is in each column of the the title row to represent the\n sort graphic.\n\n* The CSS classes 'alternateRow' and 'sortedColumn' exist so we can\n have alternating colors for each row and a highlight the sorted\n column. Something like the <style> definition below, but with the\n background colors set to whatever you want.\n\n <style>\n tr.alternateRow {\n background-color: #E0F1E0;\n }\n\n td.sortedColumn {\n background-color: #E0F1E0;\n }\n\n tr.alternateRow td.sortedColumn {\n background-color: #c5e5c5;\n }\n </style>\n\n====================================================== */\n\nfunction sortTable(td_element,ignoreLastLines) {\n\n // If the optional ignoreLastLines parameter (number of lines *not* to sort at end of table)\n // was not passed then make it 0\n ignoreLastLines = (typeof(ignoreLastLines)=='undefined') ? 0 : ignoreLastLines;\n\n var sortImages =['data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUz4IVcZDleixQIQjA1pFFZx2FVRklZvOWUl8LsVgBeFLyE8TLgDZYESISwvAAA1QvjAQwBADs=','data:image/gif;base64,R0lGODlhCgAKAMQXAJOkk3mReXume3uTe3mieXGPcXOYc/Hx8Xadds/Wz9vg24ejh3GUcYOgg6a0pnGVcfP18+3w7c3TzdPY06u4q/r8+v///////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAABcALAAAAAAKAAoAAAUw4CVeDzOeFwCgIhFBBDtY1sAmtIIWFV0VJweNRhkZeoeDpWIQNSYBgSAgWYgQLGwIADs=','data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7','http://web.archive.org/web/20150906203819im_/http://www.javascriptsource.com/miscellaneous/sorting.gif'];\n\n // Get the image used in the first row of the current column\n var sortColImage = td_element.getElementsByTagName('img')[0];\n\n // If current image is 'asc.gif' or 'none.gif' (elements 1 and 2 of sortImages array) then this will\n // be a descending sort else it will be ascending - get new sort image icon and set sort order flag\n var sortAscending = false;\n var newSortColImage = \"\";\n if (sortColImage.getAttribute('src').indexOf(sortImages[1])>-1 ||\n sortColImage.getAttribute('src').indexOf(sortImages[2])>-1) {\n newSortColImage = sortImages[0];\n sortAscending = false;\n } else {\n newSortColImage = sortImages[1];\n sortAscending = true;\n }\n\n // Assign \"SORTING\" image icon (element 3 of sortImages array)) to current column title\n // (will replace with newSortColImage when sort completes)\n sortColImage.setAttribute('src',sortImages[3]);\n\n // Find which column was clicked by getting it's column position\n var indexCol = td_element.cellIndex;\n\n // Get the table element from the td element that was passed as a parameter to this function\n var table_element = td_element.parentNode;\n while (table_element.nodeName != \"TABLE\") {\n table_element = table_element.parentNode;\n }\n\n // Get all \"tr\" elements from the table and assign then to the Array \"tr_elements\"\n var tr_elements = table_element.getElementsByTagName('tr');\n\n // Get all the images used in the first row then set them to 'none.gif'\n // (element 2 or sortImages array) except for the current column (all ready been changed)\n var allImg = tr_elements[0].getElementsByTagName('img');\n for(var i=0;i<allImg.length;i++){\n if(allImg[i]!=sortColImage){allImg[i].setAttribute('src',sortImages[2])}\n }\n\n // Some explantion of the basic concept of the following code before we\n // actually start. Essentially we are going to copy the current columns information\n // into an array to be sorted. We'll sort the column array then go back and use the information\n // we saved about the original row positions to re-order the entire table.\n // We are never really sorting more than a columns worth of data, which should keep the sorting fast.\n\n // Create a new array for holding row information\n var clonedRows = new Array()\n\n // Create a new array to store just the selected column values, not the whole row\n var originalCol = new Array();\n\n // Now loop through all the data row elements\n // NOTE: Starting at row 1 because row 0 contains the column titles\n for (var i=1; i<tr_elements.length - ignoreLastLines; i++) {\n\n // \"Clone\" the tr element i.e. save a copy all of its attributes and values\n clonedRows[i]=tr_elements[i].cloneNode(true);\n\n // Text value of the selected column on this row\n var valueCol = getTextValue(tr_elements[i].cells[indexCol]);\n\n // Format text value for sorting depending on its type, ie Date, Currency, number, etc..\n valueCol = FormatForType(valueCol);\n\n // Assign the column value AND the row number it was originally on in the table\n originalCol[i]=[valueCol,tr_elements[i].rowIndex];\n }\n\n // Get rid of element \"0\" from this array. A value was never assigned to it because the first row\n // in the table just contained the column titles, which we did not bother to assign.\n originalCol.shift();\n\n // Sort the column array returning the value of a sort into a new array\n sortCol = originalCol.sort(sortCompare);\n\n // If it was supposed to be an Ascending sort then reverse the order\n if (sortAscending) { sortCol.reverse(); }\n\n // Now take the values from the sorted column array and use that information to re-arrange\n // the order of the tr_elements in the table\n for (var i=1; i < tr_elements.length - ignoreLastLines; i++) {\n\n var old_row = sortCol[i-1][1];\n var new_row = i;\n tr_elements[i].parentNode.replaceChild(clonedRows[old_row],tr_elements[new_row]);\n }\n\n // Format the table, making the rows alternating colors and highlight the sorted column\n makePretty(table_element,indexCol,ignoreLastLines);\n\n // Assign correct sort image icon to current column title\n sortColImage.setAttribute('src',newSortColImage);\n}\n\n// Function used by the sort routine to compare the current value in the array with the next one\nfunction sortCompare (currValue, nextValue) {\n // Since the elements of this array are actually arrays themselves, just sort\n // on the first element which contiains the value, not the second which contains\n // the original row position\n if ( currValue[0] == nextValue[0] ) return 0;\n if ( currValue[0] < nextValue[0] ) return -1;\n if ( currValue[0] > nextValue[0] ) return 1;\n}\n\n//-----------------------------------------------------------------------------\n// Functions to get and compare values during a sort.\n//-----------------------------------------------------------------------------\n\n// This code is necessary for browsers that don't reflect the DOM constants\n// (like IE).\nif (document.ELEMENT_NODE == null) {\n document.ELEMENT_NODE = 1;\n document.TEXT_NODE = 3;\n}\n\nfunction getTextValue(el) {\n var i;\n var s;\n // Find and concatenate the values of all text nodes contained within the\n // element.\n s = \"\";\n for (i = 0; i < el.childNodes.length; i++)\n if (el.childNodes[i].nodeType == document.TEXT_NODE)\n s += el.childNodes[i].nodeValue;\n else if (el.childNodes[i].nodeType == document.ELEMENT_NODE &&\n el.childNodes[i].tagName == \"BR\")\n s += \" \";\n else\n // Use recursion to get text within sub-elements.\n s += getTextValue(el.childNodes[i]);\n\n return normalizeString(s);\n}\n\n// Regular expressions for normalizing white space.\nvar whtSpEnds = new RegExp(\"^\\\\s*|\\\\s*$\", \"g\");\nvar whtSpMult = new RegExp(\"\\\\s\\\\s+\", \"g\");\n\nfunction normalizeString(s) {\n s = s.replace(whtSpMult, \" \"); // Collapse any multiple whites space.\n s = s.replace(whtSpEnds, \"\"); // Remove leading or trailing white space.\n return s;\n}\n\n// Function used to modify values to make then sortable depending on the type of information\nfunction FormatForType(itm) {\n var sortValue = itm.toLowerCase();\n\n // If the item matches a date pattern (MM/DD/YYYY or MM/DD/YY or M/DD/YYYY)\n if (itm.match(/^\\d\\d[\\/-]\\d\\d[\\/-]\\d\\d\\d\\d$/) ||\n itm.match(/^\\d\\d[\\/-]\\d\\d[\\/-]\\d\\d$/) ||\n itm.match(/^\\d[\\/-]\\d\\d[\\/-]\\d\\d\\d\\d$/) ) {\n\n // Convert date to YYYYMMDD format for sort comparison purposes\n // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX\n var yr = -1;\n\n if (itm.length == 10) {\n sortValue = itm.substr(6,4)+itm.substr(0,2)+itm.substr(3,2);\n } else if (itm.length == 9) {\n sortValue = itm.substr(5,4)+\"0\" + itm.substr(0,1)+itm.substr(2,2);\n } else {\n yr = itm.substr(6,2);\n if (parseInt(yr) < 50) {\n yr = '20'+yr;\n } else {\n yr = '19'+yr;\n }\n sortValue = yr+itm.substr(3,2)+itm.substr(0,2);\n }\n\n }\n\n\n\n // If the item matches a Percent patten (contains a percent sign)\n if (itm.match(/%/)) {\n // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.\n sortValue = itm.replace(/[^0-9.-]/g,'');\n sortValue = parseFloat(sortValue);\n }\n\n // If item starts with a \"(\" and ends with a \")\" then remove them and put a negative sign in front\n if (itm.substr(0,1) == \"(\" & itm.substr(itm.length - 1,1) == \")\") {\n itm = \"-\" + itm.substr(1,itm.length - 2);\n }\n\n// If the item matches a currency pattern (starts with a dollar or negative dollar sign)\n if (itm.match(/^[£$]|(^-)/)) {\n // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.\n sortValue = itm.replace(/[^0-9.-]/g,'');\n if (isNaN(sortValue)) {\n sortValue = 0;\n } else {\n sortValue = parseFloat(sortValue);\n }\n}\n\n // If the item matches a numeric pattern\n if (itm.match(/(\\d*,\\d*$)|(^-?\\d\\d*\\.\\d*$)|(^-?\\d\\d*$)|(^-?\\.\\d\\d*$)/)) {\n // Replace anything that is not part of a number (decimal pt, neg sign, or 0 through 9) with an empty string.\n sortValue = itm.replace(/[^0-9.-]/g,'');\n // sortValue = sortValue.replace(/,/g,'');\n if (isNaN(sortValue)) {\n sortValue = 0;\n } else {\n sortValue = parseFloat(sortValue);\n }\n }\n\n return sortValue;\n}\n\n//-----------------------------------------------------------------------------\n// Functions to update the table appearance after a sort.\n//-----------------------------------------------------------------------------\n\n// Style class names.\nvar rowClsNm = \"alternateRow\";\nvar colClsNm = \"sortedColumn\";\n\n// Regular expressions for setting class names.\nvar rowTest = new RegExp(rowClsNm, \"gi\");\nvar colTest = new RegExp(colClsNm, \"gi\");\n\nfunction makePretty(tblEl, col, ignoreLastLines) {\n\n var i, j;\n var rowEl, cellEl;\n\n // Set style classes on each row to alternate their appearance.\n for (i = 1; i < tblEl.rows.length - ignoreLastLines; i++) {\n rowEl = tblEl.rows[i];\n rowEl.className = rowEl.className.replace(rowTest, \"\");\n if (i % 2 != 0)\n rowEl.className += \" \" + rowClsNm;\n rowEl.className = normalizeString(rowEl.className);\n // Set style classes on each column (other than the name column) to\n // highlight the one that was sorted.\n for (j = 0; j < tblEl.rows[i].cells.length; j++) {\n cellEl = rowEl.cells[j];\n cellEl.className = cellEl.className.replace(colTest, \"\");\n if (j == col)\n cellEl.className += \" \" + colClsNm;\n cellEl.className = normalizeString(cellEl.className);\n }\n }\n\n\n}\n\n// END Generic Table sort.\n\n// =================================================\n\n// Function to scroll to top before sorting to fix an IE bug\n// Which repositions the header off the top of the screen\n// if you try to sort while scrolled to bottom.\nfunction GoTop() {\n document.getElementById('TableContainer').scrollTop = 0;\n}\n\n//]]> \n</script>\n</head>\n<body>\n <table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">\n<tr><td>\n<div id=\"TableContainer\" class=\"TableContainer\" style=\"height:230px;\">\n<table class=\"scrollTable\">\n <thead class=\"fixedHeader headerFormat\">\n <tr>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\"><b>NAME</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\" align=\"right\"><b>Amt</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\" align=\"right\"><b>Lvl</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\" align=\"right\"><b>Rank</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\" align=\"right\"><b>Position</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n <td class=\"point\" onclick=\"GoTop(); sortTable(this,1);\" title=\"Sort\" align=\"right\"><b>Date</b> <img src=\"data:image/gif;base64,R0lGODlhCgAKALMLAHaRdnCTcHegd7C8sNTa1Ku4q9vg24GXgfr8+uDl4P///////wAAAAAAAAAAAAAAACH5BAEAAAsALAAAAAAKAAoAAAQfcMlJq12hIHKoSEqIdBIQnslknkoqfedIBQNikFduRQA7\" border=\"0\"></td>\n </tr>\n </thead>\n <tbody class=\"scrollContent bodyFormat\" style=\"height:200px;\">\n <tr class=\"alternateRow\">\n <td>Maha</td>\n <td align=\"right\">$19,923.19</td>\n <td align=\"right\">100</td>\n <td align=\"right\">100</td>\n <td>Owner</td>\n <td align=\"right\">01/02/2001</td>\n </tr>\n <tr>\n <td>Thrawl</td>\n <td align=\"right\">$9,550</td>\n <td align=\"right\">159</td>\n <td align=\"right\">100%</td>\n <td>Co-Owner</td>\n <td align=\"right\">11/07/2003</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Marhanen</td>\n <td align=\"right\">$223.04</td>\n <td align=\"right\">83</td>\n <td align=\"right\">99%</td>\n <td>Banker</td>\n <td align=\"right\">06/27/2006</td>\n </tr>\n <tr>\n <td>Peter</td>\n <td align=\"right\">$121</td>\n <td align=\"right\">567</td>\n <td align=\"right\">23423%</td>\n <td>FishHead</td>\n <td align=\"right\">06/06/2006</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Jones</td>\n <td align=\"right\">$15</td>\n <td align=\"right\">11</td>\n <td align=\"right\">15%</td>\n <td>Bubba</td>\n <td align=\"right\">10/27/2005</td>\n </tr>\n <tr>\n <td>Supa-De-Dupa</td>\n <td align=\"right\">$145</td>\n <td align=\"right\">91</td>\n <td align=\"right\">32%</td>\n <td>momma</td>\n <td align=\"right\">12/15/1996</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>ClickClock</td>\n <td align=\"right\">$1,213</td>\n <td align=\"right\">23</td>\n <td align=\"right\">1%</td>\n <td>Dada</td>\n <td align=\"right\">1/30/1998</td>\n </tr>\n <tr>\n <td>Mrs. Robinson</td>\n <td align=\"right\">$99</td>\n <td align=\"right\">99</td>\n <td align=\"right\">99%</td>\n <td>Wife</td>\n <td align=\"right\">07/04/1963</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Maha</td>\n <td align=\"right\">$19,923.19</td>\n <td align=\"right\">100</td>\n <td align=\"right\">100%</td>\n <td>Owner</td>\n <td align=\"right\">01/02/2001</td>\n </tr>\n <tr>\n <td>Thrawl</td>\n <td align=\"right\">$9,550</td>\n <td align=\"right\">159</td>\n <td align=\"right\">100%</td>\n <td>Co-Owner</td>\n <td align=\"right\">11/07/2003</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Marhanen</td>\n <td align=\"right\">$223.04</td>\n <td align=\"right\">83</td>\n <td align=\"right\">59%</td>\n <td>Banker</td>\n <td align=\"right\">06/27/2006</td>\n </tr>\n <tr>\n <td>Peter</td>\n <td align=\"right\">$121</td>\n <td align=\"right\">567</td>\n <td align=\"right\">534.23%</td>\n <td>FishHead</td>\n <td align=\"right\">06/06/2006</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Jones</td>\n <td align=\"right\">$15</td>\n <td align=\"right\">11</td>\n <td align=\"right\">15%</td>\n <td>Bubba</td>\n <td align=\"right\">10/27/2005</td>\n </tr>\n <tr>\n <td>Supa-De-Dupa</td>\n <td align=\"right\">$145</td>\n <td align=\"right\">91</td>\n <td align=\"right\">42%</td>\n <td>momma</td>\n <td align=\"right\">12/15/1996</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>ClickClock</td>\n <td align=\"right\">$1,213</td>\n <td align=\"right\">23</td>\n <td align=\"right\">2%</td>\n <td>Dada</td>\n <td align=\"right\">1/30/1998</td>\n </tr>\n <tr>\n <td>Mrs. Robinson</td>\n <td align=\"right\">$99</td>\n <td align=\"right\">99</td>\n <td align=\"right\">(-10.42%)</td>\n <td>Wife</td>\n <td align=\"right\">07/04/1963</td>\n </tr>\n <tr class=\"alternateRow\">\n <td>Maha</td>\n <td align=\"right\">-$19,923.19</td>\n <td align=\"right\">100</td>\n <td align=\"right\">(-10.01%)</td>\n <td>Owner</td>\n <td align=\"right\">01/02/2001</td>\n </tr>\n <tr>\n <td>Thrawl</td>\n <td align=\"right\">$9,550</td>\n <td align=\"right\">159</td>\n <td align=\"right\">-10.20%</td>\n <td>Co-Owner</td>\n <td align=\"right\">11/07/2003</td>\n </tr>\n <tr class=\"total\">\n <td><strong>TOTAL</strong>:</td>\n <td align=\"right\"><strong>999999</strong></td>\n <td align=\"right\"><strong>9999999</strong></td>\n <td align=\"right\"><strong>99</strong></td>\n <td > </td>\n <td align=\"right\"> </td>\n </tr>\n </tbody>\n</table>\n</div>\n</td></tr>\n</table>\n</body>\n</html>\n"
},
{
"answer_id": 16864982,
"author": "Selvakumar Arumugam",
"author_id": 297641,
"author_profile": "https://Stackoverflow.com/users/297641",
"pm_score": 4,
"selected": false,
"text": "$('#myTable').fxdHdrCol({\n fixedCols : 3, /* 3 fixed columns */\n width : \"100%\", /* set the width of the container (fixed or percentage)*/\n height : 500 /* set the height of the container */\n});\n"
},
{
"answer_id": 22340593,
"author": "C. Lee",
"author_id": 270821,
"author_profile": "https://Stackoverflow.com/users/270821",
"pm_score": 3,
"selected": false,
"text": "$(\"#clscroll-content\").scroll(function() {\n $(\"#clscroll-row-headers\").scrollTop($(\"#clscroll-content\").scrollTop());\n $(\"#clscroll-column-headers\").scrollLeft($(\"#clscroll-content\").scrollLeft());\n});\n\n$(\"#clscroll-column-headers\").scroll(function() {\n $(\"#clscroll-content\").scrollLeft($(\"#clscroll-column-headers\").scrollLeft());\n});\n\n$(\"#clscroll-row-headers\").scroll(function() {\n $(\"#clscroll-content\").scrollTop($(\"#clscroll-row-headers\").scrollTop());\n}); .clscroll table {\n table-layout: fixed;\n}\n\n.clscroll td, .clscroll th { \n overflow: hidden;\n}\n\n.corner-header {\n float: left;\n}\n\n.column-headers {\n float: left;\n overflow: scroll;\n}\n\n.row-headers {\n clear: both;\n float: left; \n overflow: scroll;\n}\n\n.table-content {\n table-layout: fixed;\n float: left;\n overflow: scroll;\n}\n\n.clscroll td, .clscroll th { \n width: 200px;\n border: 1px solid black;\n}\n\n.row-headers, .table-content {\n height: 100px;\n}\n\n.column-headers, .table-content, .table-content table, .column-headers table {\n width: 400px;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class=\"clscroll corner-header\">\n <table>\n <tr>\n <th> </th>\n </tr>\n </table>\n</div>\n<div class=\"clscroll column-headers\" id=\"clscroll-column-headers\">\n <table>\n <tr>\n <th>Bus</th>\n <th>Plane</th>\n <th>Boat</th>\n <th>Bicycle</th>\n </tr>\n </table>\n</div>\n<div class=\"clscroll row-headers\" id=\"clscroll-row-headers\">\n <table>\n <tr>\n <th>Red</th>\n </tr>\n <tr>\n <th>Green</th>\n </tr>\n <tr>\n <th>Blue</th>\n </tr>\n <tr>\n <th>Orange</th>\n </tr>\n <tr>\n <th>Purple</th>\n </tr>\n <tr>\n <th>Yellow</th>\n </tr>\n <tr>\n <th>Pink</th>\n </tr>\n <tr>\n <th>Brown</th>\n </tr>\n </table>\n</div>\n<div class=\"clscroll table-content\" id=\"clscroll-content\">\n <table>\n <tr>\n <td>Red Bus</td>\n <td>Red Plane</td>\n <td>Red Boat</td>\n <td>Red Bicycle</td>\n </tr>\n <tr>\n <td>Green Bus</td>\n <td>Green Plane</td>\n <td>Green Boat</td>\n <td>Green Bicycle</td>\n </tr>\n <tr>\n <td>Blue Bus</td>\n <td>Blue Plane</td>\n <td>Blue Boat</td>\n <td>Blue Bicycle</td>\n </tr>\n <tr>\n <td>Orange Bus</td>\n <td>Orange Plane</td>\n <td>Orange Boat</td>\n <td>Orange Bicycle</td>\n </tr>\n <tr>\n <td>Purple Bus</td>\n <td>Purple Plane</td>\n <td>Purple Boat</td>\n <td>Purple Bicycle</td>\n </tr>\n <tr>\n <td>Yellow Bus</td>\n <td>Yellow Plane</td>\n <td>Yellow Boat</td>\n <td>Yellow Bicycle</td>\n </tr>\n <tr>\n <td>Pink Bus</td>\n <td>Pink Plane</td>\n <td>Pink Boat</td>\n <td>Pink Bicycle</td>\n </tr>\n <tr>\n <td>Brown Bus</td>\n <td>Brown Plane</td>\n <td>Brown Boat</td>\n <td>Brown Bicycle</td>\n </tr>\n </table>\n</div>"
},
{
"answer_id": 26044201,
"author": "Yonatan Alexis Quintero Rodrig",
"author_id": 4071287,
"author_profile": "https://Stackoverflow.com/users/4071287",
"pm_score": -1,
"selected": false,
"text": "table{\nborder-spacing: 0;\ndisplay: flex;/*Se ajuste dinamicamente al tamano del dispositivo**/\nmax-height: 40vh; /*El alto que necesitemos**/\noverflow-y: auto; /**El scroll verticalmente cuando sea necesario*/\noverflow-x: hidden;/*Sin scroll horizontal*/\ntable-layout: fixed;/**Forzamos a que las filas tenga el mismo ancho**/\nwidth: 98vw; /*El ancho que necesitemos*/\nborder:1px solid gray;}\n"
},
{
"answer_id": 58369543,
"author": "KWallace",
"author_id": 8754098,
"author_profile": "https://Stackoverflow.com/users/8754098",
"pm_score": 0,
"selected": false,
"text": "<body onResize=\"scaleElements()\">\n\n<div id=\"table-container-div\">\n\n<table id=\"data-table\">\n <thead id=\"th-header\">\n <tr id=\"th-header-row\">\n <td>Column1</td>\n <td>Column2</td>\n <td>Column3</td>\n <td>Column4</td>\n </tr>\n </thead>\n\n <tbody id=\"tbl-body\">\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n <tr><td>a</td><td>b</td><td>c</td><td>d</td></tr>\n <tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>\n <tr><td>h</td><td>i</td><td>j</td><td>k</td></tr>\n </tbody>\n\n</table>\n (() => {\n scaleElements(); \n })();\n\n\n function scaleElements() {\n\n // element() is just shorthand for document.getElementById().\n\n // scaleElements() scales a number of other things, not included here, \n // that get rescaled any time the browser, or a container is resized.\n // the table header row here is just one of them...\n //\n // this thing includes checks to see if a table with the table & thead \n // is on the page. If it is, it checks to see if the span container is\n // here (it's not on the first run, but it is on subsequent calls. So, \n // it adds it if it needs it, or reuses it if it's there.\n\n if (element(\"data-table\")) {\n\n if (element(\"th-span-container\")) {\n element(\"th-span-container\").parentElement.removeChild(element(\"th-span-container\"));\n }\n\n var x = document.createElement(\"div\");\n x.id = \"th-span-container\";\n x.style.cssFloat = \"left\";\n x.style.position = \"fixed\";\n x.style.top = \"10px\";\n\n // you will want to fiddle with your own particular positioning. \n // this one is positioned to work on a table that is below a page \n // logo banner.\n\n var tds = element(\"th-header-row\").getElementsByTagName(\"td\");\n\n for (i = 0; i < tds.length; i++) {\n\n let z = tds[i];\n let y = document.createElement(\"span\");\n\n y.style.padding = \"0px\";\n y.style.margin = \"0px\";\n y.style.fontFamily = \"'Segoe UI', Tahoma, Geneva, Verdana, sans-serif\";\n y.style.fontSize = \"13px\";\n y.style.border = \"0px\";\n y.style.position = \"absolute\";\n y.style.color = \"white\";\n y.style.backgroundColor = \"#3D6588\";\n y.style.left = z.offsetLeft + \"px\";\n y.style.height = z.offsetHeight + \"px\";\n y.style.lineHeight = z.offsetHeight + \"px\";\n y.style.width = z.offsetWidth + \"px\";\n y.innerHTML = z.innerHTML;\n x.appendChild(y);\n\n }\n\n element(\"table-container-div\").appendChild(x);\n element(\"th-header-row\").style.visibility = \"hidden\";\n\n }\n\n }\n\nfunction element(e) {\n return document.getElementById(e);\n}\n body {\n background: black;\n}\n\n#table-container-div {\n width: 310px;\n position: absolute;\n top: 10px;\n bottom: 10px;\n overflow-x: hidden;\n overflow-y: auto;\n min-width: 320px;\n }\n\n table {\n font-size: 13px;\n height: 120px;\n width: 300px;\n border: 0px solid red;\n background-color: #11171F;\n }\n\n tr {\n height: 22px;\n color: #cff3ff;\n }\n\n tr:hover {\n background-color: dimgrey;\n }\n\n td {\n color:white;\n border-right: 1px dotted #4F4F4F;\n }\n\n #th-header-row {\n background-color: #3D6588;\n color: white;\n }\n"
},
{
"answer_id": 64817186,
"author": "Kirby Wu",
"author_id": 8503848,
"author_profile": "https://Stackoverflow.com/users/8503848",
"pm_score": 0,
"selected": false,
"text": "<table>\n <tr><th class=\"head\"></th class=\"head\"><th></th> ... </tr>\n <tr><th class=\"head\"></th> <th></th> ... </tr>\n...\n</table>\n<style type=\"text/css\">\n .head { position: sticky; top: 0; left: 0;}\n</style>\n <div class=\"grid\">\n <!-- cells to freeze -->\n <div class=\"entry head\"></div>\n <div class=\"entry head\"></div>\n ...\n <!-- normal cells -->\n <div class=\"entry\"></div>\n ...\n</div>\n<style type=\"text/css\">\n .grid {\n display: grid;\n grid-template-columns: repeat(<your-cell-count>, <cell-size>); \n } \n .entry.head { position: sticky; top: 0; left: 0 }\n</style>\n"
}
] | 2008/11/17 | [
"https://Stackoverflow.com/questions/296020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4257/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.