qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
329,556 | <p>I have <code>DataTemplate</code> containing a <code>TextBox</code>. I'm setting this template to a listbox item on a selection.</p>
<p>I'm unable to set focus to textbox in the template. I tried to call MyTemplate.FindName, but it ends up with an Invalid Operation Exception: This operation is valid only on elements that have this template applied.</p>
<p>How can I access it?</p>
| [
{
"answer_id": 329571,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": true,
"text": "TextBox ListBoxItem var item = listBox1.ItemContainerGenerator.ContainerFromItem(listBox1.SelectedItem) as ListBoxItem;\n public void FocusItem(ListBoxItem item, string name)\n{\n if (!item.IsLoaded)\n {\n // wait for the item to load so we can find the control to focus\n RoutedEventHandler onload = null;\n onload = delegate\n {\n item.Loaded -= onload;\n FocusItem(item, name);\n };\n item.Loaded += onload;\n return;\n }\n\n try\n {\n var myTemplate = FindResource(\"MyTemplateKey\") as FrameworkTemplate; // or however you get your template right now\n\n var ctl = myTemplate.FindName(name, item) as FrameworkElement;\n ctl.Focus();\n }\n catch\n {\n // focus something else if the template/item wasn't found?\n }\n}\n ItemContainerGenerator.StatusChanged ListBoxItem"
},
{
"answer_id": 3121634,
"author": "Jay",
"author_id": 114994,
"author_profile": "https://Stackoverflow.com/users/114994",
"pm_score": 4,
"selected": false,
"text": "TextBox TextBox.Load Focus() TextBox DataTemplate AutoFocusTextBox public class AutoFocusTextBox : TextBox\n{\n public AutoFocusTextBox()\n {\n Loaded += delegate { Focus(); }; \n }\n}\n DataTemplate <TextBox Text=\"{Binding Something, Mode=TwoWay}\" Style={StaticResource ...\n Loaded=\"FocusTextBoxOnLoad\" />\n private void FocusTextBoxOnLoad(object sender, RoutedEventArgs e)\n {\n var textbox = sender as TextBox;\n if(textbox == null) return;\n textbox.Focus();\n }\n"
},
{
"answer_id": 3674893,
"author": "Pete",
"author_id": 443202,
"author_profile": "https://Stackoverflow.com/users/443202",
"pm_score": 2,
"selected": false,
"text": "UIElement TextBox private void FocusControlOnLoad(object sender, RoutedEventArgs e)\n{\n var uiElement = sender as UiElement;\n if(uiElement == null) return;\n uiElement.Focus();\n}\n"
},
{
"answer_id": 11893918,
"author": "Jesse Seger",
"author_id": 81766,
"author_profile": "https://Stackoverflow.com/users/81766",
"pm_score": 3,
"selected": false,
"text": "FocusManager <DataTemplate x:Key=\"MyDataTemplate\" DataType=\"ListBoxItem\">\n <Grid>\n <WrapPanel Orientation=\"Horizontal\" FocusManager.FocusedElement=\"{Binding ElementName=tbText}\">\n <CheckBox IsChecked=\"{Binding Path=Completed}\" Margin=\"5\" />\n <Button Style=\"{StaticResource ResourceKey=DeleteButtonTemplate}\" Margin=\"5\" Click=\"btnDeleteItem_Click\" />\n <TextBox Name=\"tbText\" \n Text=\"{Binding Path=Text}\" \n Width=\"200\" \n TextWrapping=\"Wrap\" \n AcceptsReturn=\"True\" \n Margin=\"5\" \n Focusable=\"True\"/>\n <DatePicker Text=\"{Binding Path=Date}\" Margin=\"5\"/>\n </WrapPanel>\n </Grid>\n</DataTemplate>\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19146/"
] |
329,570 | <p>Is it possble to have something like this in ASP.NET MVC...</p>
<pre><code>[Authorize]
[AcceptVerbs(HttpVerbs.Get)]
public string AddData(string Issues, string LabelGUID)
{
return "Authorized";
}
[AcceptVerbs(HttpVerbs.Get)]
public string AddData()
{
return "Not Authorized";
}
</code></pre>
<p>So if the user is not logged in, it defaults to the un-Authorized action.</p>
| [
{
"answer_id": 329594,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 1,
"selected": false,
"text": "if (Request.IsAuthenticated)\n{ \n return \"Authorized\";\n}\nelse\n{ \n return \"Not Authorized\";\n}\n protected virtual bool AuthorizeCore(IPrincipal user)\n{\n if (user == null)\n {\n throw new ArgumentNullException(\"user\");\n }\n\n if (!user.Identity.IsAuthenticated)\n {\n return false;\n }\n\n ...snip...\n}\n"
},
{
"answer_id": 332181,
"author": "Doug Wilson",
"author_id": 32588,
"author_profile": "https://Stackoverflow.com/users/32588",
"pm_score": 3,
"selected": true,
"text": "ControllerActionInvoker FindActionMethod"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1231/"
] |
329,607 | <p>I am writing an xmpp library and I am trying to write a stream to support the zlib compressed data. I have two different versions one based on zlib.net and the other using SharpZipLib. The zlib.net version doesn't recognize the compression and the SharpZipLib version enters an infinite loop. You can find the appropriate code at <a href="http://github.com/coder2000/ubiety/tree/master/" rel="nofollow noreferrer">http://github.com/coder2000/ubiety/tree/master/</a> in xmpp.compression.zlib and xmpp.compression.sharpziplib. Any help to solve this problem would be appreciated.</p>
| [
{
"answer_id": 330091,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "offset count public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback cback, object state)\n{\n _outBuff = buffer;\n if ( _in.IsNeedingInput )\n return _innerStream.BeginRead(_inBuff, 0, _inBuff.Length, cback, state);\n\n ZlibStreamAsyncResult ar = new ZlibStreamAsyncResult(state);\n cback(ar);\n return ar;\n}\n GZipOutputStream"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42015/"
] |
329,613 | <p>I write financial applications where I constantly battle the decision to use a double vs using a decimal.</p>
<p>All of my math works on numbers with no more than 5 decimal places and are not larger than ~100,000. I have a feeling that all of these can be represented as doubles anyways without rounding error, but have never been sure.</p>
<p>I would go ahead and make the switch from decimals to doubles for the obvious speed advantage, except that at the end of the day, I still use the ToString method to transmit prices to exchanges, and need to make sure it always outputs the number I expect. (89.99 instead of 89.99000000001)</p>
<p>Questions:</p>
<ol>
<li>Is the speed advantage really as large as naive tests suggest? (~100 times)</li>
<li>Is there a way to guarantee the output from ToString to be what I want? Is this assured by the fact that my number is always representable?</li>
</ol>
<p>UPDATE: I have to process ~ 10 billion price updates before my app can run, and I have implemented with decimal right now for the obvious protective reasons, but it takes ~3 hours just to turn on, doubles would dramatically reduce my turn on time. Is there a safe way to do it with doubles?</p>
| [
{
"answer_id": 329738,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 3,
"selected": false,
"text": "double one = 3.05;\ndouble two = 0.05;\n\nSystem.Console.WriteLine((one + two) == 3.1);\n decimal one = 3.05m;\ndecimal two = 0.05m;\n\nSystem.Console.WriteLine((one + two) == 3.1m);\n"
},
{
"answer_id": 329758,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 5,
"selected": false,
"text": "typedef double scaled_int;\n\n#define SCALE_FACTOR 1.0e5 /* number of digits needed after decimal point */\n\nstatic inline scaled_int adds(scaled_int x, scaled_int y) { return x + y; }\nstatic inline scaled_int muls(scaled_int x, scaled_int y) { return x * y / SCALE_FACTOR; }\n\nstatic inline scaled_int scaled_of_int(int x) { return (scaled_int) x * SCALE_FACTOR; }\nstatic inline int intpart_of_scaled(scaled_int x) { return floor(x / SCALE_FACTOR); }\nstatic inline int fraction_of_scaled(scaled_int x) { return x - SCALE_FACTOR * intpart_of_scaled(x); }\n\nvoid fprint_scaled(FILE *out, scaled_int x) {\n fprintf(out, \"%d.%05d\", intpart_of_scaled(x), fraction_of_scaled(x));\n}\n int64_t"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10094/"
] |
329,622 | <p>Well basically I have this script that takes a long time to execute and occasionally times out and leaves semi-complete data floating around my database. (Yes I know in a perfect world I would fix THAT instead of implementing commits and rollbacks but I am forced to not do that)</p>
<p>Here is my basic code (dumbed down for simplicity):</p>
<pre><code>$database = new PDO("mysql:host=host;dbname=mysql_db","username","password");
while (notDone())
{
$add_row = $database->prepare("INSERT INTO table (columns) VALUES (?)");
$add_row->execute(array('values'));
//PROCESSING STUFF THAT TAKES A LONG TIME GOES HERE
}
$database = null;
</code></pre>
<p>So my problem is that if that if the entire process within that while loop isn't complete then I don't want the row inserted to remain there. I think that somehow I could use commits/rollbacks at the beginning and end of the while loop to do this but don't know how.</p>
| [
{
"answer_id": 329629,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 4,
"selected": true,
"text": "$dbh->beginTransaction();\n...\n$dbh->commit();\n"
},
{
"answer_id": 625437,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<?php\n//This may help someone....This code commit the transactions\n//only if both queries insert and update successfully runs\n\n$mysqli=new mysqli(\"localhost\",\"user_name\",\"password\",\"db_name\");\n\nif(mysqli_connect_errno())\n{\n echo \"Connection failed: \".mysqli_connect_error();\n}\nelse\n{\n $mysqli->autocommit(FALSE);\n $mysqli->query(\"insert into tblbook (id,cid,book) values('','3','book3.1')\");\n echo $q_ins=$mysqli->affected_rows.\"<br>\";\n $mysqli->query(\"update tblbook set book='book3' where cid='3'\");\n echo $q_upd=$mysqli->affected_rows.\"<br>\";\n\n if($q_ins==1 && $q_upd==1)\n {\n $mysqli->commit();\n echo \"Commit<br>\";\n }\n else\n {\n $mysqli->rollback();\n echo \"Rollback<br>\";\n }\n}\n?>\n"
},
{
"answer_id": 4407717,
"author": "Neelesh",
"author_id": 537695,
"author_profile": "https://Stackoverflow.com/users/537695",
"pm_score": 1,
"selected": false,
"text": "try\n{\n $mysqli->autocommit(FALSE);\n $mysqli->query(\"insert into tblbook (id,cid,book) values('','3','book3.1')\");\n echo $q_ins=$mysqli->affected_rows.\"<br>\";\n $mysqli->query(\"update tblbook set book='book3' where cid='3'\");\n echo $q_upd=$mysqli->affected_rows.\"<br>\";\n $mysqli->commit();\n}\ncatch(PDOException $e)\n{\n $mysqli->rollback();\n echo $sql . '<br />' . $e->getMessage();\n}\n"
}
] | 2008/11/30 | [
"https://Stackoverflow.com/questions/329622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
329,652 | <p>One thing I really like about AS3 over AS2 is how much more compile-time type-checking it adds. However, it seems to be somewhat lacking in that there is no type-checked enumeration structure available. What's a good (best / accepted) way to do custom enumerated types in AS3?</p>
| [
{
"answer_id": 14155541,
"author": "Joachim Lous",
"author_id": 628371,
"author_profile": "https://Stackoverflow.com/users/628371",
"pm_score": 1,
"selected": false,
"text": "public final class FruitEnum {\n private static const CREATE:Object = {};\n\n public static const APPLE:FruitEnum = new FruitEnum(CREATE);\n public static const ORANGE:FruitEnum = new FruitEnum(CREATE);\n public static const BANANA:FruitEnum = new FruitEnum(CREATE);\n\n public function FruitEnum(permission:Object) {\n if (permission !== CREATE){\n throw new Error(\"Enum cannot be instantiated from outside\");\n }\n }\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26933/"
] |
329,658 | <p>How do I achieve authorization with MVC asp.net?</p>
| [
{
"answer_id": 717312,
"author": "Dan",
"author_id": 230,
"author_profile": "https://Stackoverflow.com/users/230",
"pm_score": 7,
"selected": true,
"text": "[Authorize]\npublic ActionResult MyAction()\n{\n //stuff\n}\n public class CustomAuthorizeAttribute : AuthorizeAttribute\n {\n protected override bool AuthorizeCore(HttpContextBase httpContext)\n {\n string[] users = Users.Split(',');\n\n if (!httpContext.User.Identity.IsAuthenticated)\n return false;\n\n if (users.Length > 0 &&\n !users.Contains(httpContext.User.Identity.Name,\n StringComparer.OrdinalIgnoreCase))\n return false;\n\n return true;\n }\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29445/"
] |
329,676 | <p>In a WPF UserControl, I have to make to call to a WebService. I am making this call on a separate thread but I want to inform the user that the call may take some time. </p>
<p>The WebMethod returns me a collection of objects and I bind it to a ListBox in my UC. So far, so good... This part works really well. However, <strong>I want to display a progress bar (or an animation of any kind...) during the call. This animation would be on top and centered in the ListBox control.</strong></p>
<p>I tried Adorner and it partially works. However, I have to draw all controls in protected override void OnRender(DrawingContext drawingContext)... I simply want to add a control for a couple of seconds...</p>
<p>Anybody has an idea of how I could achieve this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 329714,
"author": "Rob",
"author_id": 18505,
"author_profile": "https://Stackoverflow.com/users/18505",
"pm_score": 4,
"selected": true,
"text": " <Grid x:Name=\"layoutRoot\">\n <Grid x:Name=\"contentGrid\" HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\" Visibility=\"Visible\">\n <!-- snip -->\n </Grid>\n\n <controls:ProgressGrid x:Name=\"progressGrid\" Text=\"Signing in, please wait...\" Visibility=\"Collapsed\"/>\n </Grid>\n private void SignInCommand_Executed(object sender, ExecutedRoutedEventArgs e)\n {\n contentGrid.Visibility = Visibility.Collapsed;\n progressGrid.Visibility = Visibility.Visible;\n }\n"
},
{
"answer_id": 329715,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 1,
"selected": false,
"text": "<DockPanel LastChildFill=\"True\">\n <Button DockPanel.Dock=\"Top\" Name=\"showButton\" Click=\"showProgress\">show</Button>\n <StackPanel DockPanel.Dock=\"Bottom\">\n <Canvas Name=\"zeroHeight\" Height=\"0\"/>\n <InkCanvas Name=\"inky\">\n </InkCanvas>\n </StackPanel>\n</DockPanel>\n\n\nprivate void showProgress(object sender, RoutedEventArgs e)\n{\n TextBox box = new TextBox();\n box.Text = \"on top\";\n StackPanel.SetZIndex(zeroHeight, 8);\n zeroHeight.Children.Add(box);\n box.Width = 30;\n box.Height = 30;\n Canvas.SetLeft(box, 10);\n Canvas.SetTop(box, 10);\n Canvas.SetZIndex(box, 10);\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42024/"
] |
329,682 | <p>One of the nice feature of the Image control is that we can specified an Uri as the ImageSource and the image is automatically downloaded for us. This is great! <strong>However, the control doesn't seem to have a property indicating if the image loading is in progress or not.</strong></p>
<p>Is there a property telling us the status (Downloading, Downloaded, etc.) of the Image control?</p>
<p>Thanks!</p>
| [
{
"answer_id": 330323,
"author": "Ramiro Berrelleza",
"author_id": 548,
"author_profile": "https://Stackoverflow.com/users/548",
"pm_score": 3,
"selected": true,
"text": "<Grid>\n <Grid.RowDefinitions>\n <RowDefinition Height=\"50\" />\n <RowDefinition Height=\"50\" />\n <RowDefinition Height=\"*\" />\n </Grid.RowDefinitions>\n <Image x:Name=\"image\" Grid.Row=\"2\"/>\n <Label x:Name=\"label\" Content=\"aaa\" Grid.Row=\"1\" />\n <Button Click=\"Button_Click\" Content=\"Click to load image\" Grid.Row=\"0\" />\n</Grid>\n private void Button_Click(object sender, RoutedEventArgs e)\n{\n BitmapImage bi = new BitmapImage();\n bi.BeginInit();\n bi.DecodePixelHeight = 100;\n bi.CacheOption = BitmapCacheOption.OnLoad;\n bi.UriSource = new Uri(\"bigImageUri\");\n bi.EndInit();\n\n bi.DownloadCompleted += new EventHandler(bi_DownloadCompleted);\n image.Source = bi; \n\n\n}\n\nvoid bi_DownloadCompleted(object sender, EventArgs e)\n{\n label.Content = \"dl completed\";\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42024/"
] |
329,686 | <p>I am attempting to create a UML diagram representative of some Java code.</p>
<p>In a class I have a method that is overloaded.</p>
<p>As far as I know, parameters for methods aren't shown in UML diagrams.</p>
<p>How do I represent method overloading in UML?</p>
<p>Thanks.</p>
| [
{
"answer_id": 329784,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "+doSomething(p:AThing):int{redefines}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329686",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25985/"
] |
329,724 | <p>I have this marked as PHP but only because I'll be using PHP code to show my problem.</p>
<p>So I have some code like this for the controller:</p>
<pre><code>switch ($page)
{
case "home":
require "views/home.php";
break;
case "search":
require "views/search.php";
break;
}
</code></pre>
<p>Obviously there's more pages but this should illustrate my issue. There is a common header, navigation and footer for both of these pages (and for all pages on the site for that matter). Should I be using multiple require statements? My first guess would be:</p>
<pre><code>switch ($page)
{
case "home":
require "templates/header.php";
require "templates/navigation.php";
require "views/home.php";
require "templates/footer.php";
break;
case "search":
require "templates/header.php";
require "templates/navigation.php";
require "views/search.php";
require "templates/footer.php";
break;
}
</code></pre>
<p>Somehow my gut tells me this isn't correct.</p>
| [
{
"answer_id": 329854,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 1,
"selected": false,
"text": " require \"templates/header.php\";\n require \"templates/navigation.php\";\n require \"views/$page.php\";\n require \"templates/footer.php\";\n"
},
{
"answer_id": 331372,
"author": "Alarion",
"author_id": 39420,
"author_profile": "https://Stackoverflow.com/users/39420",
"pm_score": -1,
"selected": false,
"text": "$_SESSION['page'] = sanitize_input($_GET['page']);\nrequire \"templates/main.php\";\n require \"templates/header.php\";\nrequire \"templates/navigation.php\";\nrequire \"views/{$_SESSION['page']}.php\";\nrequire \"templates/footer.php\";\n"
},
{
"answer_id": 332153,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "class Template {\n var $pagename = 'index';\n\n function __construct() {\n $this->pagename = basename($_SERVER['SCRIPT_NAME'], '.php');\n register_shutdown_function(array($this, 'do_output'));\n }\n\n function do_output() {\n $this->header();\n $this->display($this->pagename);\n $this->footer();\n }\n\n function __call($template, array $params) {\n call_user_func(array($this, 'display'), $template, params);\n }\n\n function display($template, array $params = null) {\n include \"templates/$template.php\";\n }\n}\n require \"templates/header.php\";\nrequire \"templates/navigation.php\";\nswitch ($page)\n{\n case \"home\":\n require \"views/home.php\";\n break;\n case \"search\":\n require \"views/search.php\";\n break;\n}\nrequire \"templates/footer.php\";\n"
},
{
"answer_id": 337485,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "require \"templates/header.php\";\nrequire \"templates/navigation.php\";\n\nswitch ($page) {\n case \"home\":\n require \"views/home.php\";\n break;\n case \"search\":\n require \"views/search.php\";\n break;\n}\n\nrequire \"templates/footer.php\";\n"
},
{
"answer_id": 16952854,
"author": "Brock Hensley",
"author_id": 1992193,
"author_profile": "https://Stackoverflow.com/users/1992193",
"pm_score": 0,
"selected": false,
"text": "switch require \"templates/header.php\";\nrequire \"templates/navigation.php\";\nrequire 'views/' . $page . '.php'; // <-- one-liner\nrequire \"templates/footer.php\";\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
329,775 | <p>I'm having trouble with a web application that will deadlock occasionally</p>
<p>There are 3 queries involved. 2 are trying to update a table</p>
<pre><code>UPDATE AttendanceRoll
SET ErrorFlag = 0
WHERE ContractID = @ContractID
AND DATEPART(month,AttendanceDate) = DATEPART(month,@Month_Beginning)
AND DATEPART(year,AttendanceDate) = DATEPART(year,@Month_Beginning)
</code></pre>
<p>and one is trying to insert into the table</p>
<pre><code>INSERT INTO AttendanceRoll
(AttendanceDate, ContractID, PersonID,
StartTime,
EndTime,
Hours, AbsenceReason,
UpdateCount, SplitShiftID, ModifiedBy, ModifiedDate)
SELECT
@P33, @P34, @P35,
CONVERT(datetime,REPLACE( @P36, '.', ':')),
CONVERT(datetime,REPLACE( @P37, '.', ':')),
@P38, @P39,
@P40, 1, @P41, GETDATE()
</code></pre>
<p>The deadlock graph shows a kind of circular arangement of page locks and an exchange event and the 2 update queries have the same server process id.</p>
<p>If anyone has any ideas about how I should go about solving this issue it would be most appreciated.</p>
<p>I have the deadlock graph that I can post if anybody needs to see it.</p>
<p>Thanks
Carl R</p>
| [
{
"answer_id": 2655303,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 0,
"selected": false,
"text": "for (;;) {\n try {\n using (var t = BeginTransaction()) {\n DoTheCall();\n t.Commit();\n return;\n }\n }\n catch (SqlException ex) {\n if (ex.Number != 1205 && ex.Number != 601 && ex.Number != 605)\n throw;\n }\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
329,805 | <p>In jQuery, if I assign <code>class=auto_submit_form</code> to a form, it will be submitted whenever any element is changed, with the following code:</p>
<pre><code>/* automatically submit if any element in the form changes */
$(function() {
$(".auto_submit_form").change(function() {
this.submit();
});
});
</code></pre>
<p>However, if I want to the form to submit only when specified elements are changed:</p>
<pre><code>/* submit if elements of class=auto_submit_item in the form changes */
$(function() {
$(".auto_submit_item").change(function() {
$(this).parents().filter("form").submit();
});
});
</code></pre>
<p>I'm just learning jQuery. Is there a better way to do this?</p>
| [
{
"answer_id": 329810,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": true,
"text": " /* submit if elements of class=auto_submit_item in the form changes */\n$(function() {\n $(\".auto_submit_item\").change(function() {\n $(\"form\").submit();\n });\n });\n $(this).parents(\"form\").submit()"
},
{
"answer_id": 329860,
"author": "Darko",
"author_id": 32943,
"author_profile": "https://Stackoverflow.com/users/32943",
"pm_score": 4,
"selected": false,
"text": "parents() /* submit if elements of class=auto_submit_item in the form changes */\n$(\".auto_submit_item\").change(function() {\n $(this).parents(\"form\").submit();\n});\n"
},
{
"answer_id": 329875,
"author": "Murat Ayfer",
"author_id": 25910,
"author_profile": "https://Stackoverflow.com/users/25910",
"pm_score": 3,
"selected": false,
"text": "$(\".auto-submit-item\").change(function() {\n $(\"form#auto-submit\").submit();\n});\n"
},
{
"answer_id": 44944674,
"author": "Lilleman",
"author_id": 254532,
"author_profile": "https://Stackoverflow.com/users/254532",
"pm_score": 2,
"selected": false,
"text": "$('.autoSubmit, .autoSubmit select, .autoSubmit input, .autoSubmit textarea').change(function () {\n const el = $(this);\n let form;\n\n if (el.is('form')) { form = el; }\n else { form = el.closest('form'); }\n\n form.submit();\n});\n <form class=\"autoSubmit\">\n <select><option>1</option><option>2</option></select>\n</form>\n <form>\n <select class=\"autoSubmit\"><option>1</option><option>2</option></select>\n</form>\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41759/"
] |
329,822 | <p>I have three tables in the many-to-many format. I.e, table A, B, and AB set up as you'd expect. </p>
<p>Given some set of A ids, I need to select only the rows in AB that match all of the ids. </p>
<p>Something like the following won't work:</p>
<p>"SELECT * FROM AB WHERE A_id = 1 AND A_id = 2 AND A_id = 3 AND ... "
As no single row will have more than one A_id</p>
<p>Using, an OR in the sql statment is no better as it yields results all results that have at least one of the A ids (whereas I only want those rows that have all of the ids). </p>
<p><strong>Edit:</strong></p>
<p>Sorry, I should explain. I don't know if the actual many-to-many relationship is relevant to the actual problem. The tables are outlined as follows:</p>
<pre><code>Table People
int id
char name
Table Options
int id
char option
Table peoples_options
int id
int people_id
int option_id
</code></pre>
<p>And so I have a list of people, and a list of options, and a table of options and people. </p>
<p>So, given a list of option ids such as (1, 34, 44, ...), I need to select only those people that have all the options. </p>
| [
{
"answer_id": 329841,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "AB A_id B_id OR IN B A table a:\n a_id integer\n a_payload varchar(20)\ntable b:\n b_id integer\n b_payload varchar(20)\ntable ab:\n a_id integer\n b_id integer\n B A AB B A select distinct b_id from ab n1 \n where exists (select b_id from ab where a_id = 1 and b_id = n1.b_id) \n and exists (select b_id from ab where a_id = 3 and b_id = n1.b_id) \n and exists (select b_id from ab where a_id = 4 and b_id = n1.b_id); \n"
},
{
"answer_id": 329862,
"author": "Rick",
"author_id": 14138,
"author_profile": "https://Stackoverflow.com/users/14138",
"pm_score": 1,
"selected": true,
"text": "SELECT B_id FROM AB\nWHERE A_id IN (1,2,3)\nGROUP BY B_id\nHAVING COUNT(DISTINCT A_id) = 3;\n"
},
{
"answer_id": 26724728,
"author": "pablo.vix",
"author_id": 3051783,
"author_profile": "https://Stackoverflow.com/users/3051783",
"pm_score": 0,
"selected": false,
"text": "select\n p.*\nfrom\n people p\nwhere\n not exists (\n select \n 1 \n from \n options o\n where\n not exists \n (\n select 1\n from peoples_options po \n where po.people_id = p.people_id\n AND po.option_id = o.option_id\n )\n )\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42033/"
] |
329,837 | <p>I need to create simple reusable javascript object publishing several methods and parameterized constructor. After reading through several "OOP in JavaScript" guides I'm sitting here with an empty head. How on the Earth can I do this?</p>
<p>Here my last non-working code:</p>
<pre><code>SomeClass = function(id) {
this._id = id;
}
(function() {
function intFun() {
return this._id;
}
SomeClass.prototype.extFun = function() {
return incFun();
}
})();
</code></pre>
| [
{
"answer_id": 329846,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 3,
"selected": false,
"text": "MyClass = function(x, y, z) {\n // This is the constructor. When you use it with \"new MyClass(),\"\n // then \"this\" refers to the new object being constructed. So you can\n // assign member variables to it.\n this.x = x;\n ...\n};\nMyClass.prototype = {\n doSomething: function() {\n // Here we can use the member variable that\n // we created in the constructor.\n return this.x;\n },\n somethingElse: function(a) {\n }\n};\n\nvar myObj = new MyClass(1,2,3);\nalert(myObj.doSomething()); // this will return the object's \"x\" member\nalert(myObj.x); // this will do the same, by accessing the member directly\n myDiv.onclick = myObj.doSomething;\n myDiv.onclick = function() {\n myObj.doSomething.call(myObj);\n}\n"
},
{
"answer_id": 329864,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "var MyClass = function() {};\n\nMyClass.prototype = {\n _someVar : null,\n _otherVar : null,\n\n initialize: function( optionHash ) {\n _someVar = optionsHash[\"varValue\"];\n _otherVar = optionsHash[\"otherValue\"];\n },\n\n method: function( arg ) {\n return _someVar + arg; \n },\n};\n var myClass = new MyClass( { varValue: -1, otherValue: 10 } );\nvar foo = myClass.method(6);\n"
},
{
"answer_id": 329873,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": true,
"text": "SomeClass = function (id) {\n var THIS = this; // unambiguous reference\n THIS._id = id;\n\n var intFun = function () { // private\n return THIS._id;\n }\n\n this.extFun = function () { // public\n return intFun();\n }\n}\n THIS this"
},
{
"answer_id": 23839532,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "// The module pattern\nvar feature = (function() {\n\n // private variables and functions\n var privateThing = \"secret\";\n var publicThing = \"not secret\";\n\n var changePrivateThing = function() {\n privateThing = \"super secret\";\n };\n\n var sayPrivateThing = function() {\n console.log( privateThing );\n changePrivateThing();\n };\n\n // public API\n return {\n publicThing: publicThing,\n sayPrivateThing: sayPrivateThing\n };\n\n})();\n\nfeature.publicThing; // \"not secret\"\n\n// logs \"secret\" and changes the value of privateThing\nfeature.sayPrivateThing();\n this.variable var variable"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
329,838 | <p>I have, for my game, a Packet class, which represents network packet and consists basically of an array of data, and some pure virtual functions</p>
<p>I would then like to have classes deriving from Packet, for example: StatePacket, PauseRequestPacket, etc. Each one of these sub-classes would implement the virtual functions, Handle(), which would be called by the networking engine when one of these packets is received so that it can do it's job, several get/set functions which would read and set fields in the array of data.</p>
<p>So I have two problems:</p>
<ol>
<li>The (abstract) Packet class would need to be copyable and assignable, but without slicing, keeping all the fields of the derived class. It may even be possible that the derived class will have no extra fields, only function, which would work with the array on the base class. How can I achieve that?</li>
<li>When serializing, I would give each sub-class an unique numeric ID, and then write it to the stream before the sub-class' own serialization. But for unserialization, how would I map the read ID to the appropriate sub-class to instanciate it?</li>
</ol>
<p>If anyone want's any clarifications, just ask.</p>
<p>-- Thank you</p>
<hr>
<p><strong>Edit:</strong> I'm not quite happy with it, but that's what I managed:</p>
<p>Packet.h: <a href="http://pastebin.com/f512e52f1" rel="nofollow noreferrer">http://pastebin.com/f512e52f1</a><br>
Packet.cpp: <a href="http://pastebin.com/f5d535d19" rel="nofollow noreferrer">http://pastebin.com/f5d535d19</a><br>
PacketFactory.h: <a href="http://pastebin.com/f29b7d637" rel="nofollow noreferrer">http://pastebin.com/f29b7d637</a><br>
PacketFactory.cpp: <a href="http://pastebin.com/f689edd9b" rel="nofollow noreferrer">http://pastebin.com/f689edd9b</a><br>
PacketAcknowledge.h: <a href="http://pastebin.com/f50f13d6f" rel="nofollow noreferrer">http://pastebin.com/f50f13d6f</a><br>
PacketAcknowledge.cpp: <a href="http://pastebin.com/f62d34eef" rel="nofollow noreferrer">http://pastebin.com/f62d34eef</a> </p>
<p>If someone has the time to look at it and suggest any improvements, I'd be thankful.</p>
<hr>
<p>Yes, I'm aware of the factory pattern, but how would I code it to construct each class? A giant switch statement? That would also duplicade the ID for each class (once in the factory and one in the serializator), which I'd like to avoid.</p>
| [
{
"answer_id": 329851,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "virtual Packet * clone() const = 0;\n virtual Packet * clone() const {\n return new StatePacket(*this);\n}\n struct MessageFactory {\n std::map<Packet::IdType, Packet (*)()> map;\n\n MessageFactory() {\n map[StatePacket::Id] = &StatePacket::createInstance;\n // ... all other\n }\n\n Packet * createInstance(Packet::IdType id) {\n return map[id](); \n }\n} globalMessageFactory;\n"
},
{
"answer_id": 330797,
"author": "coryan",
"author_id": 33325,
"author_profile": "https://Stackoverflow.com/users/33325",
"pm_score": 0,
"selected": false,
"text": "class Packet { ... };\n\ntypedef Packet* (*packet_creator)();\n\nclass Factory {\npublic:\n bool add_type(int id, packet_creator) {\n map_[id] = packet_creator; return true;\n }\n};\n\ntemplate<typename T>\nclass register_with_factory {\npublic:\n static Packet * create() { return new T; }\n static bool registered;\n};\n\ntemplate<typename T>\nbool register_with_factory<T>::registered = Factory::add_type(T::id(), create);\n\nclass MyPacket : private register_with_factory<MyPacket>, public Packet {\n//... your stuff here...\n\n static int id() { return /* some number that you decide */; }\n};\n"
},
{
"answer_id": 332061,
"author": "Mr.Ree",
"author_id": 37946,
"author_profile": "https://Stackoverflow.com/users/37946",
"pm_score": 0,
"selected": false,
"text": "class Packet\n{\npublic:\n enum PACKET_TYPES\n {\n STATE_PACKET = 0,\n PAUSE_REQUEST_PACKET,\n\n MAXIMUM_PACKET_TYPES,\n FIRST_PACKET_TYPE = STATE_PACKET\n };\n\n typedef bool ( * HandlerType ) ( const Packet & );\n\nprotected:\n /* Note: Initialize handlers to NULL when declared! */\n static HandlerType handlers [ MAXIMUM_PACKET_TYPES ];\n\n static HandlerType getHandler( int thePacketType )\n { // My own assert macro...\n UASSERT( thePacketType, >=, FIRST_PACKET_TYPE );\n UASSERT( thePacketType, <, MAXIMUM_PACKET_TYPES );\n UASSERT( handlers [ thePacketType ], !=, HandlerType(NULL) );\n return handlers [ thePacketType ];\n }\n\nprotected:\n struct Data\n {\n // Common data to all packets.\n int number;\n int type;\n\n union\n {\n struct\n {\n int foo;\n } statePacket;\n\n struct\n {\n int bar;\n } pauseRequestPacket;\n\n } u;\n\n } data;\n\n\npublic:\n\n //...\n bool readFromSocket() { /*read(&data); */ } // Unmarshal\n bool writeToSocket() { /*write(&data);*/ } // Marshal\n\n bool handle() { return ( getHandler( data.type ) ) ( * this ); }\n\n}; /* class Packet */\n c++decl> declare foo as function(int) returning pointer to function returning void\nvoid (*foo(int ))()\nc++decl> explain void (* getHandler( int ))( const int & );\ndeclare getHandler as function (int) returning pointer to function (reference to const int) returning void\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42029/"
] |
329,865 | <p>I am trying to create a serial port in VB.net using code only. Because I am creating a class library I cannot use the built-in component. I have tried instantiating a new SeialPort() object, but that does not seem to be enough. I'm sure there is something simple I am missing and any help would be greatly appreciated! Thanks! </p>
<p>P.S. I should add that the problem I am having at this time is getting the code to handle the datareceived event. Other than that it might be working, but I can't tell because of that problem.</p>
| [
{
"answer_id": 329894,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": false,
"text": "port = new System.IO.Ports.SerialPort(name, 4800, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);\nport.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);\nport.Open();\n\nvoid port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n{\n buffer = port.ReadLine();\n // process line\n}\n"
},
{
"answer_id": 331870,
"author": "Dilbert789",
"author_id": 77830,
"author_profile": "https://Stackoverflow.com/users/77830",
"pm_score": 4,
"selected": true,
"text": "Imports System.Threading\n\nImports System.IO\n\nImports System.Text\n\nImports System.IO.Ports\n\n\nPublic Class clsBarcodeScanner\n\nPublic Event ScanDataRecieved(ByVal data As String)\nWithEvents comPort As SerialPort\n\nPublic Sub Connect()\n Try\n comPort = My.Computer.Ports.OpenSerialPort(\"COM5\", 9600)\n Catch\n End Try\nEnd Sub\n\nPublic Sub Disconnect()\n\n If comPort IsNot Nothing AndAlso comPort.IsOpen Then\n comPort.Close()\n End If\n\nEnd Sub\n\nPrivate Sub comPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles comPort.DataReceived\n Dim str As String = \"\"\n If e.EventType = SerialData.Chars Then\n Do\n Dim bytecount As Integer = comPort.BytesToRead\n\n If bytecount = 0 Then\n Exit Do\n End If\n Dim byteBuffer(bytecount) As Byte\n\n\n comPort.Read(byteBuffer, 0, bytecount)\n str = str & System.Text.Encoding.ASCII.GetString(byteBuffer, 0, 1)\n\n Loop\n End If\n\n RaiseEvent ScanDataRecieved(str)\n\nEnd Sub\nEnd Class\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21958/"
] |
329,866 | <p>I can successfully connect to MySQL from a DOS prompt, but when I try to connect from cygwin, it just hangs.</p>
<pre><code>$/cygdrive/c/Program\ Files/MySQL/MySQL\ Server\ 5.1/bin/mysql -u root -p
</code></pre>
<p>What's wrong?</p>
| [
{
"answer_id": 329941,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 5,
"selected": true,
"text": "DOS bash mysql CYGWIN bash"
},
{
"answer_id": 9996769,
"author": "Svend Hansen",
"author_id": 779130,
"author_profile": "https://Stackoverflow.com/users/779130",
"pm_score": 6,
"selected": false,
"text": "which mysql $ which mysql\n/cygdrive/c/Program Files/MySQL/MySQL Server 5.5/bin/mysql\n Setup.exe which mysql $ which mysql\n/usr/bin/mysql\n $ mysql -u root -p\nEnter password:\nERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysql.sock' (2)\n -h 127.0.0.1 $ mysql -u root -p -h 127.0.0.1\n -h 127.0.0.1 [client]\nhost=127.0.0.1\n /etc/my.cnf -h --protocol=tcp\n protocol=tcp\n"
},
{
"answer_id": 17654860,
"author": "Donal Lafferty",
"author_id": 939250,
"author_profile": "https://Stackoverflow.com/users/939250",
"pm_score": 3,
"selected": false,
"text": "c:\\cygwin\\bin\\mintty.exe c:\\cygwin\\Cygwin.bat c:\\cygwin\\bin\\bash.exe which $ which mysql\n/cygdrive/c/Program Files/MySQL/MySQL Server 5.1/bin/mysql\n"
},
{
"answer_id": 21509442,
"author": "Bakudan",
"author_id": 179669,
"author_profile": "https://Stackoverflow.com/users/179669",
"pm_score": 1,
"selected": false,
"text": "which mysql\n /cygdrive/c/Program Files/MySQL/MySQL Server 5.5/bin/mysql\n"
},
{
"answer_id": 23164630,
"author": "martian111",
"author_id": 1034436,
"author_profile": "https://Stackoverflow.com/users/1034436",
"pm_score": 0,
"selected": false,
"text": "mysql console.exe"
},
{
"answer_id": 49353487,
"author": "Ken Ingram",
"author_id": 1418533,
"author_profile": "https://Stackoverflow.com/users/1418533",
"pm_score": 0,
"selected": false,
"text": "ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysql.sock' (2 \"No such file or directory\")\n /etc/my.conf /etc/my.cnf.d /etc/my.cnf.d/client.cnf [client]\nhost=127.0.0.1\nprotocol=tcp\n mysql -u root -p"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1094969/"
] |
329,876 | <p>i have a few classes that i am trying to move to using generics</p>
<p>Class1: Curve</p>
<p>this class has the following code:</p>
<pre><code>public class Curve : IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator(); // Calls non-interface method
}
public RTRatePointEnumerator GetEnumerator()
{
return new RTRatePointEnumerator(_hash);
}
</code></pre>
<p>Class 2:</p>
<pre><code> public class CurvePointEnumerator : IEnumerator
</code></pre>
<p>what is the recommended conversion of these two classes to using generics</p>
| [
{
"answer_id": 329888,
"author": "C. Broadbent",
"author_id": 28859,
"author_profile": "https://Stackoverflow.com/users/28859",
"pm_score": 0,
"selected": false,
"text": "IEnumerable<T> and IEnumerator<T>"
},
{
"answer_id": 329915,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 2,
"selected": true,
"text": "class Curve: IEnumerable<RTRatePoint> {\n IEnumerator<RTRatePoint> IEnumerable<RTRatePoint>.GetEnumerator() { \n return GetEnumerator();\n }\n public RTRatePointEnumerator GetEnumerator() {\n return new RTRatePointEnumerator(_hash);\n }\n}\n\nclass CurvePointEnumerator : IEnumerator<CurvePoint>\n void IDispose.Dispose() {\n // Nothing to see here\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
329,886 | <p>Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following <a href="http://www.haskell.org/haskellwiki/List_comprehension" rel="noreferrer">Haskell code</a>:</p>
<pre><code>[(i,j) | i <- [1,2], j <- [1..4]]
</code></pre>
<p>which yields</p>
<pre><code>[(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)]
</code></pre>
<p>Can I obtain a similar behavior in Python in a concise way?</p>
| [
{
"answer_id": 329904,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": "[ (i,j) for i in range(1,3) for j in range(1,5) ]\n"
},
{
"answer_id": 329978,
"author": "A. Coady",
"author_id": 36433,
"author_profile": "https://Stackoverflow.com/users/36433",
"pm_score": 3,
"selected": false,
"text": ">>> import itertools\n>>> list(itertools.product(range(1, 3), range(1, 5)))\n[(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)]\n"
},
{
"answer_id": 330335,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 3,
"selected": false,
"text": "[ (i,j) for i in range(10) for j in range(i) ] \n (i,j) 0>=i>j>10"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18770/"
] |
329,900 | <p>My question revolves around CSS Fixed Layout vs a Float Layout that extends to fill the width of the browser.</p>
<p>Right now the issue I'm running into is to have the masthead resize depending on the width of the page (something that I understand isn't possible given current browser implementation of <a href="http://www.w3.org/TR/2002/WD-css3-background-20020802/" rel="nofollow noreferrer">CSS3's <code>background-image: size;</code></a>). At this point, I feel like I've reached an impasse all around: Do I rework the site to use a fixed CSS layout, or do I keep the current layout and try to make the masthead image expand to fill most of the space provided? Moreover, what are the pros and cons of moving to a fixed width layout, and the other (unseen) ramifications of using one layout over another?</p>
<p>The site in question will be given as a comment to this question -- I don't want to be seen as trying to increase traffic to it.</p>
<p>Edit: Any other thoughts?</p>
| [
{
"answer_id": 333628,
"author": "gregnostic",
"author_id": 41891,
"author_profile": "https://Stackoverflow.com/users/41891",
"pm_score": 4,
"selected": true,
"text": "<div id=\"page\">\n <div id=\"masthead\">...</div>\n <div id=\"navigation\">...</div>\n ...\n</div>\n #page {\n max-width: 1600px;\n min-width: 800px;\n width: 80%;\n}\n\n#masthead {\n background: url('path/to/image.jpg') no-repeat left top;\n height: 100px;\n width: auto;\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16587/"
] |
329,918 | <h2>What I'm trying to accomplish</h2>
<ul>
<li>My app generates some tabular data</li>
<li>I want the user to be able to launch Excel and click "paste" to place the data as cells in Excel</li>
<li>Windows accepts a format called "CommaSeparatedValue" that is used with it's APIs so this seems possible</li>
<li>Putting raw text on the clipboard works, but trying to use this format does not</li>
<li>NOTE: I can correctly retrieve CSV data from the clipboard, my problem is about pasting CSV data to the clipboard.</li>
</ul>
<h2>What I have tried that isn't working</h2>
<p>Clipboard.SetText()</p>
<pre><code>System.Windows.Forms.Clipboard.SetText(
"1,2,3,4\n5,6,7,8",
System.Windows.Forms.TextDataFormat.CommaSeparatedValue
);
</code></pre>
<p>Clipboard.SetData()</p>
<pre><code>System.Windows.Forms.Clipboard.SetData(
System.Windows.Forms.DataFormats.CommaSeparatedValue,
"1,2,3,4\n5,6,7,8",
);
</code></pre>
<p>In both cases something is placed on the clipboard, but when pasted into Excel it shows up as one cell of garbarge text: "–§žý;pC¦yVk²ˆû"</p>
<h2>Update 1: Workaround using SetText()</h2>
<p>As BFree's answer shows <strong>SetText</strong> with <strong>TextDataFormat</strong> serves as a workaround</p>
<pre><code>System.Windows.Forms.Clipboard.SetText(
"1\t2\t3\t4\n5\t6\t7\t8",
System.Windows.Forms.TextDataFormat.Text
);
</code></pre>
<p>I have tried this and confirm that now pasting into Excel and Word works correctly. In each case it pastes as a table with cells instead of plaintext.</p>
<p>Still curious why CommaSeparatedValue is <em>not</em> working.</p>
| [
{
"answer_id": 329967,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 3,
"selected": false,
"text": "Clipboard.SetText(\"1\\t2\\t3\\t4\\t3\\t2\\t3\\t4\", TextDataFormat.Text);\n"
},
{
"answer_id": 369219,
"author": "user46432",
"author_id": 46432,
"author_profile": "https://Stackoverflow.com/users/46432",
"pm_score": 6,
"selected": true,
"text": "DataFormats.CommaSeparatedValue // Generate both tab-delimited and CSV strings.\nstring tabbedText = //...\nstring csvText = //...\n\n// Create the container object that will hold both versions of the data.\nvar dataObject = new System.Windows.DataObject();\n\n// Add tab-delimited text to the container object as is.\ndataObject.SetText(tabbedText);\n\n// Convert the CSV text to a UTF-8 byte stream before adding it to the container object.\nvar bytes = System.Text.Encoding.UTF8.GetBytes(csvText);\nvar stream = new System.IO.MemoryStream(bytes);\ndataObject.SetData(System.Windows.DataFormats.CommaSeparatedValue, stream);\n\n// Copy the container object to the clipboard.\nSystem.Windows.Clipboard.SetDataObject(dataObject, true);\n"
},
{
"answer_id": 68537627,
"author": "CAD bloke",
"author_id": 492,
"author_profile": "https://Stackoverflow.com/users/492",
"pm_score": 0,
"selected": false,
"text": "Process.Start() string filePath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + \".csv\";\n\nusing (var streamWriter = new StreamWriter(filePath))\nusing (CsvWriter csvWriter = new CsvWriter(streamWriter))\n{\n // optional header\n csvWriter.WriteRecord(new List<string>(){\"Heading1\", \"Heading2\", \"YouGetTheIdea\" });\n\n csvWriter.ValueSeparator = ',';\n foreach (var thing in YourListOfThings ?? new List<OfThings>())\n {\n if (thing != null)\n {\n List<string> csvLine = new List<string>\n {\n thing.Property1, thing.Property2, thing.YouGetTheIdea\n };\n\n csvWriter.WriteRecord(csvLine);\n }\n }\n}\n\nProcess.Start(filePath);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13477/"
] |
329,925 | <p>A program that I work on assumes that the UUID generated by the Windows RPC API call UuidCreateSequential() contains the MAC address of the primary ethernet adapter. Is this assumption correct or should I use a different method to get the MAC address?</p>
| [
{
"answer_id": 329979,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 2,
"selected": false,
"text": "NetworkInterface GetAllNetworkInterfaces() GetAdaptersInfo UuidCreateSequential"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19489/"
] |
329,931 | <p>I'm wondering if this is possible in SQL. Say you have two tables A and B, and you do a select on table A and join on table B:</p>
<pre><code>SELECT a.*, b.* FROM TABLE_A a JOIN TABLE_B b USING (some_id);
</code></pre>
<p>If table A has columns 'a_id', 'name', and 'some_id', and table B has 'b_id', 'name', and 'some_id', the query will return columns 'a_id', 'name', 'some_id', 'b_id', 'name', 'some_id'. Is there any way to prefix the column names of table B without listing every column individually? The equivalent of this:</p>
<pre><code>SELECT a.*, b.b_id as 'b.b_id', b.name as 'b.name', b.some_id as 'b.some_id'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
</code></pre>
<p>But, as mentioned, without listing every column, so something like:</p>
<pre><code>SELECT a.*, b.* as 'b.*'
FROM TABLE_A a JOIN TABLE_B b USING (some_id);
</code></pre>
<p>Basically something to say, "prefix every column returned by b.* with 'something'". Is this possible or am I out of luck?</p>
<h3>EDITS</h3>
<p>Advice on not using <code>SELECT *</code> and so on is valid advice but not relevant in my context, so please stick to the problem at hand -- is it possible to add a prefix (a constant specified in the SQL query) to all the column names of a table in a join?</p>
<p>My ultimate goal is to be able to do a <code>SELECT *</code> on two tables with a join, and be able to tell, from the names of the columns I get in my result set, which columns came from table A and which columns came from table B. Again, I don't want to have to list columns individually, I need to be able to do a <code>SELECT *</code>.</p>
| [
{
"answer_id": 329976,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "PRAGMA full_column_names PRAGMA short_column_names SELECT *"
},
{
"answer_id": 330076,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE [dbo].[stackoverflow_329931_a](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [col2] [nchar](10) NULL,\n [col3] [nchar](10) NULL,\n [col4] [nchar](10) NULL,\n CONSTRAINT [PK_stackoverflow_329931_a] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nCREATE TABLE [dbo].[stackoverflow_329931_b](\n [id] [int] IDENTITY(1,1) NOT NULL,\n [col2] [nchar](10) NULL,\n [col3] [nchar](10) NULL,\n [col4] [nchar](10) NULL,\n CONSTRAINT [PK_stackoverflow_329931_b] PRIMARY KEY CLUSTERED \n(\n [id] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nDECLARE @table1_name AS varchar(255)\nDECLARE @table1_prefix AS varchar(255)\nDECLARE @table2_name AS varchar(255)\nDECLARE @table2_prefix AS varchar(255)\nDECLARE @join_condition AS varchar(255)\nSET @table1_name = 'stackoverflow_329931_a'\nSET @table1_prefix = 'a_'\nSET @table2_name = 'stackoverflow_329931_b'\nSET @table2_prefix = 'b_'\nSET @join_condition = 'a.[id] = b.[id]'\n\nDECLARE @CRLF AS varchar(2)\nSET @CRLF = CHAR(13) + CHAR(10)\n\nDECLARE @a_columnlist AS varchar(MAX)\nDECLARE @b_columnlist AS varchar(MAX)\nDECLARE @sql AS varchar(MAX)\n\nSELECT @a_columnlist = COALESCE(@a_columnlist + @CRLF + ',', '') + 'a.[' + COLUMN_NAME + '] AS [' + @table1_prefix + COLUMN_NAME + ']'\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = @table1_name\nORDER BY ORDINAL_POSITION\n\nSELECT @b_columnlist = COALESCE(@b_columnlist + @CRLF + ',', '') + 'b.[' + COLUMN_NAME + '] AS [' + @table2_prefix + COLUMN_NAME + ']'\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = @table2_name\nORDER BY ORDINAL_POSITION\n\nSET @sql = 'SELECT ' + @a_columnlist + '\n,' + @b_columnlist + '\nFROM [' + @table1_name + '] AS a\nINNER JOIN [' + @table2_name + '] AS b\nON (' + @join_condition + ')'\n\nPRINT @sql\n-- EXEC (@sql)\n"
},
{
"answer_id": 2596380,
"author": "J Jorgenson",
"author_id": 310231,
"author_profile": "https://Stackoverflow.com/users/310231",
"pm_score": 1,
"selected": false,
"text": " SELECT a.*, b.*, c.* FROM table_a a JOIN table_b b USING (x) JOIN table_c c USING (y)\n char *name; /* Name of column (may be the alias) */\n char *org_name; /* Original column name, if an alias */\n char *table; /* Table of column if column was a field */\n char *org_table; /* Org table name, if table was an alias */\n char *db; /* Database for table */\n char *catalog; /* Catalog for table */\n char *def; /* Default value (set by mysql_list_fields) */\n unsigned long length; /* Width of column (create length) */\n unsigned long max_length; /* Max width for selected set */\n unsigned int name_length;\n unsigned int org_name_length;\n unsigned int table_length;\n unsigned int org_table_length;\n unsigned int db_length;\n unsigned int catalog_length;\n unsigned int def_length;\n unsigned int flags; /* Div flags */\n unsigned int decimals; /* Number of decimals in field */\n unsigned int charsetnr; /* Character set */\n enum enum_field_types type; /* Type of field. See mysql_com.h for types */\n"
},
{
"answer_id": 8929433,
"author": "Motin",
"author_id": 682317,
"author_profile": "https://Stackoverflow.com/users/682317",
"pm_score": 5,
"selected": false,
"text": "function prefixed_table_fields_wildcard($table, $alias)\n{\n global $wpdb;\n $columns = $wpdb->get_results(\"SHOW COLUMNS FROM $table\", ARRAY_A);\n\n $field_names = array();\n foreach ($columns as $column)\n {\n $field_names[] = $column[\"Field\"];\n }\n $prefixed = array();\n foreach ($field_names as $field_name)\n {\n $prefixed[] = \"`{$alias}`.`{$field_name}` AS `{$alias}.{$field_name}`\";\n }\n\n return implode(\", \", $prefixed);\n}\n\nfunction test_prefixed_table_fields_wildcard()\n{\n global $wpdb;\n\n $query = \"\n SELECT\n \" . prefixed_table_fields_wildcard($wpdb->posts, 'campaigns') . \",\n \" . prefixed_table_fields_wildcard($wpdb->posts, 'venues') . \"\n FROM $wpdb->posts AS campaigns\n LEFT JOIN $wpdb->postmeta meta1 ON (meta1.meta_key = 'venue' AND campaigns.ID = meta1.post_id)\n LEFT JOIN $wpdb->posts venues ON (venues.post_status = 'publish' AND venues.post_type = 'venue' AND venues.ID = meta1.meta_value)\n WHERE 1\n AND campaigns.post_status = 'publish'\n AND campaigns.post_type = 'campaign'\n LIMIT 1\n \";\n\n echo \"<pre>$query</pre>\";\n\n $posts = $wpdb->get_results($query, OBJECT);\n\n echo \"<pre>\";\n print_r($posts);\n echo \"</pre>\";\n}\n SELECT\n `campaigns`.`ID` AS `campaigns.ID`, `campaigns`.`post_author` AS `campaigns.post_author`, `campaigns`.`post_date` AS `campaigns.post_date`, `campaigns`.`post_date_gmt` AS `campaigns.post_date_gmt`, `campaigns`.`post_content` AS `campaigns.post_content`, `campaigns`.`post_title` AS `campaigns.post_title`, `campaigns`.`post_excerpt` AS `campaigns.post_excerpt`, `campaigns`.`post_status` AS `campaigns.post_status`, `campaigns`.`comment_status` AS `campaigns.comment_status`, `campaigns`.`ping_status` AS `campaigns.ping_status`, `campaigns`.`post_password` AS `campaigns.post_password`, `campaigns`.`post_name` AS `campaigns.post_name`, `campaigns`.`to_ping` AS `campaigns.to_ping`, `campaigns`.`pinged` AS `campaigns.pinged`, `campaigns`.`post_modified` AS `campaigns.post_modified`, `campaigns`.`post_modified_gmt` AS `campaigns.post_modified_gmt`, `campaigns`.`post_content_filtered` AS `campaigns.post_content_filtered`, `campaigns`.`post_parent` AS `campaigns.post_parent`, `campaigns`.`guid` AS `campaigns.guid`, `campaigns`.`menu_order` AS `campaigns.menu_order`, `campaigns`.`post_type` AS `campaigns.post_type`, `campaigns`.`post_mime_type` AS `campaigns.post_mime_type`, `campaigns`.`comment_count` AS `campaigns.comment_count`,\n `venues`.`ID` AS `venues.ID`, `venues`.`post_author` AS `venues.post_author`, `venues`.`post_date` AS `venues.post_date`, `venues`.`post_date_gmt` AS `venues.post_date_gmt`, `venues`.`post_content` AS `venues.post_content`, `venues`.`post_title` AS `venues.post_title`, `venues`.`post_excerpt` AS `venues.post_excerpt`, `venues`.`post_status` AS `venues.post_status`, `venues`.`comment_status` AS `venues.comment_status`, `venues`.`ping_status` AS `venues.ping_status`, `venues`.`post_password` AS `venues.post_password`, `venues`.`post_name` AS `venues.post_name`, `venues`.`to_ping` AS `venues.to_ping`, `venues`.`pinged` AS `venues.pinged`, `venues`.`post_modified` AS `venues.post_modified`, `venues`.`post_modified_gmt` AS `venues.post_modified_gmt`, `venues`.`post_content_filtered` AS `venues.post_content_filtered`, `venues`.`post_parent` AS `venues.post_parent`, `venues`.`guid` AS `venues.guid`, `venues`.`menu_order` AS `venues.menu_order`, `venues`.`post_type` AS `venues.post_type`, `venues`.`post_mime_type` AS `venues.post_mime_type`, `venues`.`comment_count` AS `venues.comment_count`\n FROM wp_posts AS campaigns\nLEFT JOIN wp_postmeta meta1 ON (meta1.meta_key = 'venue' AND campaigns.ID = meta1.post_id)\nLEFT JOIN wp_posts venues ON (venues.post_status = 'publish' AND venues.post_type = 'venue' AND venues.ID = meta1.meta_value)\nWHERE 1\nAND campaigns.post_status = 'publish'\nAND campaigns.post_type = 'campaign'\nLIMIT 1\n\nArray\n(\n [0] => stdClass Object\n (\n [campaigns.ID] => 33\n [campaigns.post_author] => 2\n [campaigns.post_date] => 2012-01-16 19:19:10\n [campaigns.post_date_gmt] => 2012-01-16 19:19:10\n [campaigns.post_content] => Lorem ipsum\n [campaigns.post_title] => Lorem ipsum\n [campaigns.post_excerpt] => \n [campaigns.post_status] => publish\n [campaigns.comment_status] => closed\n [campaigns.ping_status] => closed\n [campaigns.post_password] => \n [campaigns.post_name] => lorem-ipsum\n [campaigns.to_ping] => \n [campaigns.pinged] => \n [campaigns.post_modified] => 2012-01-16 21:01:55\n [campaigns.post_modified_gmt] => 2012-01-16 21:01:55\n [campaigns.post_content_filtered] => \n [campaigns.post_parent] => 0\n [campaigns.guid] => http://example.com/?p=33\n [campaigns.menu_order] => 0\n [campaigns.post_type] => campaign\n [campaigns.post_mime_type] => \n [campaigns.comment_count] => 0\n [venues.ID] => 84\n [venues.post_author] => 2\n [venues.post_date] => 2012-01-16 20:12:05\n [venues.post_date_gmt] => 2012-01-16 20:12:05\n [venues.post_content] => Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n [venues.post_title] => Lorem ipsum venue\n [venues.post_excerpt] => \n [venues.post_status] => publish\n [venues.comment_status] => closed\n [venues.ping_status] => closed\n [venues.post_password] => \n [venues.post_name] => lorem-ipsum-venue\n [venues.to_ping] => \n [venues.pinged] => \n [venues.post_modified] => 2012-01-16 20:53:37\n [venues.post_modified_gmt] => 2012-01-16 20:53:37\n [venues.post_content_filtered] => \n [venues.post_parent] => 0\n [venues.guid] => http://example.com/?p=84\n [venues.menu_order] => 0\n [venues.post_type] => venue\n [venues.post_mime_type] => \n [venues.comment_count] => 0\n )\n)\n"
},
{
"answer_id": 9926134,
"author": "Wayne Bryan",
"author_id": 1300878,
"author_profile": "https://Stackoverflow.com/users/1300878",
"pm_score": 7,
"selected": false,
"text": "SELECT '' as table1_dummy, table1.*, '' as table2_dummy, table2.*, '' as table3_dummy, table3.* FROM table1\nJOIN table2 ON table2.table1id = table1.id\nJOIN table3 ON table3.table1id = table1.id\n"
},
{
"answer_id": 15563404,
"author": "axelbrz",
"author_id": 1112654,
"author_profile": "https://Stackoverflow.com/users/1112654",
"pm_score": 2,
"selected": false,
"text": "mysql_field_table() mysql_field_name() mysql_num_fields() function mysql_rows_with_columns($query) {\n $result = mysql_query($query);\n if (!$result) return false; // mysql_error() could be used outside\n $fields = mysql_num_fields($result);\n $rows = array();\n while ($row = mysql_fetch_row($result)) { \n $newRow = array();\n for ($i=0; $i<$fields; $i++) {\n $table = mysql_field_table($result, $i);\n $name = mysql_field_name($result, $i);\n $newRow[$table . \".\" . $name] = $row[$i];\n }\n $rows[] = $newRow;\n }\n mysql_free_result($result);\n return $rows;\n}\n"
},
{
"answer_id": 26499983,
"author": "Lenik",
"author_id": 217071,
"author_profile": "https://Stackoverflow.com/users/217071",
"pm_score": 3,
"selected": false,
"text": "-- Create alias-view for specific table.\n\ncreate or replace function mkaview(schema varchar, tab varchar, prefix varchar)\n returns table(orig varchar, alias varchar) as $$\ndeclare\n qtab varchar;\n qview varchar;\n qcol varchar;\n qacol varchar;\n v record;\n sql varchar;\n len int;\nbegin\n qtab := '\"' || schema || '\".\"' || tab || '\"';\n qview := '\"' || schema || '\".\"av' || prefix || tab || '\"';\n sql := 'create view ' || qview || ' as select';\n\n for v in select * from information_schema.columns\n where table_schema = schema and table_name = tab\n loop\n qcol := '\"' || v.column_name || '\"';\n qacol := '\"' || prefix || v.column_name || '\"';\n\n sql := sql || ' ' || qcol || ' as ' || qacol;\n sql := sql || ', ';\n\n return query select qcol::varchar, qacol::varchar;\n end loop;\n\n len := length(sql);\n sql := left(sql, len - 2); -- trim the trailing ', '.\n sql := sql || ' from ' || qtab;\n\n raise info 'Execute SQL: %', sql;\n execute sql;\nend\n$$ language plpgsql;\n -- This will create a view \"avp_person\" with \"p_\" prefix to all column names.\nselect * from mkaview('public', 'person', 'p_');\n\nselect * from avp_person;\n"
},
{
"answer_id": 32485445,
"author": "Antonio",
"author_id": 2436175,
"author_profile": "https://Stackoverflow.com/users/2436175",
"pm_score": 1,
"selected": false,
"text": "AS DECLARE @asStatements varchar(8000)\n\nSELECT @asStatements = ISNULL(@asStatements + ', ','') + QUOTENAME(table_name) + '.' + QUOTENAME(column_name) + ' AS ' + '[' + table_name + '.' + column_name + ']'\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME = 'TABLE_A' OR TABLE_NAME = 'TABLE_B'\nORDER BY ORDINAL_POSITION\n EXEC('SELECT ' + @asStatements + ' FROM TABLE_A a JOIN TABLE_B b USING (some_id)');\n"
},
{
"answer_id": 46240921,
"author": "Sam",
"author_id": 8615036,
"author_profile": "https://Stackoverflow.com/users/8615036",
"pm_score": 2,
"selected": false,
"text": "SELECT a.*, b.* FROM TABLE_A a JOIN TABLE_B b USING (some_id);\n"
},
{
"answer_id": 49398335,
"author": "Blair",
"author_id": 169164,
"author_profile": "https://Stackoverflow.com/users/169164",
"pm_score": 2,
"selected": false,
"text": "const schema = { columns: ['id','another_column','yet_another_column'] }\n const prefix = (table, columns) => columns.reduce((previous, column) => {\n previous.push(table + '.' + column + ' AS ' + table + '_' + column);\n return previous;\n}, []);\n const columns_joined = [...prefix('tab1',schema.columns), ...prefix('tab2',schema.columns)];\n console.log('SELECT ' + columns_joined.join(',') + ' FROM tab1, tab2 WHERE tab1.id = tab2.id');\n"
},
{
"answer_id": 50995317,
"author": "JasonWoof",
"author_id": 168405,
"author_profile": "https://Stackoverflow.com/users/168405",
"pm_score": 1,
"selected": false,
"text": "function mysqli_rows_with_columns($link, $query) {\n $result = mysqli_query($link, $query);\n if (!$result) {\n return mysqli_error($link);\n }\n $field_count = mysqli_num_fields($result);\n $fields = array();\n for ($i = 0; $i < $field_count; $i++) {\n $field = mysqli_fetch_field_direct($result, $i);\n $fields[] = $field->table . '.' . $field->name; # changed by AS\n #$fields[] = $field->orgtable . '.' . $field->orgname; # actual table/field names\n }\n $rows = array();\n while ($row = mysqli_fetch_row($result)) {\n $new_row = array();\n for ($i = 0; $i < $field_count; $i++) {\n $new_row[$fields[$i]] = $row[$i];\n }\n $rows[] = $new_row;\n }\n mysqli_free_result($result);\n return $rows;\n}\n\n$link = mysqli_connect('localhost', 'fixme', 'fixme', 'fixme');\nprint_r(mysqli_rows_with_columns($link, 'select foo.*, bar.* from foo, bar'));\n"
},
{
"answer_id": 53109381,
"author": "Carl G",
"author_id": 39396,
"author_profile": "https://Stackoverflow.com/users/39396",
"pm_score": 1,
"selected": false,
"text": "select \n s.*\n , '' as _prefix__creator_\n , u.*\n , '' as _prefix__speaker_\n , p.*\nfrom statements s \n left join users u on s.creator_user_id = u.user_id\n left join persons p on s.speaker_person_id = p.person_id\n addPrefixes(row) fields rows const PREFIX_INDICATOR = '_prefix__'\nconst STOP_PREFIX_INDICATOR = '_stop_prefix'\n\n/** Adds a <prefix> to all properties that follow a property with the name: PREFIX_INDICATOR<prefix> */\nfunction addPrefixes(fields, row) {\n let prefix = null\n for (const field of fields) {\n const key = field.name\n if (key.startsWith(PREFIX_INDICATOR)) {\n if (row[key] !== '') {\n throw new Error(`PREFIX_INDICATOR ${PREFIX_INDICATOR} must not appear with a value, but had value: ${row[key]}`)\n }\n prefix = key.substr(PREFIX_INDICATOR.length)\n delete row[key]\n } else if (key === STOP_PREFIX_INDICATOR) {\n if (row[key] !== '') {\n throw new Error(`STOP_PREFIX_INDICATOR ${STOP_PREFIX_INDICATOR} must not appear with a value, but had value: ${row[key]}`)\n }\n prefix = null\n delete row[key]\n } else if (prefix) {\n const prefixedKey = prefix + key\n row[prefixedKey] = row[key]\n delete row[key]\n }\n }\n return row\n}\n const {\n addPrefixes,\n PREFIX_INDICATOR,\n STOP_PREFIX_INDICATOR,\n} = require('./BaseDao')\n\ndescribe('addPrefixes', () => {\n test('adds prefixes', () => {\n const fields = [\n {name: 'id'},\n {name: PREFIX_INDICATOR + 'my_prefix_'},\n {name: 'foo'},\n {name: STOP_PREFIX_INDICATOR},\n {name: 'baz'},\n ]\n const row = {\n id: 1,\n [PREFIX_INDICATOR + 'my_prefix_']: '',\n foo: 'bar',\n [STOP_PREFIX_INDICATOR]: '',\n baz: 'spaz'\n }\n const expected = {\n id: 1,\n my_prefix_foo: 'bar',\n baz: 'spaz',\n }\n expect(addPrefixes(fields, row)).toEqual(expected)\n })\n})\n"
},
{
"answer_id": 59829025,
"author": "Joe Love",
"author_id": 2283954,
"author_profile": "https://Stackoverflow.com/users/2283954",
"pm_score": 3,
"selected": false,
"text": "select row_to_json(tab1.*) AS tab1_json, row_to_json(tab2.*) AS tab2_json \n from tab1\n join tab2 on tab2.t1id=tab1.id\n"
},
{
"answer_id": 66795592,
"author": "Necips",
"author_id": 6999750,
"author_profile": "https://Stackoverflow.com/users/6999750",
"pm_score": 1,
"selected": false,
"text": "select\n name + ' as prefix.' + name + ','\nfrom sys.columns where object_id = object_id('mytable')\norder by column_id\n"
},
{
"answer_id": 69509061,
"author": "muratgozel",
"author_id": 695796,
"author_profile": "https://Stackoverflow.com/users/695796",
"pm_score": 2,
"selected": false,
"text": "to_jsonb select\n TABLE_A.*,\n to_jsonb(TABLE_B.*) as b,\n to_jsonb(TABLE_C.*) as c\nfrom TABLE_A\nleft join TABLE_B on TABLE_B.a_id=TABLE_A.id\nleft join TABLE_C on TABLE_C.a_id=TABLE_A.id\nwhere TABLE_A.id=1\n"
},
{
"answer_id": 71693424,
"author": "PetitCitron",
"author_id": 5490142,
"author_profile": "https://Stackoverflow.com/users/5490142",
"pm_score": 0,
"selected": false,
"text": "src/Controller/Component/MyUtilsComponent.php <?php\n\nnamespace App\\Controller\\Component;\n\nuse Cake\\Controller\\Component;\nuse Cake\\Datasource\\ConnectionManager;\n\nclass MyUtilsComponent extends Component\n{\n public static function prefixedTableFieldsWildcard(string $table, string $alias, string $connexion = 'default'): string\n {\n $c = ConnectionManager::get($connexion);\n $columns = $c->execute(\"SHOW COLUMNS FROM $table\");\n $field_names = [];\n foreach ($columns as $column) {\n $field_names[] = $column['Field'];\n }\n\n $prefixed = [];\n foreach ($field_names as $field_name) {\n $prefixed[] = \"`{$alias}`.`{$field_name}` AS `{$alias}.{$field_name}`\";\n }\n return implode(', ', $prefixed);\n }\n}\n function testPrefixedTableFieldsWildcard(): void\n {\n $fields = MyUtilsComponent::prefixedTableFieldsWildcard('metas', 'u', 'test');\n $this->assertEquals('`u`.`id` AS `u.id`, `u`.`meta_key` AS `u.meta_key`, `u`.`meta_value` AS `u.meta_value`, `u`.`meta_default` AS `u.meta_default`, `u`.`meta_desc` AS `u.meta_desc`', $fields,);\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26353/"
] |
329,950 | <p>Is there a reason why zero is used as a "default" function return value? I noticed that several functions from the stdlib and almost everywhere else, when not returning a proper number (e.g pow(), strcpy()) or an error (negative numbers), simply return zero.</p>
<p>I just became curious after seeing several tests performed with negated logic. Very confusing.</p>
<p>Why not return 1, or 0xff, or any positive number for that matter?</p>
| [
{
"answer_id": 329966,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "// Perfectly good K&R C code.\nNoReturn()\n{\n // do stuff;\n return;\n}\n\nint unknownValue = NoReturn();\n"
},
{
"answer_id": 330096,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "open() errno errno errno stat() signal() getpid() getuid()"
},
{
"answer_id": 330205,
"author": "joveha",
"author_id": 40668,
"author_profile": "https://Stackoverflow.com/users/40668",
"pm_score": 0,
"selected": false,
"text": "if ( somefunc() ) {\n // handle error\n}\n if ( !somefunc() ) {\n // handle error\n}\n if ( somefunc() == somevalue ) {\n // handle error \n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42040/"
] |
329,956 | <p>First, context: I'm trying to create a command-line-based tool (Linux) that
requires login. Accounts on this tool have nothing to do with
system-level accounts -- none of this looks at /etc/passwd.</p>
<p>I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd.</p>
<p>Despite not using the system-level password files, using crypt seemed
to be a good practice to use, as opposed to storing passwords in
cleartext. (While crypt is certainly better than storing passwords in
cleartext, I'm open to other ways of doing this.)</p>
<p>My crypt knowledge is based on this:
<a href="https://docs.python.org/2/library/crypt.html" rel="nofollow noreferrer">https://docs.python.org/2/library/crypt.html</a></p>
<p>The documentation seems to ask for something that isn't possible: "it
is recommended to use the full crypted password as salt when checking
for a password."</p>
<p>Huh? If I'm creating the crypted password (as in, when creating a user
record) how can I use the crypted password as a salt? It
doesn't exist yet. (I'm assuming that you must use the same salt for creating and checking a password.)</p>
<p>I've tried using the plaintext password as a salt. This does
work, but has two problems; one easily overcome, and one serious:</p>
<p>1) The first two letters of the plaintext password are included in the
crypted password. You can fix this by not writing the first two
characters to the file:</p>
<pre><code>user_record = '%s:%s:%s' % (user_name, crypted_pw[2:], user_type)
</code></pre>
<p>2) By using the plaintext password as the salt, you would seem to be
reducing the amount of entropy in the system. Possibly I'm
misunderstanding the purpose of the salt.</p>
<p>The best practice I've been able to derive is to use the first two
characters from the username as the salt. Would this be appropriate,
or is there something I've missed that makes that a bad move?</p>
<p>My understanding of a salt is that it prevents pre-computing password
hashes from a dictionary. I could use a standard salt for all
passwords (such as my initials, "JS,") but that seems to be less of a
burden for an attacker than using two characters from each user's username.</p>
| [
{
"answer_id": 330000,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 3,
"selected": true,
"text": "string_to_hash = user.stored_salt + entered_password\nsuccessful_login = (sha1(string_to_hash) == user.stored_password_hash)\n"
},
{
"answer_id": 330039,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 3,
"selected": false,
"text": ">>> crypt.crypt(\"Hello\", \"World\")\n'Wo5pEi/H5/mxU'\n>>> crypt.crypt(\"Hello\", \"ABCDE\")\n'AB/uOsC7P93EI'\n"
},
{
"answer_id": 331283,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 2,
"selected": false,
"text": "$1$ABCDEFGH$\n >>> p = crypt.crypt('password', '$1$s8Ty3/f$')\n>>> p\nOut: '$1$s8Ty3/f$0H/M0JswK9pl3X/e.n55G1'\n>>> p == crypt.crypt('password', p)\nOut: True\n"
},
{
"answer_id": 347070,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": -1,
"selected": false,
"text": "crypt.crypt()"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19207/"
] |
329,957 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa">c# - How do I round a decimal value to 2 decimal places (for output on a page)</a> </p>
</blockquote>
<p>I want to truncate the decimals like below</p>
<p>i.e.</p>
<ul>
<li>2.22939393 -> 2.229</li>
<li>2.22977777 -> 2.229</li>
</ul>
| [
{
"answer_id": 329982,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 6,
"selected": false,
"text": "decimal rounded = Math.Round(2.22939393, 3); //Returns 2.229\n string roundedNumber = number.ToString(\"N3\");\n Math.Truncate(2.22977777 * 1000) / 1000; //Returns 2.229\n"
},
{
"answer_id": 330005,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 5,
"selected": true,
"text": "double d = 2.22977777;\nd = ( (double) ( (int) (d * 1000.0) ) ) / 1000.0 ;\n"
},
{
"answer_id": 330325,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 0,
"selected": false,
"text": "double num = 3.12345;\nnum.ToString(\"G3\");\n"
},
{
"answer_id": 330362,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": -1,
"selected": false,
"text": "decimal original = GetSomeDecimal(); // 22222.22939393\nint number1 = (int)original; // contains only integer value of origina number\ndecimal temporary = original - number1; // contains only decimal value of original number\nint decimalPlaces = GetDecimalPlaces(); // 3\ntemporary *= (Math.Pow(10, decimalPlaces)); // moves some decimal places to integer\ntemporary = (int)temporary; // removes all decimal places\ntemporary /= (Math.Pow(10, decimalPlaces)); // moves integer back to decimal places\ndecimal result = original + temporary; // add integer and decimal places together\n decimal original = GetSomeDecimal(); // 22222.22939393\nint decimalPlaces = GetDecimalPlaces(); // 3\ndecimal result = ((int)original) + (((int)(original * Math.Pow(10, decimalPlaces)) / (Math.Pow(10, decimalPlaces));\n"
},
{
"answer_id": 2109913,
"author": "magicrebirth",
"author_id": 109304,
"author_profile": "https://Stackoverflow.com/users/109304",
"pm_score": 0,
"selected": false,
"text": ">>> float(\"%.1f\" % 1.00001)\n1.0\n>>> float(\"%.3f\" % 1.23001)\n1.23\n>>> float(\"%.5f\" % 1.23001)\n1.23001\n"
},
{
"answer_id": 2271032,
"author": "user274105",
"author_id": 274105,
"author_profile": "https://Stackoverflow.com/users/274105",
"pm_score": -1,
"selected": false,
"text": "double num = 2.22939393;\nnum = Convert.ToDouble(num.ToString(\"#0.000\"));\n"
},
{
"answer_id": 3309210,
"author": "Carl Hörberg",
"author_id": 80589,
"author_profile": "https://Stackoverflow.com/users/80589",
"pm_score": 3,
"selected": false,
"text": "public decimal Truncate(decimal number, int digits)\n{\n decimal stepper = (decimal)(Math.Pow(10.0, (double)digits));\n int temp = (int)(stepper * number);\n return (decimal)temp / stepper;\n}\n"
},
{
"answer_id": 6918261,
"author": "Glenn Slayden",
"author_id": 147511,
"author_profile": "https://Stackoverflow.com/users/147511",
"pm_score": 3,
"selected": false,
"text": "static double[] pow10 = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10 };\npublic static double Truncate(this double x, int precision)\n{\n if (precision < 0)\n throw new ArgumentException();\n if (precision == 0)\n return Math.Truncate(x);\n double m = precision >= pow10.Length ? Math.Pow(10, precision) : pow10[precision];\n return Math.Truncate(x * m) / m;\n}\n"
},
{
"answer_id": 7555622,
"author": "Pavlo Neiman",
"author_id": 164001,
"author_profile": "https://Stackoverflow.com/users/164001",
"pm_score": 0,
"selected": false,
"text": "double d = 2.22912312515;\nint demention = 3;\ndouble truncate = Math.Truncate(d) + Math.Truncate((d - Math.Truncate(d)) * Math.Pow(10.0, demention)) / Math.Pow(10.0, demention);\n"
},
{
"answer_id": 9235471,
"author": "Jim",
"author_id": 1203049,
"author_profile": "https://Stackoverflow.com/users/1203049",
"pm_score": 2,
"selected": false,
"text": "Private Function TruncateToDecimalPlace(byval ToTruncate as decimal, byval DecimalPlaces as integer) as double \ndim power as decimal = Math.Pow(10, decimalplaces)\nreturn math.truncate(totruncate * power) / power\nend function\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329957",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/709/"
] |
329,962 | <p>I wrote a program out, which was all in one file, and the methods were forward declared in a header. The program initially worked perfectly when it was in one file. But when I separated the program, I kept getting random occurrences for the destructor of one of the classes which was declared in the header file. </p>
<p>I have a static variable in my header to count the number of objects of a particular class. Whenever I construct the object I increment this variable. Then in my destructor I subtract 1 from that variable, check if it's 0 (meaning it's the last object) and do something. The value seems to be off sometimes, I'm not sure why. I do have random calls in my application but I don't see why that would effect what I have described above, thanks. Any help or insight is appreciated!</p>
<p>[Update]: have a base class, which contains the destructor.. which is implemented in the header, then I have two derived classes, which in their constructor increment the static var.. so what can I do? </p>
<p>What I am trying to do is the following: In my header I have this:</p>
<pre><code>class A {
public:
virtual ~A() {
count --;
if (count == 0) { /* this is the last one, do something */ }
}
class B : public A {
public:
B();
}
</code></pre>
<p>Then in Class B I have</p>
<pre><code>B::B() {
count++;
}
</code></pre>
<p>Where can I define count so I don't get misleading counts? Thanks.</p>
| [
{
"answer_id": 329997,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": 1,
"selected": false,
"text": "int MyClass::static_var;\n"
},
{
"answer_id": 330048,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": true,
"text": "class A {\npublic:\n virtual ~A() {\n count --;\n if (count == 0) { // this is the last one, do something }\n }\nprotected:\n static int count;\n};\n\nclass B : public A{\npublic:\nB();\n};\n int A::count(0);\n"
},
{
"answer_id": 330057,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 3,
"selected": false,
"text": " class A\n {\n static int count;\n\n public:\n A() // Default constructor.\n {\n ++count;\n }\n A(A const& copy) // Copy constructor/\n { // Note If you do not define it the compiler\n ++count; // will automatically do it for you\n }\n virtual ~A()\n {\n --count;\n if (count == 0)\n { // PLOP\n }\n }\n // A& operator=(A const& copy)\n // do not need to override this as object has\n // already been created and accounted for.\n};\n int A::count = 0;\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33481/"
] |
329,963 | <p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
| [
{
"answer_id": 337114,
"author": "vvarp",
"author_id": 42786,
"author_profile": "https://Stackoverflow.com/users/42786",
"pm_score": 4,
"selected": false,
"text": "$(document).ready(function() {\n $(\"textarea\").each(function(n, obj) {\n fck = new FCKeditor(obj.id) ;\n fck.BasePath = \"/admin-media/fckeditor/\" ;\n fck.ReplaceTextarea() ;\n });\n});\n"
},
{
"answer_id": 346257,
"author": "zgoda",
"author_id": 12138,
"author_profile": "https://Stackoverflow.com/users/12138",
"pm_score": 4,
"selected": false,
"text": "class ArticleAdminModelForm(forms.ModelForm):\n description = forms.CharField(widget=widgets.AdminWYMEditor)\n\n class Meta:\n model = models.Article\n forms.Textarea"
},
{
"answer_id": 7762362,
"author": "user994610",
"author_id": 994610,
"author_profile": "https://Stackoverflow.com/users/994610",
"pm_score": 2,
"selected": false,
"text": "class KindEditor(forms.Textarea):\n class Media:\n css ={\n 'all':(settings.STATIC_ROOT + 'editor/themes/default/default.css',)\n }\n js = (settings.STATIC_ROOT + 'editor/kindeditor-min.js',settings.STATIC_ROOT + 'editor/lang/zh_CN.js',)\n def __init__(self):\n attrs = {}\n attrs['rel'] = 'kind'\n super(KindEditor, self).__init__(attrs)\n\n\nclass NewsAdminForm(forms.ModelForm):\n pass\n\n class Meta:\n model = News\n widgets = {\n 'body':KindEditor()\n }\n\nclass NewsAdmin(admin.ModelAdmin):\n form = NewsAdminForm\n\n\nadmin.site.register(News, NewsAdmin)\n"
},
{
"answer_id": 71187484,
"author": "Praveen Kumar",
"author_id": 7320048,
"author_profile": "https://Stackoverflow.com/users/7320048",
"pm_score": 1,
"selected": false,
"text": "pip install django-ckeditor\n python manage.py makemigrations\npython manage.py migrate\npython manage.py collectstatic\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41736/"
] |
329,977 | <p>When creating a string using the following notation:</p>
<pre><code>NSString *foo = @"Bar";
</code></pre>
<p>Does one need to release <code>foo</code>? Or is <code>foo</code> autoreleased in this case?</p>
| [
{
"answer_id": 4469722,
"author": "Madhup Singh Yadav",
"author_id": 165260,
"author_profile": "https://Stackoverflow.com/users/165260",
"pm_score": 3,
"selected": false,
"text": "alloc retain release autorelease NSString *str = [NSString string];\n NSString *str = [[[NSString alloc] init] autorelease];\n release autorelease"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40882/"
] |
329,986 | <p>I developed a greasemonkey script that refreshes a page and checks for certain updates. I would like to run this script in a tab and browse the internet in another tab, but then have the script automatically activate it's tab when an update is found.</p>
<p>Im not sure how clear that was, maybe this is better:</p>
<p>Tab 1 is running a greasemonkey script, refreshing every x seconds looking for the word "foo"</p>
<p>Tab 2 is browsing stackoverflow</p>
<p>-- Now on a refresh, the GM script finds the word "foo". This is when I want the tab focus to automatically shift from Tab 2 to Tab 1.</p>
<p>Is this possible, and if so, how do I achieve this?</p>
<p>Thanks.</p>
| [
{
"answer_id": 330227,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 3,
"selected": true,
"text": "alert() alert('found foo')"
},
{
"answer_id": 5214463,
"author": "erikvold",
"author_id": 219166,
"author_profile": "https://Stackoverflow.com/users/219166",
"pm_score": 1,
"selected": false,
"text": "GM_openInTab GM_openInTab(window.location.href, true);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29595/"
] |
329,993 | <p>As of right now I believe only Firefox support <code>-moz-border-radius</code> property. I am surprised that twitter uses it.</p>
<p>Are any other browsers planning on supporting this or does CSS3 have something like this in the works?</p>
<p><strong>Edit:</strong> I also found <a href="http://www.css3.info/preview/rounded-border/" rel="nofollow noreferrer">-webkit-border-top-left-radius</a> and then the <a href="http://www.w3.org/TR/2002/WD-css3-border-20021107/#border-radius" rel="nofollow noreferrer">CSS3 version</a></p>
<p>So when is CSS3 coming out?</p>
| [
{
"answer_id": 330015,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "border-radius -moz-border-radius -webkit-border-radius border-radius -moz-border-radius -webkit-border-radius"
},
{
"answer_id": 330913,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 1,
"selected": false,
"text": "-moz -webkit border-radius"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/329993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27570/"
] |
330,004 | <p>What causes the publish error:
"fl.getDocumentDOM() has no properties" ?</p>
<p>The error occurs only when using the "Test Project" button in the project pane. It doesn't cause the publish to fail, it's just annoying.</p>
| [
{
"answer_id": 330015,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": false,
"text": "border-radius -moz-border-radius -webkit-border-radius border-radius -moz-border-radius -webkit-border-radius"
},
{
"answer_id": 330913,
"author": "Paul D. Waite",
"author_id": 20578,
"author_profile": "https://Stackoverflow.com/users/20578",
"pm_score": 1,
"selected": false,
"text": "-moz -webkit border-radius"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26331/"
] |
330,010 | <p>I'm trying to display a caret (<code>^</code>) in math mode in LaTeX to represent the exclusive or operation implemented in the "C languages". By default, <code>^</code> is for creating a superscript in math mode. The closest I can seem to get is by using <code>\wedge</code>, which isn't the same.</p>
| [
{
"answer_id": 330019,
"author": "genehack",
"author_id": 39933,
"author_profile": "https://Stackoverflow.com/users/39933",
"pm_score": 3,
"selected": false,
"text": "\\^{}\n \\verb|^|\n"
},
{
"answer_id": 330033,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "$7 \\^{ } 3 = 4$\n"
},
{
"answer_id": 330042,
"author": "Karl",
"author_id": 36093,
"author_profile": "https://Stackoverflow.com/users/36093",
"pm_score": 2,
"selected": false,
"text": "\\^ \\^{4} 4 $7 \\^{} 3 = 4$ 73 7 3 \\hspace{1.5} \\^{} \\hspace{1.5} \n \\verb|^|"
},
{
"answer_id": 330071,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 5,
"selected": true,
"text": "\\newcommand\\XOR{\\oplus} \\newcommand\\XOR{\\mathbin{\\char`\\^}}\n$x \\XOR y$\n \\mathbin \\char"
},
{
"answer_id": 1594882,
"author": "Dayo Adetoye",
"author_id": 193145,
"author_profile": "https://Stackoverflow.com/users/193145",
"pm_score": 2,
"selected": false,
"text": "\\textasciicircum $\\mbox{\\textasciicircum}$"
},
{
"answer_id": 7481731,
"author": "txemagon",
"author_id": 954244,
"author_profile": "https://Stackoverflow.com/users/954244",
"pm_score": 4,
"selected": false,
"text": "$ ^\\wedge $\n"
},
{
"answer_id": 9332125,
"author": "solveeid",
"author_id": 1216738,
"author_profile": "https://Stackoverflow.com/users/1216738",
"pm_score": 2,
"selected": false,
"text": "$2\\hat{\\text{ }}3$\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/488/"
] |
330,027 | <p>I recently got a Dell XPS 64-bit Vista for myself. Eclipse doesn't have their 64-bit version, but I've read on forums that they download Eclipse and work with Java 1.5 on the Vista with only some problems. I have Java 1.6 and Netbeans was easily downloadable.</p>
<p>What's the basic/big difference that I'll notice if I shift to Netbeans from Eclipse now?</p>
| [
{
"answer_id": 334609,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 5,
"selected": false,
"text": "<sarcasm> </sarcasm>"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,030 | <p>I have an object, and I want to list all the selectors to which it responds. It feels like this should be perfectly possible, but I'm having trouble finding the APIs.</p>
| [
{
"answer_id": 330084,
"author": "Rob",
"author_id": 386102,
"author_profile": "https://Stackoverflow.com/users/386102",
"pm_score": 0,
"selected": false,
"text": "-(BOOL) respondsToSelector:(SEL)aSelector {\n printf(\"Selector: %s\\n\", [NSStringFromSelector(aSelector) UTF8String]);\n return [super respondsToSelector:aSelector];\n}\n UIViewController <UITableViewDelegate, UITableViewDataSource> Selector: tableView:numberOfRowsInSection:\nSelector: tableView:cellForRowAtIndexPath:\nSelector: numberOfSectionsInTableView:\nSelector: tableView:titleForHeaderInSection:\nSelector: tableView:titleForFooterInSection:\nSelector: tableView:commitEditingStyle:forRowAtIndexPath:\nSelector: sectionIndexTitlesForTableView:\nSelector: tableView:sectionForSectionIndexTitle:atIndex:\n...\n...\netc.,etc.\n"
},
{
"answer_id": 330124,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 7,
"selected": true,
"text": "#import <objc/runtime.h>\n SomeClass * t = [[SomeClass alloc] init];\n\nint i=0;\nunsigned int mc = 0;\nMethod * mlist = class_copyMethodList(object_getClass(t), &mc);\nNSLog(@\"%d methods\", mc);\nfor(i=0;i<mc;i++)\n NSLog(@\"Method no #%d: %s\", i, sel_getName(method_getName(mlist[i])));\n\n/* note mlist needs to be freed */\n"
},
{
"answer_id": 19807414,
"author": "José Manuel Sánchez",
"author_id": 1156575,
"author_profile": "https://Stackoverflow.com/users/1156575",
"pm_score": 5,
"selected": false,
"text": "p int $num = 0;\nexpr Method *$m = (Method *)class_copyMethodList((Class)object_getClass(t), &$num);\nexpr for(int i=0;i<$num;i++) { (void)NSLog(@\"%s\",(char *)sel_getName((SEL)method_getName($m[i]))); }\n"
},
{
"answer_id": 35305698,
"author": "JAL",
"author_id": 2415822,
"author_profile": "https://Stackoverflow.com/users/2415822",
"pm_score": 3,
"selected": false,
"text": "let obj = NSObject()\n\nvar mc: UInt32 = 0\nlet mcPointer = withUnsafeMutablePointer(&mc, { $0 })\nlet mlist = class_copyMethodList(object_getClass(obj), mcPointer)\n\nprint(\"\\(mc) methods\")\n\nfor i in 0...Int(mc) {\n print(String(format: \"Method #%d: %s\", arguments: [i, sel_getName(method_getName(mlist[i]))]))\n}\n 251 methods\nMethod #0: hashValue\nMethod #1: postNotificationWithDescription:\nMethod #2: okToNotifyFromThisThread\nMethod #3: fromNotifySafeThreadPerformSelector:withObject:\nMethod #4: allowSafePerformSelector\nMethod #5: disallowSafePerformSelector\n...\nMethod #247: isProxy\nMethod #248: isMemberOfClass:\nMethod #249: superclass\nMethod #250: isFault\nMethod #251: <null selector>\n"
},
{
"answer_id": 43990109,
"author": "DeFrenZ",
"author_id": 1288097,
"author_profile": "https://Stackoverflow.com/users/1288097",
"pm_score": 2,
"selected": false,
"text": "extension NSObject {\n var __methods: [Selector] {\n var methodCount: UInt32 = 0\n guard\n let methodList = class_copyMethodList(type(of: self), &methodCount),\n methodCount != 0\n else { return [] }\n return (0 ..< Int(methodCount))\n .flatMap({ method_getName(methodList[$0]) })\n }\n}\n"
},
{
"answer_id": 55406047,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 1,
"selected": false,
"text": "SomeClass *someClass = [[SomeClass alloc] init]; \n\n//List of all methods\nunsigned int amountMethod = 0;\nMethod *methods = class_copyMethodList(someClass, &amountMethod);\n\nfor (unsigned int i = 0; i < amountMethod; i++) {\n Method method = methods[i];\n\n printf(\"\\t method named:'%s' \\n\", sel_getName(method_getName(method)));\n}\n\nfree(methods);\n"
},
{
"answer_id": 70573417,
"author": "Sherwin Zadeh",
"author_id": 1146712,
"author_profile": "https://Stackoverflow.com/users/1146712",
"pm_score": 0,
"selected": false,
"text": " Class c = [myObject class];\n while (c != nil) {\n int i = 0;\n unsigned int mc = 0;\n Method* mlist = class_copyMethodList(c, &mc);\n NSLog(@\"%d methods for %@\", mc, c);\n for(i = 0; i < mc; i++) {\n const char* selName = sel_getName(method_getName(mlist[i]));\n NSLog(@\"Method #%d: %s\", i, selName);\n }\n free(mlist);\n c = [c superclass];\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18017/"
] |
330,032 | <p>I've seen some methods of <a href="http://www.anastasiosyal.com/archive/2007/04/17/3.aspx" rel="noreferrer">checking if a PEFile is a .NET assembly by examining the binary structure</a>.</p>
<p>Is that the fastest method to test multiple files? I assume that trying to load each file (e.g. via <a href="http://msdn.microsoft.com/en-us/library/0et80c7k(VS.80).aspx" rel="noreferrer">Assembly.ReflectionOnlyLoad</a>) file might be pretty slow since it'll be loading file type information.</p>
<p>Note: I'm looking for a way to check files programmatically.</p>
| [
{
"answer_id": 331677,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": false,
"text": "StreamReader"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5/"
] |
330,034 | <p>When I pass a list of objects out of my silverlight app using WCF everything works fine until the List grows too big. It seems that when I exceed 80 items I get the error:
The remote server returned an unexpected response: (404) Not Found</p>
<p>I'm presuming that it's because the List has grown too big as when the List had 70 items everyhing works fine. Strange error message though, right?</p>
<p>In the config file I change the maxBufferSize to the highest value that it will accept but still I can't have more then 80 items in my List.
</p>
<p>How can I pass out large objects without having to split the object up?</p>
<hr>
<p>Thanks Shawn, so where exactly do I do it?
This is my ServiceReferences.ClientConfig</p>
<pre><code><configuration>
<system.serviceModel>
<client>
<!--"http://sy01911.fw.gsjbw.com/WcfService1/Service1.svc"-->
<endpoint address="http://localhost/WcfService1/Service1.svc"
binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService11"
contract="SilverlightApplication1.ServiceReference1.IService1"
name="BasicHttpBinding_IService1" />
</client>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IService1" maxBufferSize="655360000"
maxReceivedMessageSize="655360000">
<security mode="None" />
</binding>
<binding name="BasicHttpBinding_IService11" maxBufferSize="655360000"
maxReceivedMessageSize="655360000">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</code></pre>
<p></p>
<hr>
<p>and this is the server config that you mentioned</p>
<hr>
<pre><code><services>
<service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior" >
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" contract="WcfService1.IService1" >
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</code></pre>
<p></p>
| [
{
"answer_id": 377300,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "basicHttpBinding <system.serviceModel> <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.serviceModel>\n <bindings>\n <basicHttpBinding>\n <binding name=\"MyBasicHttpBinding\" maxReceivedMessageSize=\"300000000\">\n <security mode=\"None\"/>\n <readerQuotas maxStringContentLength=\"300000000\"/>\n </binding>\n </basicHttpBinding>\n </bindings>\n.......\n <endpoint address=\"\" binding=\"basicHttpBinding\" bindingConfiguration=\"MyBasicHttpBinding\" contract=\"WcfService1.IService1\">\n"
},
{
"answer_id": 3213034,
"author": "Jacob Adams",
"author_id": 32518,
"author_profile": "https://Stackoverflow.com/users/32518",
"pm_score": 2,
"selected": false,
"text": "<behaviors>\n <serviceBehaviors>\n <behavior name=\"YourBahvior\">\n <dataContractSerializer maxItemsInObjectGraph=\"6553600\"/>\n </behavior>\n </serviceBehaviors>\n</behaviors>\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,035 | <p>I am trying to establish the best practice for handling the creation of child objects when the parent object is incomplete or doesn't yet exist in a web application. I want to handle this in a stateless way so in memory objects are out.</p>
<p>For example, say we have a bug tracking application.</p>
<p>A Bug has a title and a description (both required) and any number of attachments. So the "Bug" is the parent object with a list of "Attachment" children.</p>
<p>So you present a page with a title input, a description input, and a file input to add an attachment. People then add the attachments but we haven't created the Parent Bug as yet.</p>
<p>How do you handle persisting the added attachments ? </p>
<p>Obviously we have to keep track of the attachments added, but at this point we haven't persisted the parent "Bug" object to attach the "Attachment" to.</p>
| [
{
"answer_id": 330069,
"author": "mshroyer",
"author_id": 40511,
"author_profile": "https://Stackoverflow.com/users/40511",
"pm_score": 1,
"selected": false,
"text": "use CGI qw(:standard);\nmy $query = CGI->new;\nprint \"Bug title: \" . $query->param(\"title\") . \"\\n\";\nprint \"Description: \" . $query->param(\"description\"). \"\\n\";\nprint \"Path to uploaded attachment: \" . $query->param(\"attachment\") . \"\\n\";\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11523/"
] |
330,043 | <p>I have a structure that represents a wire format packet. In this structure is an array of other structures. I have generic code that handles this very nicely for most cases but this array of structures case is throwing the marshaller for a loop.</p>
<p>Unsafe code is a no go since I can't get a pointer to a struct with an array (argh!).</p>
<p>I can see from <a href="http://www.codeproject.com/KB/dotnet/ReadingStructures.aspx" rel="nofollow noreferrer">this codeproject article</a> that there is a very nice, generic approach involving C++/CLI that goes something like...</p>
<pre><code>public ref class Reader abstract sealed
{
public:
generic <typename T> where T : value class
static T Read(array<System::Byte>^ data)
{
T value;
pin_ptr<System::Byte> src = &data[0];
pin_ptr<T> dst = &value;
memcpy((void*)dst, (void*)src,
/*System::Runtime::InteropServices::Marshal::SizeOf(T::typeid)*/
sizeof(T));
return value;
}
};
</code></pre>
<p>Now if just had the structure -> byte array / writer version I'd be set! Thanks in advance!</p>
| [
{
"answer_id": 330090,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 2,
"selected": false,
"text": "public ref class Writer abstract sealed\n {\n public:\n generic <typename T> where T : value class\n static System::Byte[] Write(T value)\n {\n System::Byte buffer[] = new System::Byte[sizeof(T)]; // this syntax is probably wrong.\n pin_ptr<System::Byte> dst = &buffer[0];\n pin_ptr<T> src = &value;\n\n memcpy((void*)dst, (void*)src,\n /*System::Runtime::InteropServices::Marshal::SizeOf(T::typeid)*/\n sizeof(T));\n\n return buffer;\n }\n };\n"
},
{
"answer_id": 330209,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 2,
"selected": false,
"text": "[System.Runtime.InteropServices.StructLayout]"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/109736/"
] |
330,053 | <p>I have a simple row that I edit using LINQ. It has about 30 columns, including a primary key numeric sequence.</p>
<p>When an UPDATE is performed through LINQ, the UPDATE statement includes all the columns of the table (for concurrency checking). </p>
<p>I'm wondering how inefficient this is - if not negligibiel. Since there is an index on the primary key I assume that column is being used for the initial row search and then the other fields are being checked in addition. I wouldn't have thought this would take more than a negligible amount of time.</p>
<p>The reason I ask is that I've seen this UPDATE take over a second in some cases, which just doesnt seem right. There may be other long running operations things going on but it made me curious as to whether or not I should be worried.</p>
<p>I know I can set 'UpdateCheck' to never for all the other fields, but this is a pain. </p>
<p>Is there a way to turn off 'Update Check' for a single SubmitChanges(), or do I have to do it by changing 'UpdateCheck' for every field.</p>
<p>Any advice would be appreciated.</p>
<p>Here is the SQL update :</p>
<pre><code>exec sp_executesql N'UPDATE [dbo].[SiteVisit]
SET [TotalTimeOnSite] = @p12, [ContentActivatedTime] = @p13
WHERE ([SiteVisitId] = @p0) AND ([SiteUserId] IS NULL) AND ([ClientGUID] = @p1) AND ([ServerGUID] IS NULL) AND ([UserGUID] = @p2) AND ([SiteId] = @p3) AND ([EntryURL] = @p4) AND ([CampaignId] = @p5) AND ([Date] = @p6) AND ([Cookie] IS NULL) AND ([UserAgent] = @p7) AND ([Platform] IS NULL) AND ([Referer] = @p8) AND ([KnownRefererId] = @p9) AND ([FlashVersion] IS NULL) AND ([SiteURL] IS NULL) AND ([Email] IS NULL) AND ([FlexSWZVersion] IS NULL) AND ([HostAddress] IS NULL) AND ([HostName] IS NULL) AND ([InitialStageSize] IS NULL) AND ([OrderId] IS NULL) AND ([ScreenResolution] IS NULL) AND ([TotalTimeOnSite] IS NULL) AND ([CumulativeVisitCount] = @p10) AND ([ContentActivatedTime] IS NULL) AND ([ContentCompleteTime] IS NULL) AND ([MasterVersion] = @p11) AND ([VisitedHome] IS NULL) AND ([VisitedStore] IS NULL) AND ([VisitedVideoDemos] IS NULL) AND ([VisitedProducts] IS NULL) AND ([VisitedAdvantages] IS NULL) AND ([VisitedGallery] IS NULL) AND ([VisitedTestimonials] IS NULL) AND ([VisitedEvolution] IS NULL) AND ([VisitedFAQ] IS NULL)',N'@p0 int,@p1 uniqueidentifier,@p2 uniqueidentifier,@p3 int,@p4 varchar(46),@p5 varchar(3),@p6 datetime,@p7 varchar(164),@p8 varchar(36),@p9 int,@p10 int,@p11 int,@p12 int,@p13 int',@p0=1009772,@p1='039A0614-31EE-4DD9-9E1A-8A0F947E1719',@p2='C83C0E68-142A-47CB-B7F9-BAF462E79429',@p3=1,@p4='http://www.example.com/default.aspx?c=183',@p5='183',@p6='2008-11-30 18:22:59:047',@p7='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SIMBAR={85B62341-3F6B-4645-A473-53A2D2BB66DC}; FunWebProducts; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)',@p8='http://apps.facebook.com/inthemafia/',@p9=1,@p10=1,@p11=30,@p12=6,@p13=6
</code></pre>
| [
{
"answer_id": 330073,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 5,
"selected": false,
"text": "UpdateCheck=\"never\" <Type Name=\"Badge\">\n <Column Name=\"Id\" Type=\"System.Int32\" DbType=\"Int NOT NULL IDENTITY\"\n IsPrimaryKey=\"true\" IsDbGenerated=\"true\" CanBeNull=\"false\" />\n <Column Name=\"Class\" Type=\"System.Byte\" DbType=\"TinyInt NOT NULL\"\n CanBeNull=\"false\" UpdateCheck=\"Never\" />\n <Column Name=\"Name\" Type=\"System.String\" DbType=\"VarChar(50) NOT NULL\" \n CanBeNull=\"false\" UpdateCheck=\"Never\" />\n"
},
{
"answer_id": 330103,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "timestamp exec sp_executesql N'UPDATE [dbo].[SiteVisit]\nSET [TotalTimeOnSite] = @p2, [ContentActivatedTime] = @p3\nWHERE ([SiteVisitId] = @p0) AND ([Timestamp] = @p1)\n"
},
{
"answer_id": 332836,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "exec sp_executesql N'UPDATE [dbo].[SiteVisit]\nSET [TotalTimeOnSite] = @p2\nWHERE ([SiteVisitId] = @p0) AND ([timestamp] = @p1)\n SELECT [t1].[timestamp]\nFROM [dbo].[SiteVisit] AS [t1]\nWHERE ((@@ROWCOUNT) > 0) AND ([t1].[SiteVisitId] = @p3)',N'@p0 int,@p1 timestamp,@p2 int,@p3 int',@p0=814109,@p1=0x0000000000269CB8,@p2=1199920,@p3=814109\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
330,056 | <p>I'm trying to see if anyone knows how to cluster some Lat/Long results, using a database, to reduce the number of results sent over the wire to the application.</p>
<p>There are a number of resources about how to cluster, either on the client side OR in the server (application) side .. but not in the database side :(</p>
<p><a href="https://stackoverflow.com/questions/73927/clustering-algorithm-for-mapping-application">This is a similar question</a>, asked by a fellow S.O. member. The solutions are server side based (ie. C# code behind).</p>
<p>Has anyone had any luck or experience with solving this, but in a database? Are there any database guru's out there who are after a hawt and sexy DB challenge?</p>
<p>please help :)</p>
<p>EDIT 1: Clarification - by clustering, i'm hoping to group <code>x</code> number of points into a single point, for an area. So, if i say cluster everything in a 1 mile / 1 km square, then all the results in that 'square' are GROUP'D into a single result (say ... the middle of the square).</p>
<p>EDIT 2: I'm using MS Sql 2008, but i'm open to hearing if there are other solutions in other DB's.</p>
| [
{
"answer_id": 330068,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": false,
"text": "def compute_chunk(latitude, longitude)\n (floor_lon(longitude) * 0x1000) | floor_lat(latitude)\nend\n\ndef floor_lon(longitude)\n ((longitude + 180) * 10).to_i\nend\n\ndef floor_lat(latitude)\n ((latitude + 90) * 10).to_i\nend\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
330,060 | <p>I create an <code>NSURLRequest</code> to post my data in the iPhone application to a server to proceed the PHP script. My PHP script is look like this.</p>
<pre><code><?php
$name = $_POST['name'];
$email = $_POST['email'];
$link = mysql_connect("localhost", "fffasfdas","Nfdsafafs") or die ("Unable to connect to database.");
mysql_select_db("muradsbi_mydatabase") or die ("Unable to select database.");
$sqlstatement= "INSERT INTO dbname (name,email) VALUES ('$name','$email')";
$newquery = mysql_query($sqlstatement, $link);
echo 'thanks for your register';
?>
</code></pre>
<p>and my <code>NSURLRequst</code> is created like below.</p>
<pre><code>NSString *myRequestString = @"&name=Hello%20World&email=Ohai2u";
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.google.com/"]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
</code></pre>
<p>However, this site is unable to get the data from this application and save it to the database, but I know it was connected succussfully because my application is able to get the response data from the server. I don't know whether my variable name is declared in the wrong way or others issues. How can I fix it?</p>
| [
{
"answer_id": 330064,
"author": "superfell",
"author_id": 41455,
"author_profile": "https://Stackoverflow.com/users/41455",
"pm_score": 6,
"selected": false,
"text": "& myRequestString content-type [request setValue:@\"application/x-www-form-urlencoded\" forHTTPHeaderField:@\"content-type\"];\n nil"
},
{
"answer_id": 7205645,
"author": "Spire",
"author_id": 450606,
"author_profile": "https://Stackoverflow.com/users/450606",
"pm_score": 0,
"selected": false,
"text": "NSString *name = [[NSString alloc]initWith String: @\"Hello World\"]; \nNSString *email = [[NSString alloc]initWith String: @\"Ohai2u\"]; \nNSString *urlString = [NSString stringWithFormat:@\"http://somedomain.com/sendMail.php?name=%@&email=%@\", \n [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],\n [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];\n\n NSURL *url = [[NSURL alloc] initWithString:urlString];\n\n NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];\n\n NSData *urlData;\n NSURLResponse *response;\n urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];\n [url release];\n"
},
{
"answer_id": 10419191,
"author": "Stefan Arentz",
"author_id": 56837,
"author_profile": "https://Stackoverflow.com/users/56837",
"pm_score": 3,
"selected": false,
"text": "NSData *data = [NSData dataWithBytes: [myRequestString UTF8String]\n length: [myRequestString length]];\n NSData *data = [myRequestString dataUsingEncoding: NSUTF8StringEncoding];\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,074 | <p>I've one plist file and I want to parse it and copy it's content into NSArray,and code that I am using for that is. </p>
<pre><code>NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *fooPath = [documentsPath stringByAppendingPathComponent:@"myfirstplist.plist"];
NSLog(fooPath);
self.myArray = [[NSArray arrayWithContentsOfFile:fooPath] retain];
NSLog(@"%@",myArray);
</code></pre>
<p>Now problem is very weird, sometime when I print myArray content it prints file data, and sometime it doesn't.</p>
<p>I am facing a same problem even when I use URL as my path.</p>
<pre><code>self.myArray = [[NSArray arrayWithContentsOfURL:URlPath] retain];
</code></pre>
<p>what would be the reason?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 332583,
"author": "Amit Vaghela",
"author_id": 451867,
"author_profile": "https://Stackoverflow.com/users/451867",
"pm_score": 0,
"selected": false,
"text": "self.myArray = [[NSArray arrayWithContentsOfURL:URlPath] retain];\n"
},
{
"answer_id": 2143869,
"author": "alex davila",
"author_id": 259697,
"author_profile": "https://Stackoverflow.com/users/259697",
"pm_score": 1,
"selected": false,
"text": "NSString *plistPath = [bundle pathForResource: @\"file-name\" ofType:@\"plist\"];\n NSArray *phrase2 = [NSArray arrayWithContentsOfFile: plistPath]; \nNSLog (@\"%@\", phrase2); \n"
},
{
"answer_id": 2143898,
"author": "alex davila",
"author_id": 259697,
"author_profile": "https://Stackoverflow.com/users/259697",
"pm_score": 1,
"selected": false,
"text": "NSBundle *bundle = [NSBundle mainBundle]; \n\nNSString *plistPath = [bundle pathForResource: @\"file-name\" ofType:@\"plist\"]; \n\nNSArray *phrase2 = [NSArray arrayWithContentsOfFile: plistPath];\n\nNSLog (@\"%@\", phrase2); \n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451867/"
] |
330,085 | <p>My aim is to convert a stream of byte code sent from an Alesis synthesizer to a human readable format. I need to be able to take a "Program Dump" and read the 10 character string that makes up the patch name.</p>
<p>In order to receive the "Program Dump" from the synth, I sent the synth the following command via MIDI-OX:</p>
<pre><code>F0 00 00 0E 0E 01 73 F7
</code></pre>
<p>I requested that it send me the dump for program 73.</p>
<p>I received this:</p>
<pre><code>F0 00 00 0E 0E 00 73 00 60 24 0B 27 27 01 64 1E 19 19 05 23 19 1E 2A 41 0D 23 46 19 1E 06 00 47 0D 23 30 6C 18 63 30 6C 18 40 3F 0A 67 1B 16 20 40 00 60 18 00 18 06 05 0C 2B 41 13 70 05 30 40 31 63 70 05 00 40 31 63 70 05 00 40 31 63 00 4C 2A 51 00 46 7F 78 18 40 0F 40 31 40 31 04 30 0C 00 30 6C 03 30 3C 0F 00 00 05 0A 0F 14 19 1E 23 28 2D 72 00 76 34 3C 54 42 19 46 0C 33 3C 0C 00 0E 1B 46 60 58 31 46 61 58 31 00 7F 14 4E 37 6C 74 13 00 40 31 00 30 0C 0A 18 56 02 27 60 0B 60 00 63 46 61 0B 00 00 63 46 61 0B 00 00 63 46 01 18 55 22 01 0C 7F 71 31 00 1F 00 63 00 63 08 60 18 00 60 58 07 60 18 1E 00 00 0A 14 1E 28 32 3C 46 50 5A 64 01 0C 2D 15 29 05 36 0C 19 66 78 18 00 1C 36 0C 41 31 63 0C 43 31 63 00 7E 29 1C 6F 58 00 01 02 00 63 00 60 18 14 30 2C 05 4E 40 17 40 01 46 0D 43 17 00 00 46 0D 43 17 00 00 46 0D 03 30 2A 45 02 18 7E 63 63 00 3E 00 46 01 46 11 40 31 00 40 31 0F 40 71 3D 00 00 14 28 3C 50 64 78 0C 21 35 49 03 58 4C 71 31 1C 6C 18 32 4C 71 31 00 38 6C 18 02 63 46 19 06 63 46 01 7C 53 00 60 18 53 37 6C 70 0D 03 40 31 28 60 58 0A 1C 01 2F 00 03 0C 1B 06 2F 00 00 0C 1B 06 2F 00 00 0C 1B 06 60 54 0A 05 30 7C 47 47 01 7C 00 0C 03 0C 23 00 63 00 00 63 1E 3C 63 18 00 00 28 50 78 20 49 71 19 42 6A 12 07 F7
</code></pre>
<p>MIDI-OX told me that it received 408 bytes.</p>
<p>This jives with the specification:</p>
<p>"There are 400 data bytes sent for a single program dump, which corresponds to 350
bytes of program data. With the header, the total number of bytes transmitted with
a program dump is 408. The location of each parameter within a program dump is
shown in the next section."</p>
<p>The "Program Dump" should be composed of these values:</p>
<pre><code>F0 00 00 0E 0E 00 <program#> <data> F7
</code></pre>
<p>That means the data should begin with "00 60" and end with "07 F7".</p>
<p>Now I should be able to convert these 400 bytes to the "350 bytes of packed parameter data" for this program. Following the "Program Data Format", 10 digits of the program name should be located within the packed data somewhere. Patch 73 is called either "BlowDeTune" or "PanBristle", not totally sure if it starts at 0 or 1.</p>
<p>So how do you go about make the conversion? Page 1 of the specification gives the transmission format, but I don't understand how to unpack it.</p>
<p>Can anyone help?</p>
<p>The Alesis QS MIDI Sysex Specification is here:</p>
<p><a href="http://www.midiworld.com/quadrasynth/qs_swlib/qs678r.pdf" rel="nofollow noreferrer">http://www.midiworld.com/quadrasynth/qs_swlib/qs678r.pdf</a></p>
<p>MIDI-OX can be found here:</p>
<p><a href="http://www.midiox.com/" rel="nofollow noreferrer">http://www.midiox.com/</a></p>
| [
{
"answer_id": 331329,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "0 - b07 b06 b05 b04 b03 b02 b01 b00\n1 - b17 b16 b15 b14 b13 b12 b11 b10\n2 - b27 b26 b25 b24 b23 b22 b21 b20\n3 - b37 b36 b35 b34 b33 b32 b31 b30\n4 - b47 b46 b45 b44 b43 b42 b41 b40\n5 - b57 b56 b55 b54 b53 b52 b51 b50\n6 - b67 b66 b65 b64 b63 b62 b61 b60\n 0 - 0 b06 b05 b04 b03 b02 b01 b00\n1 - 0 b15 b14 b13 b12 b11 b10 b07\n2 - 0 b24 b23 b22 b21 b20 b17 b16\n3 - 0 b33 b32 b31 b30 b27 b26 b25\n4 - 0 b42 b41 b40 b37 b36 b35 b34\n5 - 0 b51 b50 b47 b46 b45 b44 b43\n6 - 0 b60 b57 b56 b55 b54 b53 b52\n7 - 0 b67 b66 b65 b64 b63 b62 b61\n 0 - 00000000 0x00\n1 - 01100000 0x60\n2 - 00100100 0x24\n3 - 00001011 0x0B\n4 - 00100111 0x27\n5 - 00100111 0x27\n6 - 00000001 0x01\n7 - 01100100 0x64\n\n0 - 00011110 0x1E\n1 - 00011001 0x19\n2 - 00011001 0x19\n3 - 00000101 0x05\n4 - 00100011 0x23\n5 - 00011001 0x19\n6 - 00011110 0x1E\n7 - 00101010 0x2A\n 0 - 00000000 0x00\n1 - 00110000 0x30\n2 - 01101001 0x69\n3 - 01110001 0x71\n4 - 00111010 0x3A\n5 - 00000101 0x05\n6 - 11001000 0xC8\n\n0 - 10011110 0x9E\n1 - 01001100 0x4C\n2 - 10100110 0xA6\n3 - 00110000 0x30\n4 - 11001010 0xCA\n5 - 01111000 0x78\n6 - 01010100 0x54\n var midiData =\n[\n 0xF0, 0x00, 0x00, 0x0E, 0x0E, 0x00, 0x73,\n 0x00, 0x60, 0x24, 0x0B, 0x27, 0x27, 0x01, 0x64, 0x1E, 0x19, 0x19, 0x05, 0x23, 0x19, 0x1E, 0x2A,\n 0x41, 0x0D, 0x23, 0x46, 0x19, 0x1E, 0x06, 0x00, 0x47, 0x0D, 0x23, 0x30, 0x6C, 0x18, 0x63, 0x30,\n 0x6C, 0x18, 0x40, 0x3F, 0x0A, 0x67, 0x1B, 0x16, 0x20, 0x40, 0x00, 0x60, 0x18, 0x00, 0x18, 0x06,\n 0x05, 0x0C, 0x2B, 0x41, 0x13, 0x70, 0x05, 0x30, 0x40, 0x31, 0x63, 0x70, 0x05, 0x00, 0x40, 0x31,\n 0x63, 0x70, 0x05, 0x00, 0x40, 0x31, 0x63, 0x00, 0x4C, 0x2A, 0x51, 0x00, 0x46, 0x7F, 0x78, 0x18,\n 0x40, 0x0F, 0x40, 0x31, 0x40, 0x31, 0x04, 0x30, 0x0C, 0x00, 0x30, 0x6C, 0x03, 0x30, 0x3C, 0x0F,\n 0x00, 0x00, 0x05, 0x0A, 0x0F, 0x14, 0x19, 0x1E, 0x23, 0x28, 0x2D, 0x72, 0x00, 0x76, 0x34, 0x3C,\n 0x54, 0x42, 0x19, 0x46, 0x0C, 0x33, 0x3C, 0x0C, 0x00, 0x0E, 0x1B, 0x46, 0x60, 0x58, 0x31, 0x46,\n 0x61, 0x58, 0x31, 0x00, 0x7F, 0x14, 0x4E, 0x37, 0x6C, 0x74, 0x13, 0x00, 0x40, 0x31, 0x00, 0x30,\n 0x0C, 0x0A, 0x18, 0x56, 0x02, 0x27, 0x60, 0x0B, 0x60, 0x00, 0x63, 0x46, 0x61, 0x0B, 0x00, 0x00,\n 0x63, 0x46, 0x61, 0x0B, 0x00, 0x00, 0x63, 0x46, 0x01, 0x18, 0x55, 0x22, 0x01, 0x0C, 0x7F, 0x71,\n 0x31, 0x00, 0x1F, 0x00, 0x63, 0x00, 0x63, 0x08, 0x60, 0x18, 0x00, 0x60, 0x58, 0x07, 0x60, 0x18,\n 0x1E, 0x00, 0x00, 0x0A, 0x14, 0x1E, 0x28, 0x32, 0x3C, 0x46, 0x50, 0x5A, 0x64, 0x01, 0x0C, 0x2D,\n 0x15, 0x29, 0x05, 0x36, 0x0C, 0x19, 0x66, 0x78, 0x18, 0x00, 0x1C, 0x36, 0x0C, 0x41, 0x31, 0x63,\n 0x0C, 0x43, 0x31, 0x63, 0x00, 0x7E, 0x29, 0x1C, 0x6F, 0x58, 0x00, 0x01, 0x02, 0x00, 0x63, 0x00,\n 0x60, 0x18, 0x14, 0x30, 0x2C, 0x05, 0x4E, 0x40, 0x17, 0x40, 0x01, 0x46, 0x0D, 0x43, 0x17, 0x00,\n 0x00, 0x46, 0x0D, 0x43, 0x17, 0x00, 0x00, 0x46, 0x0D, 0x03, 0x30, 0x2A, 0x45, 0x02, 0x18, 0x7E,\n 0x63, 0x63, 0x00, 0x3E, 0x00, 0x46, 0x01, 0x46, 0x11, 0x40, 0x31, 0x00, 0x40, 0x31, 0x0F, 0x40,\n 0x71, 0x3D, 0x00, 0x00, 0x14, 0x28, 0x3C, 0x50, 0x64, 0x78, 0x0C, 0x21, 0x35, 0x49, 0x03, 0x58,\n 0x4C, 0x71, 0x31, 0x1C, 0x6C, 0x18, 0x32, 0x4C, 0x71, 0x31, 0x00, 0x38, 0x6C, 0x18, 0x02, 0x63,\n 0x46, 0x19, 0x06, 0x63, 0x46, 0x01, 0x7C, 0x53, 0x00, 0x60, 0x18, 0x53, 0x37, 0x6C, 0x70, 0x0D,\n 0x03, 0x40, 0x31, 0x28, 0x60, 0x58, 0x0A, 0x1C, 0x01, 0x2F, 0x00, 0x03, 0x0C, 0x1B, 0x06, 0x2F,\n 0x00, 0x00, 0x0C, 0x1B, 0x06, 0x2F, 0x00, 0x00, 0x0C, 0x1B, 0x06, 0x60, 0x54, 0x0A, 0x05, 0x30,\n 0x7C, 0x47, 0x47, 0x01, 0x7C, 0x00, 0x0C, 0x03, 0x0C, 0x23, 0x00, 0x63, 0x00, 0x00, 0x63, 0x1E,\n 0x3C, 0x63, 0x18, 0x00, 0x00, 0x28, 0x50, 0x78, 0x20, 0x49, 0x71, 0x19, 0x42, 0x6A, 0x12, 0x07,\n 0xF7\n];\n\n// Show original data\nDumpData(midiData, 16);\n\nvar headerLength = 7; // Bytes to skip\nvar resultData = new Array();\nvar decodedByteCount = 0; // Number of expanded bytes in result\n\nvar cumulator = 0;\nvar bitCount = 0;\nfor (var i = headerLength; // Skip header\n i < midiData.length - 1; // Omit EOF\n i++)\n{\n var rank = (i - headerLength) % 8; // We split the data in runs of 8 bytes\n // We cumulate the bits of these runs (less the high bit) to make a big word of 56 bits\n/*\n cumulator |= midiData[i] << (7 * rank);\n if (rank == 7) // End of the run\n {\n // Split the cumulator in 7 bytes\n for (var j = 0; j < 7; j++)\n {\n var shift = 8 * j;\n var byte = (cumulator & (0xFF << shift)) >> shift;\n WScript.StdOut.Write(ByteToHex(byte) + ' ');\n resultData[decodedByteCount++] = byte;\n }\n cumulator = 0; // Reset the buffer\n }\n*/\n // Actually, we cannot do that, because JS' bit arithmetic seems to be limited to signed 32 bits!\n // So I get the bytes out as soon as they are complete.\n // Somehow, it is more elegant anyway (but reflects less the original algorithm).\n cumulator |= midiData[i] << bitCount;\n bitCount += 7;\n//~ WScript.StdOut.Write((i - 7) + ':' + ByteToHex(midiData[i]) + ' (' + bitCount + ') ' + DecimalToHex(cumulator) + '\\n');\n if (bitCount >= 8)\n {\n var byte = cumulator & 0xFF;\n bitCount -= 8;\n cumulator >>= 8;\n resultData[decodedByteCount++] = byte;\n//~ WScript.StdOut.Write((i - 7) + ':' + ByteToHex(midiData[i]) + ' (' + bitCount + ') ' + DecimalToHex(cumulator) + ' > ' + ByteToHex(byte) + '\\n');\n }\n}\nDumpData(resultData, 14);\n function DumpData(data, lineLength)\n{\n WScript.StdOut.Write(\"Found \" + data.length + \" bytes\\n\");\n var txt = '';\n for (var i = 0; i < data.length; i++)\n {\n var rd = data[i];\n if (rd > 31)\n {\n txt += String.fromCharCode(rd);\n }\n else\n {\n txt += '.';\n }\n WScript.StdOut.Write(ByteToHex(rd) + ' ');\n if ((i+1) % lineLength == 0)\n {\n WScript.StdOut.Write(' ' + txt + '\\n');\n txt = '';\n }\n }\n WScript.StdOut.Write(' ' + txt + '\\n');\n}\n\nfunction NibbleToHex(halfByte)\n{\n return String.fromCharCode(halfByte < 10 ?\n halfByte + 48 : // 0 to 9\n halfByte + 55); // A to F\n}\n\nfunction ByteToHex(dec)\n{\n var h = (dec & 0xF0) >> 4;\n var l = dec & 0x0F;\n return NibbleToHex(h) + NibbleToHex(l);\n}\n\nfunction DecimalToHex(dec)\n{\n var result = '';\n do\n {\n result = ByteToHex(dec & 0xFF) + result;\n dec >>= 8;\n } while (dec > 0);\n return result;\n}\n Found 350 bytes\n00 30 69 71 3A 05 C8 9E 4C A6 30 CA 78 54 .0iq:.ÈL¦0ÊxT\nC1 C6 C8 98 F1 18 00 C7 C6 08 C6 C6 8C 61 ÁÆÈñ..ÇÆ.ÆÆa\n6C 0C F0 A7 38 6F 2C 20 20 00 8C 01 60 0C l.ð§8o, ..`.\n05 C6 2A 38 81 17 60 C0 D8 18 5E 00 00 63 .Æ*8.`ÀØ.^..c\n63 78 01 00 8C 8D 01 4C 55 14 60 FC E3 31 cx...LU.`üã1\nC0 07 30 06 8C 11 60 0C 00 8C 3D 80 F1 1E À.0..`..=ñ.\n00 40 41 F1 A0 64 3C 23 54 4B 0E B0 D3 78 .@Añ d<#TK.°Óx\n54 61 C6 C8 98 F1 18 00 C7 C6 08 C6 C6 8C TaÆÈñ..ÇÆ.ÆÆ\n61 6C 0C F0 A7 38 6F 6C FA 04 00 8C 01 60 al.ð§8olú...`\n0C 05 C6 2A 38 81 17 60 C0 D8 18 5E 00 00 ..Æ*8.`ÀØ.^..\n63 63 78 01 00 8C 8D 01 4C 55 14 60 FC E3 ccx...LU.`üã\n31 C0 07 30 06 8C 11 60 0C 00 8C 3D 80 31 1À.0..`..=1\n1E 00 40 41 F1 A0 64 3C 23 54 4B 0E 30 5A ..@Añ d<#TK.0Z\n95 54 C1 C6 C8 98 F1 18 00 C7 C6 08 C6 C6 TÁÆÈñ..ÇÆ.ÆÆ\n8C 61 6C 0C F0 A7 38 6F 2C 20 20 00 8C 01 al.ð§8o, ..\n60 0C 05 C6 2A 38 81 17 60 C0 D8 18 5E 00 `..Æ*8.`ÀØ.^.\n00 63 63 78 01 00 8C 8D 01 4C 55 14 60 FC .ccx...LU.`ü\nE3 31 C0 07 30 06 8C 11 60 0C 00 8C 3D 80 ã1À.0..`..=\nF1 1E 00 40 41 F1 A0 64 3C 23 54 4B 0E B0 ñ..@Añ d<#TK.°\nCC 78 8C C3 C6 C8 98 F1 18 00 C7 C6 08 C6 ÌxÃÆÈñ..ÇÆ.Æ\nC6 8C 61 6C 0C F0 A7 00 30 66 7A 63 C3 1B Æal.ð§.0fzcÃ.\n03 60 0C 05 C6 2A 38 81 17 60 C0 D8 18 5E .`..Æ*8.`ÀØ.^\n00 00 63 63 78 01 00 8C 8D 01 4C 55 14 60 ..ccx...LU.`\nFC E3 31 C0 07 30 06 8C 11 60 0C 00 8C 3D üã1À.0..`..=\nBC 31 06 00 40 41 F1 A0 64 3C 23 54 4B 0E ¼1..@Añ d<#TK.\n // Here the 8 bits of 7 bytes of raw data are coded as 7 bytes of data stripped off of the high bit,\n// while the stripped bits are grouped in the first byte of the data run.\n// In other words, when we have a run of 8 bytes, the first one groups the high bits of the 7 next bytes.\n// Information found at http://crystal.apana.org.au/ghansper/midi_introduction/file_dump.html\n\nvar headerLength = 7;\nvar resultData = new Array();\nvar decodedByteCount = 0; // Number of expanded bytes in result\nvar runCount = -1; // Number of runs in the encoded data\nfor (var i = headerLength; // Skip header\n i < midiData.length - 1; // Omit EOF\n i++)\n{\n var rank = (i - headerLength) % 8; // We split the data in runs of 8 bytes\n if (rank == 0) // Start of the run\n {\n // Get the high bits\n var highBits = midiData[i];\n runCount++;\n//~ WScript.StdOut.Write(runCount + ' > ' + (i - 7) + ' >> ' + ByteToHex(highBits) + '\\n');\n }\n else\n {\n resultData[decodedByteCount++] = midiData[i] |\n ((highBits & (1 << (7 - rank))) << rank);\n//~ WScript.StdOut.Write((i - 7) + ' >> ' + ByteToHex(midiData[i]) + ' > ' +\n//~ ByteToHex(midiData[i] | ((highBits & (1 << (7 - rank))) << rank)) + '\\n');\n }\n}\n"
},
{
"answer_id": 36956134,
"author": "solitud",
"author_id": 1187159,
"author_profile": "https://Stackoverflow.com/users/1187159",
"pm_score": 0,
"selected": false,
"text": "packSysex : function(midiData) {\n var header = [0xF0, 0x04, 0x01, 0x00, 0x03, 0x00]; //Voyager Single Preset Dump.\n\n var resultData = new Array();\n var packedByteCount = 0;\n var bitCount = 0;\n\n var thisByte;\n var packedByte;\n var nextByte = 0x0;\n\n\n for (var i = 0; i <= midiData.length; i++)\n {\n thisByte = midiData[i];\n packedByte = ((thisByte << bitCount) | nextByte) & 0x7F;\n nextByte = midiData[i] >> (7-bitCount);\n\n resultData[packedByteCount++] = packedByte;\n\n bitCount++;\n if(bitCount >= 7) {\n bitCount = 0;\n\n //Fill last byte\n packedByte = nextByte & 0x7F;\n resultData[packedByteCount++] = packedByte;\n nextByte = 0x0;\n }\n }\n\n resultData[packedByteCount++] = 0xF7;\n resultData = header.concat(resultData);\n\n return resultData;\n},\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42054/"
] |
330,092 | <p>I'm not familiar with shell scripting, so I'm not sure how to do it or if it is possible. If you can give me links or advice, that would be great.</p>
<p>What I want to do is:</p>
<ul>
<li><p>Create a file, simple text file
EX:</p>
<p>param1 (RANDOMVALUE)</p>
<p>Where randomvalue is a random number generated.</p>
</li>
<li><p>run a program with that file we just created and output to a file</p>
<p>./program filewejustcreated > A</p>
</li>
</ul>
<p>The program has already been created and it takes a filename as a parameter, no need to worry about that stuff.</p>
<ul>
<li>run another program with the file we just created, the program already exists and out put it to a file</li>
</ul>
<p>./Anotherprogram filewejustcreated > B</p>
<ul>
<li><p>run a diff comamand on A, B</p>
<p>diff A B</p>
</li>
</ul>
<p>Display what diff returns...</p>
<p>Thanks</p>
<p>[Edit] I am using shell: tcsh</p>
| [
{
"answer_id": 330105,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\nperl -e 'print \"TheWord (\", int(rand(1000)), \")\\n\"' > tempfile\n./program tempfile > A\n./Anotherprogram tempfile > B\n# rm tempfile # this would delete 'tempfile' if uncommented\ndiff A B\n chmod +x script.sh\n ./script.sh\n"
},
{
"answer_id": 330109,
"author": "Shyam Kumar Sundarakumar",
"author_id": 35392,
"author_profile": "https://Stackoverflow.com/users/35392",
"pm_score": 2,
"selected": false,
"text": "$RANDOM BASH #Pick the first argument to the call as the file name\nFILE_NAME=shift\necho \"param1 $RANDOM\" > $FILE_NAME\n./program $FILE_NAME > $FILE1\n./Anotherprogram $FILE_NAME > $FILE2\ndiff $FILE1 $FILE2\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,115 | <p>In C#, it is possible to retrieve assembly related information like product name, version etc using reflection:</p>
<pre><code>string productName = Assembly.GetCallingAssembly().GetName().Name;
string versionString = Assembly.GetCallingAssembly().GetName().Version.ToString();
</code></pre>
<p>How do I do the equivalent if the executing assembly is written in unmanaged C++ (say)? Is it even possible? Assume that I have a .NET dll which is being invoked in unmanaged code via a COM interface.</p>
<p><strong>edit:</strong><br>
To make things absolutely clear, this is my scenario:</p>
<ul>
<li>I have an executable written in
unmanaged C++ </li>
<li>I have a dll written
in C#/.NET </li>
<li>The dll is invoked by the
executable via a COM interface</li>
<li>Within the .NET dll I want to be
able to retrieve information like
the product name and version of the
calling executable.</li>
</ul>
<p>Possible?</p>
| [
{
"answer_id": 330314,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 0,
"selected": false,
"text": "Sub Main()\n Dim arrHeaders(41)\n\n Dim shell As New Shell32.Shell\n Dim objFolder As Shell32.Folder\n\n objFolder = shell.NameSpace(\"C:\\tmp\\\")\n\n For i = 0 To 40\n arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)\n Next\n For Each strFileName In objfolder.Items\n For i = 0 To 40\n Console.WriteLine(i & vbTab & arrHeaders(i) & \": \" & objFolder.GetDetailsOf(strFileName, i))\n Next\n Next\n\nEnd Sub\n 0 Name: dpvoice.dll\n1 Size: 208 KB\n2 Type: Application Extension\n3 Date Modified: 14.04.2008 04:41\n4 Date Created: 14.04.2008 04:41\n5 Date Accessed: 01.12.2008 09:56\n6 Attributes: A\n7 Status: Online\n8 Owner: Administrators\n9 Author:\n10 Title:\n11 Subject:\n12 Category:\n13 Pages:\n14 Comments:\n15 Copyright:\n16 Artist:\n17 Album Title:\n18 Year:\n19 Track Number:\n20 Genre:\n21 Duration:\n22 Bit Rate:\n23 Protected:\n24 Camera Model:\n25 Date Picture Taken:\n26 Dimensions:\n27 :\n28 :\n29 Episode Name:\n30 Program Description:\n31 :\n32 Audio sample size:\n33 Audio sample rate:\n34 Channels:\n35 Company: Microsoft Corporation\n36 Description: Microsoft DirectPlay Voice\n37 File Version: 5.3.2600.5512\n38 Product Name: Microsoftr Windowsr Operating System\n39 Product Version: 5.03.2600.5512\n40 Keywords:\n"
},
{
"answer_id": 331761,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": true,
"text": "HMODULE hEXE = GetModuleHandle(NULL);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4368/"
] |
330,125 | <p>Can anyone please help me to get the keycodes for the arrow keys in c# .net keypress events? Can you help me to get out of this check point?</p>
<p>best regards,
Arun.</p>
| [
{
"answer_id": 26214404,
"author": "Ashu",
"author_id": 3378851,
"author_profile": "https://Stackoverflow.com/users/3378851",
"pm_score": 0,
"selected": false,
"text": "e.KeyValue==39 \n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201406/"
] |
330,138 | <p>I have got these two classes interacting and I am trying to call four different classes from class one for use in class two.</p>
<p>The methods are public and they do return values but for some reason there is not a connection being made.
The error I get when I try is: <code>"An object reference is required for the nonstatic field, method, or property 'GradeBook.[method I want called]'"</code></p>
<hr>
<p>I have everything initialized. I don't want to create the methods as static. I read over the specifics of my assignment again and I'm not even supposed to but I can't seem to get this to work anyway I word it.</p>
<p>myGradeBook.[method]
GraceBook.[method]</p>
<p>It all seems to create errors.</p>
<p>The current errors:</p>
<pre><code>The best overloaded method match or 'System.Console.WriteLine(string, object)' has some invalid arguments.
Arugment '2': cannot convert from 'method group' to 'object'
</code></pre>
<p>I'm not even sur what those mean....</p>
<p>EDIT:
I just fixed that problem thanks to the Step Into feature of Visual Studio.
I don't know why it took me so long to use it.</p>
| [
{
"answer_id": 330140,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "GradeBook myGradeBook = new GradeBook();\n myGradeBook.[method you want called]\n"
},
{
"answer_id": 330141,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "class Example {\n public static string NonInstanceMethod() {\n return \"static\";\n }\n public string InstanceMethod() { \n return \"non-static\";\n }\n}\n\nstatic void SomeMethod() {\n Console.WriteLine(Example.NonInstanceMethod());\n Console.WriteLine(Example.InstanceMethod()); // Does not compile\n Example v1 = new Example();\n Console.WriteLine(v1.InstanceMethod());\n}\n"
},
{
"answer_id": 330143,
"author": "discorax",
"author_id": 30408,
"author_profile": "https://Stackoverflow.com/users/30408",
"pm_score": 4,
"selected": false,
"text": "MyClass myClass = new MyClass();\n myClass.myMethod();\n"
},
{
"answer_id": 330277,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public static string InstanceMethod() {return \"Hello World\";}\n object o = new object();\nstring s = o.InstanceMethod();\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29756/"
] |
330,149 | <p>I'm looking to spend a bit of my lunch break each day teaching myself some C#. I have access to some books on the subject via my employer-paid Books24x7 subscription, but I have no way of running code while I'm at work.</p>
<p>My work PC is rather locked down (no admin privileges, read-only "Program Files" - though install to a desktop-based folder is possible, and USB thumbdrives are forbidden..), so I'm looking for another way to compile some code.</p>
<p>Can anyone point to:
* A web-based compiler (binary download from a known-good site, or possibly a web-based CLI to interact with non-GUI apps)
* A standalone compiler requiring no-install
* A compiler which does not require admin right to install.</p>
<p>Thanks!</p>
<hr />
<p><strong>[Edit 1]</strong><br>
I suppose another reason why I mentioned the web-based compiler first was that I'm not sure which version(s) of the .Net framework might be installed on my work machine. We do absolutely no .Net work on my project so there's no reason to believe there's anything more than what came with XP. If there's a way to install the latest version without admin privileges, I'd love to hear it! </p>
| [
{
"answer_id": 330156,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 2,
"selected": false,
"text": "C:\\Windows\\Microsoft.NET\\Framework\\[VERSION]\\ csc.exe"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] |
330,151 | <p>I'm not sure if this has been asked or not yet, but how much logic should you put in your UI classes?</p>
<p>When I started programming I used to put all my code behind events on the form which as everyone would know makes it an absolute pain in the butt to test and maintain. Overtime I have come to release how bad this practice is and have started breaking everything into classes.</p>
<p>Sometimes when refactoring I still have that feeling of "where should I put this stuff", but because most of the time the code I'm working on is in the UI layer, has no unit tests and will break in unimaginable places, I usually end up leaving it in the UI layer.</p>
<p>Are there any good rules about how much logic you put in your UI classes? What patterns should I be looking for so that I don't do this kind of thing in the future?</p>
| [
{
"answer_id": 330284,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": true,
"text": "if (totalAmount < 0)\n color = \"RED\";\nelse\n color = \"BLACK\";\n if (totalAmount < 0)\n isNegative = true;\nelse\n isNegative = false;\n"
},
{
"answer_id": 330414,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "bound text, bound boolean, bound number, bound combobox, unbound label, ... beforeUpdate afterUpdate onClick beforeUpdate onClick afterUpdate Tbl_Form Tbl_Control"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
330,155 | <p>Can someone tell me how to change directories using FtpWebRequest? This seems like it should be an easy thing to do, but I'm not seeing it.</p>
<p><strong>EDIT</strong></p>
<p>I just want to add...I don't have my heart set on FtpWebRequest. If there's a better (easier) way to do FTP in .NET please let me know.</p>
<hr>
<p>Apparently there's no way to do it using a live connection, you need to change the uri to trick ftpwebrequest into using a different request (thanks Jon).</p>
<p>So I'm looking for a 3rd party client...</p>
<p>Some of the open source solutions I tried didn't work too well (kept crashing), but I found one open source solution that's passed some of my preliminary tests (<a href="http://sourceforge.net/projects/dotnetftpclient/" rel="noreferrer">.NET FTP Client</a>).</p>
| [
{
"answer_id": 330177,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "String uri = \"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl\";\nFtpWebRequest Request = (FtpWebRequest)WebRequest.Create(uri);\nRequest.Method = \"LIST\";\n uri = \"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/%2E%2E/%2E%2E\";\n cd ../../ ”..” \"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/../..\" \"ftp://myFtpUserName:myFtpUserPassword@myFtpUrl/\" FtpWebRequest \"ftp://myFtpUrl/%2F/anotherUserDir\"\n Cd /\ncd anotherUserDirectory\n"
},
{
"answer_id": 38051986,
"author": "Giochi Blu",
"author_id": 6509186,
"author_profile": "https://Stackoverflow.com/users/6509186",
"pm_score": 2,
"selected": false,
"text": "request.Close();\n uri = \"ftp://example.com/%2F/directory\" //Go to a forward directory (cd directory)\nuri = \"ftp://example.com/%2E%2E\" //Go to the previously directory (cd ../)\n\nFtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330155",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
] |
330,169 | <p>It's been quite a while since I last used <a href="http://digitalmars.com/d" rel="nofollow noreferrer">D Programming Language</a>, and now I'm using it for some project that involves scientific calculations.</p>
<p>I have a bunch of floating point data, but when I print them using <code>writefln</code>, I get results like: <code>4.62593E-172</code> which is a zero! How do I use string formatting % stuff to print such things as 0?</p>
<p>Right now I'm using a hack: </p>
<pre><code> if( abs(a) < 0.0000001 )
writefln(0);
else
writefln(a);
</code></pre>
<p>it does the job, but I want to do it using the formatting operations, if possible.</p>
<p><strong>UPDATE</strong></p>
<p>someone suggested <code>writefln("%.3f", a)</code> but the problem with it is that it prints needless extra zeros, i.e. <code>0</code> becomes <code>0.000</code> and <code>1.2</code> becomes <code>1.200</code><br>
Can I make it also remove the trailing zeros?</p>
| [
{
"answer_id": 330192,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 2,
"selected": false,
"text": "writefln(\"%.3f\", a);\n"
},
{
"answer_id": 330338,
"author": "Sascha",
"author_id": 36372,
"author_profile": "https://Stackoverflow.com/users/36372",
"pm_score": 4,
"selected": true,
"text": "vsprintf()"
},
{
"answer_id": 330586,
"author": "larsivi",
"author_id": 14047,
"author_profile": "https://Stackoverflow.com/users/14047",
"pm_score": -1,
"selected": false,
"text": "Stdout.formatln(\"{:f2}\", 1.2);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35364/"
] |
330,178 | <p>Checkstyle reports this code as "The double-checked locking idiom is broken", but I don't think that my code actually is affected by the problems with double-checked locking.</p>
<p>The code is supposed to create a row in a database if a row with that id doesn't exist. It runs in a multi-threaded environment and I want to avoid the primary-key-exists SQL-exceptions.</p>
<p>The pseudo-code:</p>
<pre><code>private void createRow(int id) {
Row row = dao().fetch(id);
if (row == null) {
synchronized (TestClass.class) {
row = dao().fetch(id);
if (row == null) {
dao().create(id);
}
}
}
}
</code></pre>
<p>I can agree that it looks like double-checked locking, but I am not using static variables and the code in fetch() and create() is probably too complex to be inlined and put out of order.</p>
<p>Am I wrong or checkstyle? :)</p>
| [
{
"answer_id": 330184,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": true,
"text": "row = dao().create(id);\n dao().fetch"
},
{
"answer_id": 330189,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "row == null INSERT OR UPDATE synchronized"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40136/"
] |
330,186 | <p>I'm currently working on a DNA database class and I currently associate each row in the database with both a match score (based on edit distance) and the actual DNA sequence itself, is it safe to modify first this way within an iteration loop?</p>
<pre><code>typedef std::pair<int, DnaDatabaseRow> DnaPairT;
typedef std::vector<DnaPairT> DnaDatabaseT;
// ....
for(DnaDatabaseT::iterator it = database.begin();
it != database.end(); it++)
{
int score = it->second.query(query);
it->first = score;
}
</code></pre>
<p>The reason I am doing this is so that I can sort them by score later. I have tried maps and received a compilation error about modifying first, but is there perhaps a better way than this to store all the information for sorting later?</p>
| [
{
"answer_id": 330196,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 4,
"selected": true,
"text": "first DnaPairT #include <vector>\n#include <utility>\n#include <algorithm> \n\ntypedef std::pair<int, DnaDatabaseRow> DnaPairT;\ntypedef std::vector<DnaPairT *> DnaDatabaseT;\n\n// ...\n\n// your scoring code, modified to use pointers\nvoid calculateScoresForQuery(DnaDatabaseT& database, queryT& query)\n{\n for(DnaDatabaseT::iterator it = database.begin(); it != database.end(); it++)\n {\n int score = (*it)->second.query(query);\n (*it)->first = score;\n }\n}\n\n// custom sorting function to handle DnaPairT pointers\nbool sortByScore(DnaPairT * A, DnaPairT * B) { return (A->first < B->first); }\n\n// function to sort the database\nvoid sortDatabaseByScore(DnaDatabaseT& database)\n{\n sort(database.begin(), database.end(), sortByScore);\n}\n\n// main\nint main()\n{\n DnaDatabaseT database;\n\n // code to load the database with DnaPairT pointers ...\n\n calculateScoresForQuery(database, query);\n sortDatabaseByScore(database);\n\n // code that uses the sorted database ...\n} query"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2594/"
] |
330,206 | <p>In PHP, depending on your error reporting level, if you don't define a constant and then call it like so:</p>
<pre><code><?= MESSAGE ?>
</code></pre>
<p>It may print the name of the constant instead of the value!</p>
<p>So, I wrote the following function to get around this problem, but I wanted to know if you know a way to do it in faster code? I mean, when I did a speed test without this function, I can define and dump 500 constants in .0073 seconds. But use this function below, and this switches to anywhere from .0159 to .0238 seconds. So, it would be great to get the microseconds down to as small as possible. And why? Because I want to use this for templating. I'm thinking there simply has to be a better way than toggling the error reporting with every variable I want to display.</p>
<pre><code>function C($constant) {
$nPrev1 = error_reporting(E_ALL);
$sPrev2 = ini_set('display_errors', '0');
$sTest = defined($constant) ? 'defined' : 'not defined';
$oTest = (object) error_get_last();
error_reporting($nPrev1);
ini_set('display_errors', $sPrev2);
if (strpos($oTest->message, 'undefined constant')>0) {
return '';
} else {
return $constant;
}
}
<?= C(MESSAGE) ?>
</code></pre>
| [
{
"answer_id": 330271,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 3,
"selected": false,
"text": "function C($constant) {\n return defined($constant) ? constant($constant) : 'Undefined';\n}\n\necho C('MESSAGE') . '<br />';\n\ndefine('MESSAGE', 'test');\n\necho C('MESSAGE') . '<br />';\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,207 | <p>One concept I've always wondered about is the use of cryptographic hash functions and values. I understand that these functions can generate a hash value that is unique and virtually impossible to reverse, but here's what I've always wondered:</p>
<p>If on my server, in PHP I produce:</p>
<pre><code>md5("stackoverflow.com") = "d0cc85b26f2ceb8714b978e07def4f6e"
</code></pre>
<p>When you run that same string through an MD5 function, you get the same result on your PHP installation. A process is being used to produce some value, from some starting value.</p>
<p>Doesn't this mean that there is some way to deconstruct what is happening and reverse the hash value? </p>
<p>What is it about these functions that makes the resulting strings impossible to retrace?</p>
| [
{
"answer_id": 330232,
"author": "Trevel",
"author_id": 25110,
"author_profile": "https://Stackoverflow.com/users/25110",
"pm_score": 4,
"selected": false,
"text": "\"hello\" -> \"1ab53\"\n\"Hello\" -> \"993LB\"\n\"ZR#!RELSIEKF\" -> \"1ab53\"\n"
},
{
"answer_id": 929885,
"author": "Babar",
"author_id": 102668,
"author_profile": "https://Stackoverflow.com/users/102668",
"pm_score": 0,
"selected": false,
"text": "aea23489ce3aa9b6406ebb28e0cda430\n"
},
{
"answer_id": 7151531,
"author": "Paŭlo Ebermann",
"author_id": 600500,
"author_profile": "https://Stackoverflow.com/users/600500",
"pm_score": 5,
"selected": false,
"text": "function simple_hash($input) {\n return bin2hex(substr(str_pad($input, 16), 0, 16));\n}\n print simple_hash(\"stackoverflow.com\");\n 737461636b6f766572666c6f772e636f6d\n hex2bin simple_hash"
},
{
"answer_id": 14969061,
"author": "Olathe",
"author_id": 463897,
"author_profile": "https://Stackoverflow.com/users/463897",
"pm_score": 0,
"selected": false,
"text": "password Wsg5Nm^bkI4EgxUOhpAjTmTjO0F!VkWvysS6EEMsIJiTZcvsh@WI$IH$TYqiWvK!%&Ue&nk55ak%BX%9!NnG%32ftud%YkBO$U6o password Wsg5Nm^bkI4EgxUO"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1390354/"
] |
330,215 | <p>Is there a Php function to determine if a string consist of only ASCII alphanumerical characters?</p>
<p>Note: I'm sorry if the question sounds dumb to some, but I couldn't easily find such a function in the Php manual.</p>
| [
{
"answer_id": 330225,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 1,
"selected": false,
"text": "preg_match('/^[a-z0-9]+$/i', $str);\n"
},
{
"answer_id": 24667031,
"author": "Fabrizio",
"author_id": 583230,
"author_profile": "https://Stackoverflow.com/users/583230",
"pm_score": 0,
"selected": false,
"text": "<?php\npublic function alphanum($string){\n if(function_exists('ctype_alnum')){\n $return = ctype_alnum($string);\n }else{\n $return = preg_match('/^[a-z0-9]+$/i', $string) > 0;\n }\n return $return;\n}\n?>\n"
},
{
"answer_id": 37091909,
"author": "Saemon Zixel",
"author_id": 6304685,
"author_profile": "https://Stackoverflow.com/users/6304685",
"pm_score": 0,
"selected": false,
"text": "strspn($string, '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM_') == strlen($string)\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
330,229 | <p>When presenting preformatted text on the web (e.g. code samples), line wrapping can be a problem. You want to wrap for readability without scrolling, but also need it to be unambiguous to the user that it is all one line with no line break.</p>
<p>For example, you may have a really long command line to display, like this:</p>
<pre><code>c:\Program Files\My Application\Module\bin\..> Some_really_long_command line "with parameters" "that just go on and on" " that should all be typed on one line" "but need to be wrapped for display and I'd like the text style to indicate that it has wrapped"
</code></pre>
<p>(Stackoverflow forces a line like this not to wrap.)</p>
<p>Is there a way of styling with CSS to give the same treatment as you see in books? i.e. to wrap the line, but include an image or glyph that indicates a line continuation. </p>
<p>Obviously I am looking for a style that can be applied to all text, and let the browser's XHTML/CSS rendering engine figure out which lines have wrapped and therefore need the special treatment.</p>
<h1>The Solution so far..</h1>
<h2>Adding line continuation glyphs</h2>
<p>Thanks to Jack Ryan and Maarten Sander, have a reasonably workable solution to add continuation glyphs to either the left or right of wrapped lines. It requires an image with repeating glyphs in the vertical, which is offset so that it is invisible if only one unwrapped line. The main requirement of this technique is that every line needs to be within a block (e.g. p, span or div). This means it cannot easily be used manually with existing text that is just sitting in a pre block.</p>
<p>The fragment below summarises the essential technique. I posted a live example <a href="http://blog.tardate.com/2008/12/code-formatting-and-line-continuations.html" rel="nofollow noreferrer">here</a>.</p>
<pre><code>.wrap-cont-l {
margin-left: 24px;
margin-bottom: 14px;
width: 400px;
}
.wrap-cont-l p {
font-family: Courier New, Monospace;
font-size: 12px;
line-height: 14px;
background: url(wrap-cont-l.png) no-repeat 0 14px; /* move the background down so it starts on line 2 */
text-indent: -21px;
padding-left: 14px;
margin: 0 0 2px 7px;
}
.wrap-cont-r {
margin-left: 24px;
margin-bottom: 14px;
width: 400px;
}
.wrap-cont-r p {
font-family: Courier New, Monospace;
font-size: 12px;
line-height: 14px;
background: url(wrap-cont-r.png) no-repeat right 14px; /* move the background down so it starts on line 2 */
text-indent: -28px;
margin: 0 0 2px 28px;
padding-right: 14px;
}
</code></pre>
<p>To be used like this:</p>
<pre><code><div class="wrap-cont-l">
<p>take a long line</p>
<p>take a long line</p>
</div>
<div class="wrap-cont-r">
<p>take a long line</p>
<p>reel him in</p>
</div>
</code></pre>
<h2>But wait, there's more!</h2>
<p>I recently discovered <a href="http://code.google.com/p/syntaxhighlighter" rel="nofollow noreferrer">syntaxhighlighter</a> by Alex Gorbatchev. It is a fantastic tool for dynamically and automatically formatting text blocks. It is principally intended for syntax highlighting code, but could be used for any text. In v1.5.1 however, it does not wrap lines (in fact it forces them not to wrap).</p>
<p>I did a little hacking around though, and was able to add a simple line wrap option syntaxhighlighter and also incorporate the continuation glyph idea. </p>
<p>I've added this to the <a href="http://blog.tardate.com/2008/12/code-formatting-and-line-continuations.html" rel="nofollow noreferrer">live examples</a> and included a few notes on the hacks required (they are trivial). So with this as the text in the page:</p>
<pre><code><textarea name="code" class="java:wraplines" cols="60" rows="10">
public class HelloWorld {
public static void main (String[] args)
{
System.out.println("Hello World! But that's not all I have to say. This line is going to go on for a very long time and I'd like to see it wrapped in the display. Note that the line styling clearly indicates a continuation.");
}
}
</textarea>
</code></pre>
<p>This is a snapshot of the formatted result:</p>
<p><a href="http://tardate.com/syntaxhighlighter/line-continuation-example.jpg" rel="nofollow noreferrer">screenshot http://tardate.com/syntaxhighlighter/line-continuation-example.jpg</a></p>
| [
{
"answer_id": 330352,
"author": "Jack Ryan",
"author_id": 28882,
"author_profile": "https://Stackoverflow.com/users/28882",
"pm_score": 3,
"selected": true,
"text": "p.codeLine\n{\n font-size: 12px;\n line-height: 12px;\n font-family: Monospace;\n background: transparent url(lineGlyph) no-repeat 0 12px; /* move the background down so it starts on line 2 */\n padding-left: 6px; /* move the text over so we can see the newline glyph*/\n}\n"
},
{
"answer_id": 330388,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "\np {\n font-family: Arial, Sans-Serif;\n font-size: 13px;\n line-height: 16px;\n margin: 0 0 16px 0;\n}\n\n.wrap-cont {\n font-family: Courier New, Monospace;\n margin-bottom: 16px;\n width: 400px;\n}\n\n.wrap-cont p {\n background: url(wrap-cont.gif) no-repeat bottom right;\n text-indent: -32px;\n margin: 0 0 0 32px;\n padding-right: 16px;\n}\n \n<p>For example, you may have a really long command line to display, like this:</p>\n<div class=\"wrap-cont\">\n <p>c:\\Program Files\\My Application\\Module\\bin\\..> Some_really_long_command line \"with parameters\" \"that just go on and on\" \" that should all be typed on one line\" \"but need to be wrapped for display and I'd like the text style to indicate that it has wrapped\"</p>\n <p>c:\\Program Files\\My Application\\Module\\bin\\..> Some_really_long_command line \"with parameters\" \"that just go on and on\" \" that should all be typed on one line\" \"but need to be wrapped for display and I'd like the text style to indicate that it has wrapped\"</p>\n</div>\n<p>Stackoverflow forces a line like this not to wrap.</p>\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6329/"
] |
330,241 | <p>From my code (Java) I want to ensure that a row exists in the database (DB2) after my code is executed.</p>
<p>My code now does a <code>select</code> and if no result is returned it does an <code>insert</code>. I really don't like this code since it exposes me to concurrency issues when running in a multi-threaded environment.</p>
<p>What I would like to do is to put this logic in DB2 instead of in my Java code.
Does DB2 have an <code>insert-or-update</code> statement? Or anything like it that I can use?</p>
<p>For example:</p>
<pre><code>insertupdate into mytable values ('myid')
</code></pre>
<p>Another way of doing it would probably be to always do the insert and catch "SQL-code -803 primary key already exists", but I would like to avoid that if possible.</p>
| [
{
"answer_id": 330364,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 5,
"selected": false,
"text": "MERGE INTO target_table USING source_table ON match-condition\n{WHEN [NOT] MATCHED \n THEN [UPDATE SET ...|DELETE|INSERT VALUES ....|SIGNAL ...]}\n[ELSE IGNORE]\n"
},
{
"answer_id": 16032501,
"author": "CupOfTea",
"author_id": 1854720,
"author_profile": "https://Stackoverflow.com/users/1854720",
"pm_score": 4,
"selected": false,
"text": "CREATE TABLE STAGE.TEST_TAB ( ID INTEGER, DATE DATE, STATUS VARCHAR(10) );\nCOMMIT;\n\nINSERT INTO TEST_TAB VALUES (1, '2013-04-14', NULL), (2, '2013-04-15', NULL); COMMIT;\n\nMERGE INTO TEST_TAB T USING (\n SELECT\n 3 NEW_ID,\n CURRENT_DATE NEW_DATE,\n 'NEW' NEW_STATUS\n FROM\n SYSIBM.DUAL\nUNION ALL\n SELECT\n 2 NEW_ID,\n NULL NEW_DATE,\n 'OLD' NEW_STATUS\n FROM\n SYSIBM.DUAL \n) AS S\n ON\n S.NEW_ID = T.ID\n WHEN MATCHED THEN\n UPDATE SET\n (T.STATUS) = (S.NEW_STATUS)\n WHEN NOT MATCHED THEN\n INSERT\n (T.ID, T.DATE, T.STATUS) VALUES (S.NEW_ID, S.NEW_DATE, S.NEW_STATUS);\nCOMMIT;\n"
},
{
"answer_id": 23223928,
"author": "Felipe",
"author_id": 3561128,
"author_profile": "https://Stackoverflow.com/users/3561128",
"pm_score": 2,
"selected": false,
"text": "update TABLE_NAME set FIELD_NAME=xxxxx where MyID=XXX;\n\nINSERT INTO TABLE_NAME (MyField1,MyField2) values (xxx,xxxxx) \nWHERE NOT EXISTS(select 1 from TABLE_NAME where MyId=xxxx);\n"
},
{
"answer_id": 23784606,
"author": "teknopaul",
"author_id": 870207,
"author_profile": "https://Stackoverflow.com/users/870207",
"pm_score": 4,
"selected": false,
"text": "MERGE INTO mytable AS mt USING (\n SELECT * FROM TABLE (\n VALUES \n (123, 'text')\n )\n) AS vt(id, val) ON (mt.id = vt.id)\nWHEN MATCHED THEN\n UPDATE SET val = vt.val\nWHEN NOT MATCHED THEN\n INSERT (id, val) VALUES (vt.id, vt.val)\n;\n VALUES \n (123, 'text'),\n (456, 'more')\n"
},
{
"answer_id": 65351965,
"author": "akshay",
"author_id": 9247596,
"author_profile": "https://Stackoverflow.com/users/9247596",
"pm_score": -1,
"selected": false,
"text": "String sql=\"Insert into tblstudent (firstName,lastName,gender) values (?,?,?) \nON DUPLICATE KEY UPDATE \nfirstName= VALUES(firstName),\nlastName= VALUES(lastName),\ngender= VALUES(gender)\";\n String sql=\"Insert into tblstudent (id,firstName,lastName,gender) values (?,?,?) \nON DUPLICATE KEY UPDATE \nid=id+1,\nfirstName= VALUES(firstName),\nlastName= VALUES(lastName),\ngender= VALUES(gender)\";\n"
},
{
"answer_id": 73884205,
"author": "Vlado Lovis",
"author_id": 13608212,
"author_profile": "https://Stackoverflow.com/users/13608212",
"pm_score": 0,
"selected": false,
"text": "Merge MERGE INTO USERS t \n USING (VALUES (123, 'John', 'john@host.com')) \n AS v(ID, NAME, EMAIL)\n ON (t.ID = v.ID)\nWHEN MATCHED THEN \n UPDATE SET NAME = v.NAME,EMAIL = v.EMAIL \nWHEN NOT MATCHED THEN \n INSERT (ID,NAME,EMAIL) VALUES (v.ID,v.NAME,v.EMAIL)\n Java PreparedStatement LUW 9.7 final String TABLE = \"USERS\";\nfinal int NUM_OF_KEYS = 1; //first n columns are keys(PKs)\nfinal String COLUMNS = Arrays.asList(\n \"ID\", //1 only this first 1 column will be PK\n \"NAME\", //2\n \"EMAIL\"); //3\nString mergreSqlString = getMergeSql(TABLE, COLUMNS, NUM_OF_KEYS);\n MERGE INTO USERS t \n USING (VALUES (?,?,?)) \n AS v(ID, NAME, EMAIL)\n ON (t.ID = v.ID)\nWHEN MATCHED THEN \n UPDATE SET NAME = v.NAME,EMAIL = v.EMAIL \nWHEN NOT MATCHED THEN \n INSERT (ID,NAME,EMAIL) VALUES (v.ID,v.NAME,v.EMAIL)\n PreparedStatement /**\n * Creates a String representation of DB2 SQL Merge Statement.<br>\n * The returned SQL should be used with {@link java.sql.PreparedStatement}.<br>\n * This Merge Statement will perform <b>update</b> if it matches already existing record,\n * else <b>insert</b> will be performed.<br>\n * The matching will be done on first n columns.(Where n is numberOfKeys)<br>\n * This means that the DB Table Identifiers(PKs) have to be at the start of the provided columns List.<br>\n * Example of matching:<br>\n * columns = {\"id\", \"key\", \"name\"}; numberOfKey = 2 (first 2 columns are used in matching condition)<br>\n * Matching condition will look like: <br>\n * preparedStatementSetValue.id = table.id <b>AND</b> preparedStatementSetValue.key = table.key<br>\n * <b>Please note the order of List of columns is important because:</b>\n * <ul>\n * <li>First numberOfKeys columns are used for matching.</li>\n * <li>When setting values of PreparedStatement, they have to be filled in same order as they are supplied to this method.</li>\n * </ul>\n * @param table name of table the returned Merge statement will be created for\n * @param columns ordered list of columns to be merged, starting with identifiers(Primary Keys), must be >=1\n * @param numberOfKeys number of first n columns that will be used for matching\n * @return a new String representing DB2 SQL Merge Statement, or null if some problem occurs\n * @see <a href=\"https://www.ibm.com/docs/en/db2-for-zos/12?topic=statements-merge\">IBM DB2 Merge Statement</a>\n */\n public static String getMergeSql(String table, List<String> columns, int numberOfKeys) {\n if (numberOfKeys < 1 || //Need at least 1 key to match on\n Objects.isNull(columns) ||\n columns.isEmpty() ||\n numberOfKeys > columns.size() || //Cannot match on more columns than were provided\n Objects.isNull(table) ||\n table.isEmpty()) {\n return null; //Input validation failed.\n }\n\n return \"MERGE INTO \" + table +\n \" t \" + // table reference (DO NOT CHANGE - ref. is used in getMatchingOrUpdateString)\n \"USING (VALUES \" +\n getPsValues(columns.size()) + // question marks for prepared statement parameters\n \") AS v\" + // table reference (DO NOT CHANGE - ref. is used in getMatchingOrUpdateString)\n getColumns(columns, \"\") + //all columns separated by ','\n \" ON (\" +\n getMatchingOrUpdateString(columns, numberOfKeys, true) + //get matching String\n \") WHEN MATCHED THEN UPDATE SET \" +\n //Update Statement\n getMatchingOrUpdateString(columns, numberOfKeys, false) +//get update String\n \" WHEN NOT MATCHED THEN INSERT \" +\n //Insert Statement\n getColumns(columns, \"\") + //all columns separated by ,\n \" VALUES \" +\n getColumns(columns, \"v.\"); //all columns with 'v.' prefix, separated by ','\n }\n\n /**\n * Builds a new String that can have one of two formats, example :<br>\n * if isMatching == true :<br>\n * mt.column[0] = v.column[0], mt.column[1] = v.column[1],..., mt.column[n-1] = v.column[n-1] <br>\n * if isMatching == false :<br>\n * column[n] = v.column[n], column[n+1] = v.column[n+1],..., column[columns.size()-1] = v.column[columns.size()-1]\n * @param columns list of columns from which this string is build\n * @param n denotes how many columns are keys\n * @param isMatching determines format of the returned string\n * @return a new String constructed from input arguments\n */\n private static String getMatchingOrUpdateString(List<String> columns, int n, boolean isMatching) {\n StringBuilder result = new StringBuilder();\n\n //matching string starts at 0 and ends at n-1 -> i.e., appends all key columns (first n columns)\n //update string starts at n and appends the rest of columns -> i.e., appends all columns except of key columns\n int startIndex = isMatching ? 0 : n;\n int endIndex = isMatching ? n : columns.size();\n for (int i = startIndex ; i < endIndex; i++) {//loop over desired columns and create the string\n if (isMatching) result.append(\"t.\");\n result.append(columns.get(i));\n result.append(\" = \");\n result.append(\"v.\");\n result.append(columns.get(i));\n result.append(\",\");\n }\n replaceLastCommaWithString(result, \"\");// delete last comma\n\n return result.toString();\n }\n\n /**\n * Builds String like (?,?,...,?) the number of ? is determined by the parameter n\n * @param n determines the number of '?'\n * @return a new String like '(?,?,...,?)'\n */\n private static String getPsValues(int n) {\n StringBuilder result = new StringBuilder(\"(\");\n for (int i = 0; i < n; i++) {\n result.append(\"?,\");\n }\n replaceLastCommaWithString(result, \")\"); // replace last string with closing bracket\n return result.toString();\n }\n\n /**\n * Builds String like ([columnPrefix]columns[0], [columnPrefix]columns[1], ... [columnPrefix]columns[n])\n * The columnPrefix is either empty, or a table name from which selection is made e.g., \"v.\"\n * @param columns list of column names\n * @param columnPrefix prefix for each column name\n * @return a new String constructed from columns argument\n */\n private static String getColumns(List<String> columns, String columnPrefix) {\n String delimiter = \",\" + columnPrefix;\n return \"(\" + columnPrefix +\n String.join(delimiter, columns) +\n \")\";\n }\n\n private static void replaceLastCommaWithString(StringBuilder sb, String replacement) {\n int idx = sb.lastIndexOf(\",\");\n if (idx != -1) { // avoid IndexOutOfBounds exception (if \",\" wasn't found)\n sb.replace(idx, ++idx, replacement);\n }\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40136/"
] |
330,268 | <p>I have an array full of random content item ids. I need to run a mysql query (id in the array goes in the WHERE clause), using each ID that's in the array, in the order that they appear in the said array. How would I do this? </p>
<p>This will be an UPDATE query, for each individual ID in the array.</p>
| [
{
"answer_id": 330274,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 2,
"selected": false,
"text": "$ids = array(2,4,6,8);\n$ids = implode($ids);\n$sql=\"SELECT * FROM my_table WHERE id IN($ids);\";\nmysql_query($sql);\n $ids = array(2,4,6,8);\nforeach($ids as $id) {\n $sql=\"SELECT * FROM my_table WHERE ID = $id;\";\n mysql_query($sql);\n}\n"
},
{
"answer_id": 330279,
"author": "Rodney Amato",
"author_id": 4342,
"author_profile": "https://Stackoverflow.com/users/4342",
"pm_score": 0,
"selected": false,
"text": "foreach ($array as $key = $var) {\n if ((int) $var <= 0) {\n unset($array[$key]);\n }\n}\n\n\n$query = \"SELECT * \nfrom content \nWHERE contentid IN ('\".implode(\"','\", $array).\"')\";\n\n$result = mysql_query($query);\n"
},
{
"answer_id": 330280,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 6,
"selected": true,
"text": "$ids = array(2, 4, 6, 8);\n\n// prepare an SQL statement with a single parameter placeholder\n$sql = \"UPDATE MyTable SET LastUpdated = GETDATE() WHERE id = ?\";\n$stmt = $mysqli->prepare($sql);\n\n// bind a different value to the placeholder with each execution\nfor ($i = 0; $i < count($ids); $i++)\n{\n $stmt->bind_param(\"i\", $ids[$i]);\n $stmt->execute();\n echo \"Updated record ID: $id\\n\";\n}\n\n// done\n$stmt->close();\n $ids = array(2, 4, 6, 8);\n\n// prepare an SQL statement with multiple parameter placeholders\n$params = implode(\",\", array_fill(0, count($ids), \"?\"));\n$sql = \"UPDATE MyTable SET LastUpdated = GETDATE() WHERE id IN ($params)\";\n$stmt = $mysqli->prepare($sql);\n\n// dynamic call of mysqli_stmt::bind_param hard-coded eqivalent\n$types = str_repeat(\"i\", count($ids)); // \"iiii\"\n$args = array_merge(array($types), $ids); // [\"iiii\", 2, 4, 6, 8]\ncall_user_func_array(array($stmt, 'bind_param'), ref($args)); // $stmt->bind_param(\"iiii\", 2, 4, 6, 8)\n\n// execute the query for all input values in one step\n$stmt->execute();\n\n// done\n$stmt->close();\necho \"Updated record IDs: \" . implode(\",\" $ids) .\"\\n\";\n\n// ----------------------------------------------------------------------------------\n// helper function to turn an array of values into an array of value references\n// necessary because mysqli_stmt::bind_param needs value refereces for no good reason\nfunction ref($arr) {\n $refs = array();\n foreach ($arr as $key => $val) $refs[$key] = &$arr[$key];\n return $refs;\n}\n execute()"
},
{
"answer_id": 330295,
"author": "Fusion",
"author_id": 6253,
"author_profile": "https://Stackoverflow.com/users/6253",
"pm_score": 1,
"selected": false,
"text": "$ids = array(2, 4, 6, 8);\nfor ($i = 0; $i < count($ids); $i++)\n{\n mysql_query(\"UPDATE MyTable SET LastUpdated = GETDATE() WHERE id = \" . intval($ids[$i]));\n}\n"
},
{
"answer_id": 330316,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 1,
"selected": false,
"text": "$values_filtered = array_filter('is_int', $values);\nif (count($values_filtered) == count($values)) {\n $sql = 'update table set attrib = 'something' where someid in (' . implode(',', $values_filtered) . ');';\n //execute\n} else {\n //do something\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,303 | <p>Is it possible to create a stored procedure as</p>
<pre><code>CREATE PROCEDURE Dummy
@ID INT NOT NULL
AS
BEGIN
END
</code></pre>
<p>Why is it not possible to do something like this?</p>
| [
{
"answer_id": 330324,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 1,
"selected": true,
"text": "IF ISNULL(@param) THEN\n raise error ....\nEND IF\n"
},
{
"answer_id": 330333,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 6,
"selected": false,
"text": "RAISERROR CREATE proc dbo.CheckForNull @i int \nas\nbegin\n if @i is null \n raiserror('The value for @i should not be null', 15, 1) -- with log \n\nend\nGO\n exec dbo.CheckForNull @i = 1 \n exec dbo.CheckForNull @i = null \n"
},
{
"answer_id": 25404531,
"author": "Patrick Fromberg",
"author_id": 2712726,
"author_profile": "https://Stackoverflow.com/users/2712726",
"pm_score": 4,
"selected": false,
"text": "Natively Compiled"
},
{
"answer_id": 51818160,
"author": "BigBother",
"author_id": 8018798,
"author_profile": "https://Stackoverflow.com/users/8018798",
"pm_score": 1,
"selected": false,
"text": "RAISERROR CREATE proc dbo.CheckForNull \n @name sysname = 'parameter',\n @value sql_variant\nas\nbegin\n if @value is null\n raiserror('The value for %s should not be null', 16, 1, @name) -- with log\nend\nGO\n exec dbo.CheckForNull @name 'whateverParamName', @value = 1\n exec dbo.CheckForNull @value = null \n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21586/"
] |
330,320 | <p>In an aspx page I get the Windows username with the function <code>Request.LogonUserIdentity.Name</code>. This function returns a string in the format "domain\user".</p>
<p>Is there some function to only get the username, without resorting to the <code>IndexOf</code> and <code>Substring</code>, like this?</p>
<pre><code>public static string StripDomain(string username)
{
int pos = username.IndexOf('\\');
return pos != -1 ? username.Substring(pos + 1) : username;
}
</code></pre>
| [
{
"answer_id": 330408,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 7,
"selected": true,
"text": "var user = System.Web.HttpContext.Current.User; \nvar name = user.Identity.Name;\n\nvar slashIndex = name.IndexOf(\"\\\\\");\nreturn slashIndex > -1 \n ? name.Substring(slashIndex + 1)\n : name.Substring(0, name.IndexOf(\"@\"));\n var name = Request.LogonUserIdentity.Name;\n\nvar slashIndex = name.IndexOf(\"\\\\\");\nreturn slashIndex > -1 \n ? name.Substring(slashIndex + 1)\n : name.Substring(0, name.IndexOf(\"@\"));\n"
},
{
"answer_id": 330417,
"author": "Johan Buret",
"author_id": 15366,
"author_profile": "https://Stackoverflow.com/users/15366",
"pm_score": 0,
"selected": false,
"text": "string[] parts= username.Split( new char[] {'\\\\'} );\nreturn parts[1];\n"
},
{
"answer_id": 331459,
"author": "Mr. Kraus",
"author_id": 5132,
"author_profile": "https://Stackoverflow.com/users/5132",
"pm_score": 3,
"selected": false,
"text": "public static string NameWithoutDomain( this WindowsIdentity identity )\n{\n string[] parts = identity.Name.Split(new char[] { '\\\\' });\n\n //highly recommend checking parts array for validity here \n //prior to dereferencing\n\n return parts[1];\n}\n"
},
{
"answer_id": 332406,
"author": "BenAlabaster",
"author_id": 40650,
"author_profile": "https://Stackoverflow.com/users/40650",
"pm_score": 1,
"selected": false,
"text": "static class IdentityHelpers\n{\n public static string ShortName(this WindowsIdentity Identity)\n {\n if (null != Identity)\n {\n return Identity.Name.Split(new char[] {'\\\\'})[1];\n }\n return string.Empty;\n }\n}\n WindowsIdentity a = WindowsIdentity.GetCurrent();\nConsole.WriteLine(a.ShortName);\n"
},
{
"answer_id": 7754605,
"author": "Vitaliy Ulantikov",
"author_id": 63867,
"author_profile": "https://Stackoverflow.com/users/63867",
"pm_score": 5,
"selected": false,
"text": "WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();\nif (windowsIdentity == null)\n throw new InvalidOperationException(\"WindowsIdentity is null\");\nstring nameWithoutDomain = windowsIdentity.Name.Split('\\\\').Last();\n"
},
{
"answer_id": 16150796,
"author": "Robin V.",
"author_id": 1738331,
"author_profile": "https://Stackoverflow.com/users/1738331",
"pm_score": 6,
"selected": false,
"text": "System.Environment.UserName System.Environment.UserDomainName"
},
{
"answer_id": 55603215,
"author": "nop",
"author_id": 9991651,
"author_profile": "https://Stackoverflow.com/users/9991651",
"pm_score": 1,
"selected": false,
"text": "var usernameWithoutDomain = Path.GetFileName(@\"somedomain\\someusername\")\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
] |
330,331 | <p>I just recently installed <a href="http://www.oddsock.org/tools/gen_songrequester/" rel="nofollow noreferrer">Winamp Song Requester</a> wich is a Winamp web song requester plugin with a built in minimal HTTP CGI Server.</p>
<p>What the plugin does is that it runs a web server, serves a html page with some special variables wich it replaces with actual data on request (playlist, request queue, time left in song etc).</p>
<p>I saw this as a fun and good project to learn some jQuery so I started hooking up my own js code to replace, fix and ajaxify the served website from the plugin but I've now run into a problem with character encoding.</p>
<p>On the page you get links to all songs in the playlist. When you click on one of the links I hooked up my own jQuery click function. So instead of reloading the whole page when you request a song I do a <code>$.get($(this).attr('href', function(response) {... code ...})</code> and then I use replaceWith to replace the current queue with the new generated queue with your request added on the fly. I do the same thing to show/update currently playing and on search so that everything get fetched in the background and then replaced on the fly with some animations added.</p>
<p>All jQuery/Ajax works great but the big problem I have is with charset and with song names in queue/playlist. Special characters (åäöé etc.) in names doesn't work at all.</p>
<p>The plugin outputs everything in iso-8859-1/latin1 and my meta tag in the markup tells the browser that this page is latin1. On a normal page refresh in the browser this works well and the special characters display as normal. But when I use jQuery and <code>$.get()</code> to replace blocks of code on the fly the special characters only show up as ?.</p>
<p>I think that the problem lies in that jQuery defaults to believe that the <code>$.get()</code> response is UTF-8 if no header says otherwise. The plugin doesn't set any header for encoding/charset at all and since I have no control at all of the backend and what headers get set I can't change this.</p>
<p>The only headers I get in the response from the plugin is:</p>
<blockquote>
<p>Server: WinampServer<br/>
Connection: close<br/>
Content-Type: text/html</p>
</blockquote>
<p>I hope you understand my problem. I've got a page where I have no control at all over the backend and all I have to work with is generated HTML. I can't change or add headers in responses. I need to tell jQuery that the response is actually in latin1 and not UTF-8 so that the encoding of special characters don't break. I've tried the scriptCharset: 'iso-8859-1' in jQuerys ajaxSetup but that only works with type script/json and I'm working with HTML responses.</p>
<p>Any idea if this is possible or any other workaround you could think about?</p>
| [
{
"answer_id": 330398,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 6,
"selected": true,
"text": "$.ajaxSetup({\n 'beforeSend' : function(xhr) {\n xhr.overrideMimeType('text/html; charset=UTF-8');\n },\n});\n$('#stuff').load('/yourresource.file'); // your ajax load\n UTF-8 ISO-8859-1"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32728/"
] |
330,334 | <p>What would be the best way to do this.</p>
<p>The input string is </p>
<pre><code><133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust.</135_3></133_3>
</code></pre>
<p>the expected output is </p>
<pre><code>{'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit \
using either camera now they are just sitting and collecting dust.':[133, 135],
'The other system worked for about 1 month': [116],
'on it then it started doing the same thing as the first one':[137]
}
</code></pre>
<p>that seems like a recursive regexp search but I can't figure out how exactly.</p>
<p>I can think of a tedious recursive function as of now, but have a feeling that there should be a better way.</p>
<p>Related question: <a href="https://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns">Can regular expressions be used to match nested patterns?</a></p>
| [
{
"answer_id": 330463,
"author": "Daniel Naab",
"author_id": 32638,
"author_profile": "https://Stackoverflow.com/users/32638",
"pm_score": 3,
"selected": true,
"text": "from xml.parsers.expat import ParserCreate\n\nopen_elements = {}\nresult_dict = {}\n\ndef start_element(name, attrs):\n open_elements[name] = True\n\ndef end_element(name):\n del open_elements[name]\n\ndef char_data(data):\n for element in open_elements:\n cur = result_dict.setdefault(element, '')\n result_dict[element] = cur + data\n\nif __name__ == '__main__':\n p = ParserCreate()\n\n p.StartElementHandler = start_element\n p.EndElementHandler = end_element\n p.CharacterDataHandler = char_data\n\n p.Parse(u'<_133_3><_135_3><_116_2>The other system worked for about 1 month</_116_2> got some good images <_137_3>on it then it started doing the same thing as the first one</_137_3> so then I quit using either camera now they are just sitting and collecting dust.</_135_3></_133_3>', 1)\n\n print result_dict\n"
},
{
"answer_id": 330591,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "from cStringIO import StringIO\nfrom collections import defaultdict\n####from xml.etree import cElementTree as etree\nfrom lxml import etree\n\nxml = \"<e133_3><e135_3><e116_2>The other system worked for about 1 month</e116_2> got some good images <e137_3>on it then it started doing the same thing as the first one</e137_3> so then I quit using either camera now they are just sitting and collecting dust. </e135_3></e133_3>\"\n\nd = defaultdict(list)\nfor event, elem in etree.iterparse(StringIO(xml)):\n d[''.join(elem.itertext())].append(int(elem.tag[1:-2]))\n\nprint(dict(d.items()))\n {'on it then it started doing the same thing as the first one': [137], \n'The other system worked for about 1 month': [116], \n'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \\\neither camera now they are just sitting and collecting dust. ': [133, 135]}\n"
},
{
"answer_id": 330931,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "import re\n\nre_tag = re.compile(r'<(?P<tag>[^>]+)>(?P<content>.*?)</(?P=tag)>', re.S)\n\ndef iterparse(text, tag=None):\n if tag is not None: yield tag, text\n for m in re_tag.finditer(text):\n for tag, text in iterparse(m.group('content'), m.group('tag')):\n yield tag, text\n\ndef strip_tags(content):\n nested = lambda m: re_tag.sub(nested, m.group('content'))\n return re_tag.sub(nested, content)\n\n\ntxt = \"<133_3><135_3><116_2>The other system worked for about 1 month</116_2> got some good images <137_3>on it then it started doing the same thing as the first one</137_3> so then I quit using either camera now they are just sitting and collecting dust. </135_3></133_3>\"\nd = {}\nfor tag, text in iterparse(txt):\n d.setdefault(strip_tags(text), []).append(int(tag[:-2]))\n\nprint(d)\n {'on it then it started doing the same thing as the first one': [137], \n 'The other system worked for about 1 month': [116], \n 'The other system worked for about 1 month got some good images on it then it started doing the same thing as the first one so then I quit using \\\n either camera now they are just sitting and collecting dust. ': [133, 135]}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33612/"
] |
330,337 | <p>I have a greasemonkey user script with this single line of code...</p>
<pre><code>window.close();
</code></pre>
<p>but firefox does not allow a user script to close a window (as reported by an error message in the error console)</p>
<p>Is there a work around to this problem?</p>
| [
{
"answer_id": 330372,
"author": "M.N",
"author_id": 18615,
"author_profile": "https://Stackoverflow.com/users/18615",
"pm_score": 6,
"selected": true,
"text": "function closeTab(){\n window.open('', '_self', '');\n window.close();\n} \n"
},
{
"answer_id": 54340012,
"author": "DDRRSS",
"author_id": 6664036,
"author_profile": "https://Stackoverflow.com/users/6664036",
"pm_score": 3,
"selected": false,
"text": "// @grant window.close\n// @grant window.focus\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
330,339 | <p>Is there any way to re-generate views from newly updated model?</p>
| [
{
"answer_id": 331746,
"author": "Benny Wong",
"author_id": 2999,
"author_profile": "https://Stackoverflow.com/users/2999",
"pm_score": 5,
"selected": true,
"text": "./script/generate -f scaffold Model\n"
},
{
"answer_id": 34286633,
"author": "jbheren",
"author_id": 5025832,
"author_profile": "https://Stackoverflow.com/users/5025832",
"pm_score": 2,
"selected": false,
"text": "rails destroy scaffold Model -f rails generate scaffold Model"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27257/"
] |
330,367 | <p>I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with the application. This algorithm is used often during each user's work to make certain important decisions.</p>
<p>For performance reasons, re-initializing the state on every request from the (semi-normalized) database data quickly becomes non-feasible. It would be highly preferable, for example, to cache the state's Python object in some way so that it can simply be used and/or updated whenever necessary. However, since this is a web application, there several processes serving requests, so using a global variable is out of the question.</p>
<p>I've tried serializing the relevant object (via pickle) and saving the serialized data to the DB, and am now experimenting with caching the serialized data via memcached. However, this still has the significant overhead of serializing and deserializing the object often.</p>
<p>I've looked at shared memory solutions but the only relevant thing I've found is <a href="http://poshmodule.sourceforge.net/" rel="nofollow noreferrer">POSH</a>. However POSH doesn't seem to be widely used and I don't feel easy integrating such an experimental component into my application.</p>
<p>I need some advice! This is my first shot at developing a web application, so I'm hoping this is a common enough issue that there are well-known solutions to such problems. At this point solutions which assume the Python back-end is running on a single server would be sufficient, but extra points for solutions which scale to multiple servers as well :)</p>
<p>Notes:</p>
<ul>
<li>I have this application working, currently live and with active users. I started out without doing any premature optimization, and then optimized as needed. I've done the measuring and testing to make sure the above mentioned issue is the actual bottleneck. I'm sure pretty sure I could squeeze more performance out of the current setup, but I wanted to ask if there's a better way.</li>
<li>The setup itself is still a work in progress; assume that the system's architecture can be whatever suites your solution.</li>
</ul>
| [
{
"answer_id": 330580,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 3,
"selected": true,
"text": "multiprocessing"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40076/"
] |
330,371 | <p>I've been a web developer for some time now, and have recently started learning some functional programming. Like others, I've had some significant trouble apply many of these concepts to my professional work. For me, the primary reason for this is I see a conflict between between FP's goal of remaining stateless seems quite at odds with that fact that most web development work I've done has been heavily tied to databases, which are very data-centric.</p>
<p>One thing that made me a much more productive developer on the OOP side of things was the discovery of object-relational mappers like MyGeneration d00dads for .Net, Class::DBI for perl, ActiveRecord for ruby, etc. This allowed me to stay away from writing insert and select statements all day, and to focus on working with the data easily as objects. Of course, I could still write SQL queries when their power was needed, but otherwise it was abstracted nicely behind the scenes.</p>
<p>Now, turning to functional-programming, it seems like with many of the FP web frameworks like Links require writing a lot of boilerplate sql code, as in <a href="http://groups.inf.ed.ac.uk/links/examplessrc/dictionary/dict-suggest-update.links" rel="noreferrer">this example</a>. Weblocks seems a little better, but it seems to use kind of an OOP model for working with data, and still requires code to be manually written for each table in your database as in <a href="http://www.bitbucket.org/S11001001/weblocks-dev/src/3ca71e2dfdd3/examples/weblocks-clsql-demo/src/model/" rel="noreferrer">this example</a>. I suppose you use some code generation to write these mapping functions, but that seems decidedly un-lisp-like.</p>
<p>(Note I have not looked at Weblocks or Links extremely closely, I may just be misunderstanding how they are used).</p>
<p>So the question is, for the database access portions (which I believe are pretty large) of web application, or other development requiring interface with a sql database we seem to be forced down one of the following paths:</p>
<ol>
<li>Don't Use Functional Programming</li>
<li>Access Data in an annoying, un-abstracted way that involves manually writing a lot of SQL or SQL-like code ala Links</li>
<li>Force our functional Language into a pseudo-OOP paradigm, thus removing some of the elegance and stability of true functional programming.</li>
</ol>
<p>Clearly, none of these options seem ideal. Has found a way circumvent these issues? Is there really an even an issue here?</p>
<p>Note: I personally am most familiar with LISP on the FP front, so if you want to give any examples and know multiple FP languages, lisp would probably be the preferred language of choice</p>
<p>PS: For Issues specific to other aspects of web development see <a href="https://stackoverflow.com/questions/292033/is-functional-programming-relevant-to-web-development">this question</a>.</p>
| [
{
"answer_id": 10498495,
"author": "animal",
"author_id": 96640,
"author_profile": "https://Stackoverflow.com/users/96640",
"pm_score": 4,
"selected": false,
"text": "# Start: Time T\nlikes(db, \"Bob\")\n=> \"Suzie\"\n# Change who bob likes\n...\nlikes(db \"Bob\")\n=> \"Alice\"\n# Recover the database from T\ndb = getDb(T)\nlikes(db, \"Bob\")\n=> \"Suzie\"\n"
},
{
"answer_id": 56091013,
"author": "Lin Pengcheng",
"author_id": 11485521,
"author_profile": "https://Stackoverflow.com/users/11485521",
"pm_score": 1,
"selected": false,
"text": " Clojure -> DBMS, Super Foxpro\n STM -> Transaction,MVCC\nPersistent Collections -> db, table, col\n hash-map -> indexed data\n Watch -> trigger, log\n Spec -> constraint\n Core API -> SQL, Built-in function\n function -> Stored Procedure\n Meta Data -> System Table\n\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] |
330,374 | <p>As per c99 standard, size of <code>long long</code> should be minimum 64 bits. How is this implemented in a 32 bit machine (eg. addition or multiplication of 2 <code>long long</code>s). Also, What is the equivalent of <code>long long</code> in C++.</p>
| [
{
"answer_id": 330377,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 2,
"selected": false,
"text": "#include <stdint.h>\n\nint32_t n;\n struct my_64bit_integer {\n uint32_t low;\n uint32_t high;\n};\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39615/"
] |
330,383 | <p>Given a string as below, I need to convert:</p>
<p>1 Dec 2008 06:43:00 +0100</p>
<p>to</p>
<p>MM/DD/YYYY HH:MM:SSAM</p>
<p>using jython what is the best way to do this?</p>
| [
{
"answer_id": 330466,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 3,
"selected": true,
"text": "import java\nsdf = java.text.SimpleDateFormat\n\nfmt_in = sdf('d MMM yyyy HH:mm:ss Z')\nfmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')\n\nfmt_out.format(fmt_in.parse(time_str))\n"
},
{
"answer_id": 330596,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "strptime(string[, format]) strptime import time\nmytime = time.strptime(\"1 Dec 2008 06:43:00 +0100\", \"%d %b %Y %H:%M:%S %Z\")\nnew_time_string = time.strftime(\"%m/%d/%Y %I:%M:%S%p\", mytime)\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21537/"
] |
330,387 | <p>While checking out the generic collection in .net i found about KeyedByTypeCollection. Although I worked with it and got to know how to use it, I did not get in which scenario it will be useful.</p>
<p>I read through <a href="https://stackoverflow.com/questions/178255/serviceprovider-cache-etc-done-with-generics-without-cast">ServiceProvider, cache etc. done with generics without cast</a>, but could not get much.</p>
<p>I think, there must have a reason as to why it has been included in the .Net framework. Any body who have used the KeyedByTypeCollection can explain me why they used it or any body, if they know in which scenario potentially it can be used, can explain it to me. </p>
<p>As more of a curiosity does any other languages support this type of collection ? </p>
| [
{
"answer_id": 349304,
"author": "Prensen",
"author_id": 43633,
"author_profile": "https://Stackoverflow.com/users/43633",
"pm_score": 5,
"selected": true,
"text": "KeyedCollection<KEY,VALUE> KEY VALUE public class Factory<T>\n{\n private readonly KeyedByTypeCollection<T> _singletons = new KeyedByTypeCollection<T>();\n\n public V GetSingleton<V>() where V : T, new()\n {\n if (!_singletons.Contains(typeof(V)))\n {\n _singletons.Add(new V());\n }\n return (V)_singletons[typeof(V)];\n }\n}\n [Test]\n public void Returns_Singletons()\n {\n Factory<ICar> factory = new Factory<ICar>();\n Opel opel1 = factory.GetSingleton<Opel>();\n Opel opel2 = factory.GetSingleton<Opel>();\n\n Assert.IsNotNull(opel1);\n Assert.IsNotNull(opel2);\n Assert.AreEqual(opel1, opel2);\n }\n KeyedByTypeCollection<T>"
},
{
"answer_id": 13703707,
"author": "Hugh",
"author_id": 925090,
"author_profile": "https://Stackoverflow.com/users/925090",
"pm_score": 2,
"selected": false,
"text": "Current Instance Singleton<T> class A : Singleton<B> SingletonFactory"
},
{
"answer_id": 52809373,
"author": "James Johnston",
"author_id": 10505131,
"author_profile": "https://Stackoverflow.com/users/10505131",
"pm_score": 1,
"selected": false,
"text": "KeyedCollection GetKeyForItem KeyedByTypeCollection Find FindAll Remove RemoveAll KeyedCollection KeyedByTypeCollection KeyedCollection FindAll RemoveAll FindAll FindAll RemoveAll GetKeyForItem GetKeyForItem"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
330,390 | <p>I'm writing a web application that will have "plugins". The plugins will be .DLL files which will export their functionality through predefined interfaces 'n stuff. All the .DLL files are in a folder called "Plugins", and the ASP.NET application loads them all upon startup (by using Assembly.LoadFrom).</p>
<p>The problem is that when developing, these plugins will change fairly often (all the functionality is in the plugins, the website itself is just a skeleton). Thus, I need a way to automatically restart the application when the .DLL files change.</p>
<p>How do I do that?</p>
| [
{
"answer_id": 330440,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 2,
"selected": false,
"text": "HttpRuntime.UnloadAppDomain();"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41360/"
] |
330,391 | <p>Because this is not the kind of company where wiki's are accepted, we tend to do a lot of communication through outlook. Sending code snippets through it is painfull.
Is there some way to get the markdown thing we have here, but in outlook?</p>
| [
{
"answer_id": 330711,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 3,
"selected": false,
"text": "__text__ **bold** - 1."
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
330,395 | <p>I am setting up a development server in my flat. I have set up an Ubuntu DNS server on it and have added the zone weddinglist (just weddinglist - no <a href="http://en.wikipedia.org/wiki/Top-level_domain" rel="noreferrer">TLD</a>. It's just an internal domain.)</p>
<p>This works fine on my Ubuntu laptop.</p>
<p>On all my Windows PCs (Vista and XP) I get the following from the command prompt:</p>
<pre><code>C:\Users\Giles Roadnight>nslookup weddinglist
Server: UnKnown
Address: 192.168.0.40
Name: weddinglist
Address: 192.168.0.41
C:\Users\Giles Roadnight>ping 192.168.0.41
Pinging 192.168.0.41 with 32 bytes of data:
Reply from 192.168.0.41: bytes=32 time<1ms TTL=64
Reply from 192.168.0.41: bytes=32 time<1ms TTL=64
Reply from 192.168.0.41: bytes=32 time<1ms TTL=64
Reply from 192.168.0.41: bytes=32 time<1ms TTL=64
Ping statistics for 192.168.0.41:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds: Minimum = 0ms, Maximum = 0ms, Average = 0ms
C:\Users\Giles Roadnight>ping weddinglist
Ping request could not find host weddinglist. Please check the name and try again.
</code></pre>
<p>My ipconfig:</p>
<pre><code>C:\Users\Giles Roadnight>ipconfig -all
Windows IP Configuration
Host Name . . . . . . . . . . . . : Giles-Desktop
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Hybrid
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix . :
Description . . . . . . . . . . . : Marvell Yukon 88E8001/8003/8010 PCI Gigabit Ethernet Controller
Physical Address. . . . . . . . . : **-**-**-**-**-**
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::f179:680f:f313:5448%8(Preferred)
IPv4 Address. . . . . . . . . . . : 192.168.0.5(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.0.1
DNS Servers . . . . . . . . . . . : 192.168.0.40
NetBIOS over Tcpip. . . . . . . . : Enabled
</code></pre>
<p>I am pretty sure that I have the DNS set up OK as the nslookup is OK but I can't ping and I can't access webpages at weddinglist.</p>
<p>How can I make ping work for the Windows PCs?</p>
| [
{
"answer_id": 330409,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": false,
"text": "nslookup ping"
},
{
"answer_id": 330411,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": "C:\\WINDOWS\\system32\\drivers\\etc\n nslookup"
},
{
"answer_id": 14993221,
"author": "Jamie Cook",
"author_id": 105804,
"author_profile": "https://Stackoverflow.com/users/105804",
"pm_score": 6,
"selected": false,
"text": "net stop dnscache\nnet start dnscache\n"
},
{
"answer_id": 15847871,
"author": "Nick",
"author_id": 2251573,
"author_profile": "https://Stackoverflow.com/users/2251573",
"pm_score": 3,
"selected": false,
"text": "ipconfig /flushdns"
},
{
"answer_id": 23377946,
"author": "xx1xx",
"author_id": 1792831,
"author_profile": "https://Stackoverflow.com/users/1792831",
"pm_score": 3,
"selected": false,
"text": "PS C:\\Users\\Administrator> nslookup nuget\nServer: ad-01.docs.com\nAddress: 192.168.10.20\n\nName: nuget.docs.com\nAddress: 192.168.10.17\n PS C:\\Users\\Administrator> ping nuget\nPing request could not find host nuget. Please check the name and try again.\n PS C:\\Users\\Administrator> ping nuget.docs.com\n\nPinging nuget.docs.com [192.168.70.17] with 32 bytes of data:\nReply from 192.168.10.17: bytes=32 time=1ms TTL=127\nReply from 192.168.10.17: bytes=32 time=2ms TTL=127\nReply from 192.168.10.17: bytes=32 time=2ms TTL=127\nReply from 192.168.10.17: bytes=32 time=2ms TTL=127\n\nPing statistics for 192.168.10.17:\n Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\nApproximate round trip times in milli-seconds:\n Minimum = 1ms, Maximum = 2ms, Average = 1ms\n"
},
{
"answer_id": 31359295,
"author": "james smith",
"author_id": 5054042,
"author_profile": "https://Stackoverflow.com/users/5054042",
"pm_score": 0,
"selected": false,
"text": "IPCONFIG /ALL\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42088/"
] |
330,405 | <p>If I have a table where <strong>the cells in a column should not have the same values</strong>, how do I check this and update? (I know I can set constraints in the settings, but I don't want to do that.)</p>
<p>Say the column name is called <em>unique hash name</em> and contains </p>
<pre>
Peter
Peter
Peter
Dave
Dave
</pre>
<p>and so on. I want that to transform to:</p>
<pre>
Peter
Peter1
Peter2
Dave
Dave1
</pre>
<p>What is the T-SQL for SQL Server to do that?</p>
<p><strong>Update</strong>: For clarity's sake, let's call the table "Persons" and the cell I want unique "UniqueName". Could you make it a SELECT-statement, so I can test the result before updating. And I am using <strong>SQL Server 2005 and above</strong>.</p>
| [
{
"answer_id": 330695,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": true,
"text": "UPDATE Persons SET UniqueName = temp.DeDupded FROM\n (SELECT ID,\n CASE WHEN ROW_NUMBER() OVER\n (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName\n ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER()\n OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded\n FROM Persons) temp\nWHERE Persons.ID = temp.ID\n SELECT ID,\n CASE WHEN ROW_NUMBER() OVER\n (PARTITION BY UniqueName ORDER BY UniqueName) = 1 THEN UniqueName\n ELSE UniqueName + CONVERT(VARCHAR, ROW_NUMBER()\n OVER (PARTITION BY UniqueName ORDER BY UniqueName)-1) END AS DeDupded\nFROM Persons\n CREATE TABLE #Persons ( ID INT IDENTITY(1, 1), UniqueName VARCHAR(100) )\n\nINSERT INTO #Persons VALUES ('Bob')\nINSERT INTO #Persons VALUES ('Bob')\nINSERT INTO #Persons VALUES ('Bob')\nINSERT INTO #Persons VALUES ('John')\nINSERT INTO #Persons VALUES ('John')\n\nSELECT\n ID,\n CASE WHEN Position = 0 THEN UniqueName\n ELSE UniqueName + (CONVERT(VARCHAR, Position))\n END AS UniqueName\nFROM\n (SELECT\n ID,\n UniqueName,\n (SELECT COUNT(*) FROM #Persons p2 WHERE\n p1.UniqueName = p2.UniqueName AND p1.ID > p2.ID) AS Position\n FROM\n #Persons p1) _temp\n\nDROP TABLE #Persons\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2429/"
] |
330,427 | <p>I want to develop JavaScript on my Windows machine. Do you know a browser where I can turn off <em>Same Origin Policy</em> so I can develop locally? Firefox would be optimal.</p>
<p>Or if you know a proxy I could use for a SOAP/WSDL site it would be great too.</p>
<p>I am trying to work with the <a href="http://www.codeplex.com/JavaScriptSoapClient" rel="noreferrer">JavaSCript SOAP Client</a>.</p>
| [
{
"answer_id": 2771363,
"author": "miek",
"author_id": 102170,
"author_profile": "https://Stackoverflow.com/users/102170",
"pm_score": 4,
"selected": false,
"text": "if (navigator.userAgent.indexOf(\"Firefox\") != -1) {\n try {\n netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n } \n catch (e) {\n alert(\"Permission UniversalBrowserRead denied -- not running Mozilla?\");\n }\n}\n --disable-web-security"
},
{
"answer_id": 6577383,
"author": "user828878",
"author_id": 828878,
"author_profile": "https://Stackoverflow.com/users/828878",
"pm_score": 3,
"selected": false,
"text": "netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n"
},
{
"answer_id": 39334972,
"author": "Johann Echavarria",
"author_id": 2391782,
"author_profile": "https://Stackoverflow.com/users/2391782",
"pm_score": 0,
"selected": false,
"text": "--user-data-dir chromium-browser --disable-web-security --user-data-dir\n"
},
{
"answer_id": 56391406,
"author": "Miftah Mizwar",
"author_id": 5273989,
"author_profile": "https://Stackoverflow.com/users/5273989",
"pm_score": 1,
"selected": false,
"text": "open -a Google\\ Chrome --args --disable-web-security --user-data-dir\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19929/"
] |
330,444 | <p>I've got a MenuItem whos ItemsSource is databound to a simple list of strings, its showing correctly, but I'm struggling to see how I can handle click events for them!</p>
<p>Here's a simple app that demonstrates it:</p>
<pre><code><Window x:Class="WPFDataBoundMenu.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">
<Grid>
<Menu>
<MenuItem Header="File" Click="MenuItem_Click" />
<MenuItem Header="My Items" ItemsSource="{Binding Path=MyMenuItems}" />
</Menu>
</Grid>
</code></pre>
<p></p>
<pre><code>using System.Collections.Generic;
using System.Windows;
namespace WPFDataBoundMenu
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public List<string> MyMenuItems { get; set;}
public Window1()
{
InitializeComponent();
MyMenuItems = new List<string> { "Item 1", "Item 2", "Item 3" };
DataContext = this;
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("how do i handle the other clicks?!");
}
}
}
</code></pre>
<p>Many thanks!</p>
<p>Chris.</p>
| [
{
"answer_id": 330566,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 3,
"selected": false,
"text": "<MenuItem Header=\"My Items\" ItemsSource=\"{Binding Path=MyMenuItems}\">\n <MenuItem.ItemContainerStyle>\n <Style TargetType=\"MenuItem\">\n <Setter Property=\"Command\" Value=\"{x:Static local:MyCommands.MyCommand}\"/>\n <Setter Property=\"CommandParameter\" Value=\"{Binding SomeProperty}\"/>\n </Style>\n </MenuItem.ItemContainerStyle>\n</MenuItem>\n SomeProperty MyMenuItems SomeProperty"
},
{
"answer_id": 330578,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 5,
"selected": true,
"text": "<MenuItem Header=\"My Items\" ItemsSource=\"{Binding Path=MyMenuItems}\" Click=\"DataBoundMenuItem_Click\" />\n private void DataBoundMenuItem_Click(object sender, RoutedEventArgs e)\n{\n MenuItem obMenuItem = e.OriginalSource as MenuItem;\n MessageBox.Show( String.Format(\"{0} just said Hi!\", obMenuItem.Header));\n}\n"
},
{
"answer_id": 19178803,
"author": "mdn",
"author_id": 2154510,
"author_profile": "https://Stackoverflow.com/users/2154510",
"pm_score": 1,
"selected": false,
"text": "private void DataBoundMenuItem_Click(object sender, RoutedEventArgs e)\n{\n // get menu item with ItemsSource bound\n var myItemsMenuItems = sender as MenuItem; \n\n // get submenu clicked item constructed from MyMenuItems collection\n var myItemsMenuSubItem = e.OriginalSource as MenuItem; \n\n // get underlying MyMenuItems collection item\n var o = myItemsMenuItems\n .ItemContainerGenerator\n .ItemFromContainer(myItemsMenuSubItem);\n // convert to MyMenuItems type ... in our case string\n var itemObj = o as (string);\n\n // TODO some processing\n}\n"
},
{
"answer_id": 34856428,
"author": "amnesyc",
"author_id": 875130,
"author_profile": "https://Stackoverflow.com/users/875130",
"pm_score": 0,
"selected": false,
"text": "<MenuItem Header=\"My Items\" ItemsSource=\"{Binding Path=MyMenuItems}\" Click=\"MenuItem_Click\">\n <MenuItem.ItemContainerStyle>\n <Style TargetType=\"MenuItem\">\n <Setter Property=\"CommandParameter\" Value=\"{Binding}\" />\n </Style>\n </MenuItem.ItemContainerStyle>\n</MenuItem>\n private void MenuItem_Click(object sender, RoutedEventArgs e)\n{\n var item = ((MenuItem)e.OriginalSource).CommandParameter; \n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26759/"
] |
330,447 | <p>How can I compile a .cs file into a DLL?</p>
<p>My project name is WA. In my <code>bin</code> folder after the compilation, I found:</p>
<ul>
<li><code>WA.exe</code></li>
<li><code>WA.vshost.exe</code></li>
<li><code>WA.pdb</code></li>
</ul>
| [
{
"answer_id": 330450,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 4,
"selected": false,
"text": "csc /t:library source.cs -> source.dll\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201406/"
] |
330,458 | <p>Is there a clean and OS independent way to determine the local machine's IP addresses from Perl?</p>
<p>So far I have found the following solutions:</p>
<ul>
<li><p>parse the output of ifconfig and ipconfig (hard, different windows versions have different ipconfig outputs)</p></li>
<li><p>establish a network connection to a well-known IP and examine the socket's local IP address (won't work if I can't establish a connection and will determine only one IP address)</p></li>
</ul>
<p>Any better suggestion?</p>
| [
{
"answer_id": 330564,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "Sys::Hostname use Sys::Hostname;\nuse Socket;\nmy $addr = inet_ntoa((gethostbyname(hostname))[4]);\nprint \"$addr\\n\";\n"
},
{
"answer_id": 330641,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 5,
"selected": true,
"text": "use Net::Address::IP::Local;\n\n# Get the local system's IP address that is \"en route\" to \"the internet\":\nmy $address = Net::Address::IP::Local->public;\n"
},
{
"answer_id": 11954926,
"author": "Tommy Stanton",
"author_id": 1265245,
"author_profile": "https://Stackoverflow.com/users/1265245",
"pm_score": 4,
"selected": false,
"text": "#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nuse IO::Socket::INET;\n\nmy $local_ip_address = get_local_ip_address();\n\nprint \"$local_ip_address\\n\";\n\n# This idea was stolen from Net::Address::IP::Local::connected_to()\nsub get_local_ip_address {\n my $socket = IO::Socket::INET->new(\n Proto => 'udp',\n PeerAddr => '198.41.0.4', # a.root-servers.net\n PeerPort => '53', # DNS\n );\n\n # A side-effect of making a socket connection is that our IP address\n # is available from the 'sockhost' method\n my $local_ip_address = $socket->sockhost;\n\n return $local_ip_address;\n}\n get_local_ip_address() Net::Address::IP::Local->public_ipv4 PeerAddr"
},
{
"answer_id": 12354223,
"author": "dolmen",
"author_id": 328115,
"author_profile": "https://Stackoverflow.com/users/328115",
"pm_score": 3,
"selected": false,
"text": "perl -MIO::Interface::Simple '-Esay $_->address for grep { $_->is_running && defined $_->address } IO::Interface::Simple->interfaces'\n $_->is_loopback"
},
{
"answer_id": 22024335,
"author": "Matt",
"author_id": 3352877,
"author_profile": "https://Stackoverflow.com/users/3352877",
"pm_score": 0,
"selected": false,
"text": "foreach (split(/\\r?\\n/,`netstat -r`))\n{\n next unless /^\\s+0.0.0.0/;\n @S = split(/\\s+/); \n # $S[3] = Default Gateway\n # $S[4] = Main IP\n}\n"
},
{
"answer_id": 41918817,
"author": "PodTech.io",
"author_id": 1842743,
"author_profile": "https://Stackoverflow.com/users/1842743",
"pm_score": -1,
"selected": false,
"text": "hostname -i\nhostname -I\nls /sys/class/net\nip -f inet addr show eth0| grep -Po 'inet \\K[\\d.]+'\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] |
330,461 | <p>How do I get the battery status on an iPhone?</p>
| [
{
"answer_id": 2605569,
"author": "Paresh Thakor",
"author_id": 1149180,
"author_profile": "https://Stackoverflow.com/users/1149180",
"pm_score": 6,
"selected": true,
"text": "UIDevice *myDevice = [UIDevice currentDevice];\n[myDevice setBatteryMonitoringEnabled:YES];\nfloat batLeft = [myDevice batteryLevel];\nint i=[myDevice batteryState];\n\nint batinfo=(batLeft*100);\n\nNSLog(@\"Battry Level is :%d and Battery Status is :%d\",batinfo,i);\n\nswitch (i)\n{\n case UIDeviceBatteryStateUnplugged:\n {\n [BCStatus setText:NSLocalizedString(@\"UnpluggedKey\", @\"\")];\n break;\n }\n case UIDeviceBatteryStateCharging:\n {\n [BCStatus setText:NSLocalizedString(@\"ChargingKey\", @\"\")];\n break;\n }\n case UIDeviceBatteryStateFull:\n {\n [BCStatus setText:NSLocalizedString(@\"FullKey\", @\"\")];\n break;\n }\n default:\n {\n [BCStatus setText:NSLocalizedString(@\"UnknownKey\", @\"\")];\n break;\n }\n}\n"
},
{
"answer_id": 12733002,
"author": "BadPirate",
"author_id": 285694,
"author_profile": "https://Stackoverflow.com/users/285694",
"pm_score": 0,
"selected": false,
"text": "NSString *statusString(void)\n{\n UIDevice *device = [UIDevice currentDevice];\n NSString *batteryStateString = nil;\n switch(device.batteryState)\n {\n case UIDeviceBatteryStateUnplugged: batteryStateString = @\"Unplugged\"; break;\n case UIDeviceBatteryStateCharging: batteryStateString = @\"Charging\"; break;\n case UIDeviceBatteryStateFull: batteryStateString = @\"Full\"; break;\n default: batteryStateString = @\"Unknown\"; break;\n }\n\n [device setBatteryMonitoringEnabled:YES];\n NSString *statusString = [NSString stringWithFormat:@\"Battery Level - %d%%, Battery State - %@\",\n (int)round(device.batteryLevel * 100), batteryStateString];\n [device setBatteryMonitoringEnabled:NO];\n return statusString;\n}\n"
},
{
"answer_id": 21227051,
"author": "Has AlTaiar",
"author_id": 1570662,
"author_profile": "https://Stackoverflow.com/users/1570662",
"pm_score": 2,
"selected": false,
"text": "MonoTouch try\n{\n UIDevice.CurrentDevice.BatteryMonitoringEnabled = true;\n _Battery.Level = (int)(UIDevice.CurrentDevice.BatteryLevel * IOSBatteryLevelScalingFactor);\n _Battery.State = UIDevice.CurrentDevice.BatteryState;\n}\ncatch (Exception e)\n{\n ExceptionHandler.HandleException(e, \"BatteryState.Update\");\n throw new BatteryUpdateException();\n}\nfinally\n{\n UIDevice.CurrentDevice.BatteryMonitoringEnabled = false;\n}\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42078/"
] |
330,471 | <p>Explain why a nullable int can't be assigned the value of null e.g</p>
<pre><code>int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
</code></pre>
<p>What's wrong with that code?</p>
| [
{
"answer_id": 330484,
"author": "Harry Steinhilber",
"author_id": 6118,
"author_profile": "https://Stackoverflow.com/users/6118",
"pm_score": 9,
"selected": true,
"text": "int? accom = (accomStr == \"noval\" ? (int?)null : Convert.ToInt32(accomStr));\n"
},
{
"answer_id": 330490,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 6,
"selected": false,
"text": "int? accom = (accomStr == \"noval\" ? null : (int?)Convert.ToInt32(accomStr));\n"
},
{
"answer_id": 3784674,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "int? accom = (accomStr == \"noval\" ? Convert.DBNull : Convert.ToInt32(accomStr); \n"
},
{
"answer_id": 10072721,
"author": "tenss",
"author_id": 1321786,
"author_profile": "https://Stackoverflow.com/users/1321786",
"pm_score": 1,
"selected": false,
"text": "myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40623/"
] |
330,482 | <p>I was wondering if anyone has a good solution to a problem I've encountered numerous times during the last years.</p>
<p>I have a shopping cart and my customer explicitly requests that it's order is significant. So I need to persist the order to the DB.</p>
<p>The obvious way would be to simply insert some OrderField where I would assign the number 0 to N and sort it that way.</p>
<p>But doing so would make reordering harder and I somehow feel that this solution is kinda fragile and will come back at me some day.</p>
<p>(I use C# 3,5 with NHibernate and SQL Server 2005)</p>
<p>Thank you </p>
| [
{
"answer_id": 330510,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 3,
"selected": false,
"text": "SELECT"
},
{
"answer_id": 10356675,
"author": "Kickaha",
"author_id": 1318601,
"author_profile": "https://Stackoverflow.com/users/1318601",
"pm_score": 6,
"selected": false,
"text": "CREATE TABLE myitems (Myitem TEXT, id INTEGER PRIMARY KEY, orderindex NUMERIC);\n DELETE FROM myitems WHERE orderindex=6; \nUPDATE myitems SET orderindex = (orderindex - 1) WHERE orderindex > 6;\n UPDATE myitems SET orderindex = 0 WHERE orderindex = 4;\nUPDATE myitems SET orderindex = 4 WHERE orderindex = 7;\nUPDATE myitems SET orderindex = 7 WHERE orderindex = 0;\n UPDATE myitems SET orderindex = (orderindex + 1) WHERE orderindex > 2;\n INSERT INTO myitems (Myitem,orderindex) values (\"MytxtitemHere\",3)\n"
},
{
"answer_id": 27649934,
"author": "yglodt",
"author_id": 272180,
"author_profile": "https://Stackoverflow.com/users/272180",
"pm_score": -1,
"selected": false,
"text": "Hibernate @OneToMany Map List @OneToMany(fetch = FetchType.EAGER, mappedBy = \"rule\", cascade = CascadeType.ALL)\n@MapKey(name = \"position\")\n@OrderBy(\"position\")\nprivate Map<Integer, RuleAction> actions = LazyMap.decorate(new LinkedHashMap<>(), FactoryUtils.instantiateFactory(RuleAction.class, new Class[] { Rule.class }, new Object[] { this }));\n position RuleAction"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
] |
330,493 | <p>In many places in our code we have collections of objects, from which we need to create a comma-separated list. The type of collection varies: it may be a DataTable from which we need a certain column, or a List<Customer>, etc.</p>
<p>Now we loop through the collection and use string concatenation, for example:</p>
<pre><code>string text = "";
string separator = "";
foreach (DataRow row in table.Rows)
{
text += separator + row["title"];
separator = ", ";
}
</code></pre>
<p>Is there a better pattern for this? Ideally I would like an approach we could reuse by just sending in a function to get the right field/property/column from each object.</p>
| [
{
"answer_id": 330522,
"author": "Matt Howells",
"author_id": 16881,
"author_profile": "https://Stackoverflow.com/users/16881",
"pm_score": 4,
"selected": false,
"text": "static string ToCsv<T>(IEnumerable<T> things, Func<T, string> toStringMethod)\n{\n StringBuilder sb = new StringBuilder();\n\n foreach (T thing in things)\n sb.Append(toStringMethod(thing)).Append(',');\n\n return sb.ToString(0, sb.Length - 1); //remove trailing ,\n}\n DataTable dt = ...; //datatable with some data\nConsole.WriteLine(ToCsv(dt.Rows, row => row[\"ColName\"]));\n List<Customer> customers = ...; //assume Customer has a Name property\nConsole.WriteLine(ToCsv(customers, c => c.Name));\n"
},
{
"answer_id": 330525,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 3,
"selected": false,
"text": "public string Concat(IEnumerable<string> stringList)\n{\n StringBuilder textBuilder = new StringBuilder();\n string separator = String.Empty;\n foreach(string item in stringList)\n {\n textBuilder.Append(separator);\n textBuilder.Append(item);\n separator = \", \";\n }\n return textBuilder.ToString();\n}\n"
},
{
"answer_id": 330546,
"author": "Hosam Aly",
"author_id": 41283,
"author_profile": "https://Stackoverflow.com/users/41283",
"pm_score": 4,
"selected": true,
"text": "// using System.Collections;\n// using System.Collections.Generic;\n// using System.Linq\n\npublic delegate string Indexer<T>(T obj);\n\npublic static string concatenate<T>(IEnumerable<T> collection, Indexer<T> indexer, char separator)\n{\n StringBuilder sb = new StringBuilder();\n foreach (T t in collection) sb.Append(indexer(t)).Append(separator);\n return sb.Remove(sb.Length - 1, 1).ToString();\n}\n\n// version for non-generic collections\npublic static string concatenate<T>(IEnumerable collection, Indexer<T> indexer, char separator)\n{\n StringBuilder sb = new StringBuilder();\n foreach (object t in collection) sb.Append(indexer((T)t)).Append(separator);\n return sb.Remove(sb.Length - 1, 1).ToString();\n}\n\n// example 1: simple int list\nstring getAllInts(IEnumerable<int> listOfInts)\n{\n return concatenate<int>(listOfInts, Convert.ToString, ',');\n}\n\n// example 2: DataTable.Rows\nstring getTitle(DataRow row) { return row[\"title\"].ToString(); }\nstring getAllTitles(DataTable table)\n{\n return concatenate<DataRow>(table.Rows, getTitle, '\\n');\n}\n\n// example 3: DataTable.Rows without Indexer function\nstring getAllTitles(DataTable table)\n{\n return concatenate<DataRow>(table.Rows, r => r[\"title\"].ToString(), '\\n');\n}\n"
},
{
"answer_id": 330560,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 7,
"selected": false,
"text": "string.Join(\", \", Array.ConvertAll(somelist.ToArray(), i => i.ToString()))\n"
},
{
"answer_id": 536997,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "string strTest = \"1,2,4,6\";\nstring[] Nums = strTest.Split(',');\nConsole.Write(Nums.Aggregate<string>((first, second) => first + \",\" + second));\n//OUTPUT:\n//1,2,4,6\n"
},
{
"answer_id": 1088092,
"author": "BigBlondeViking",
"author_id": 119910,
"author_profile": "https://Stackoverflow.com/users/119910",
"pm_score": 2,
"selected": false,
"text": "public static string ToCsv<T>(this IEnumerable<T> things, Func<T, string> toStringMethod)\n var list = Session.Find(\"from User u where u.IsActive = true\").Cast<User>();\n\nreturn list.ToCsv(i => i.Email);\n"
},
{
"answer_id": 2661323,
"author": "Ian Mercer",
"author_id": 224370,
"author_profile": "https://Stackoverflow.com/users/224370",
"pm_score": 3,
"selected": false,
"text": "string.Join(\", \", table.Rows.Select(r => r[\"title\"]))"
},
{
"answer_id": 5195810,
"author": "Umang Patel",
"author_id": 453159,
"author_profile": "https://Stackoverflow.com/users/453159",
"pm_score": 4,
"selected": false,
"text": "Select<Func<>> List<string> fruits = new List<string>();\nfruits.Add(\"Mango\");\nfruits.Add(\"Banana\");\nfruits.Add(\"Papaya\");\n\nstring commaSepFruits = string.Join(\",\", fruits.Select(f => \"'\" + f + \"'\"));\nConsole.WriteLine(commaSepFruits);\n\nList<int> ids = new List<int>();\nids.Add(1001);\nids.Add(1002);\nids.Add(1003);\n\nstring commaSepIds = string.Join(\",\", ids);\nConsole.WriteLine(commaSepIds);\n\nList<Customer> customers = new List<Customer>();\ncustomers.Add(new Customer { Id = 10001, Name = \"John\" });\ncustomers.Add(new Customer { Id = 10002, Name = \"Robert\" });\ncustomers.Add(new Customer { Id = 10002, Name = \"Ryan\" });\n\nstring commaSepCustIds = string.Join(\", \", customers.Select(cust => cust.Id));\nstring commaSepCustNames = string.Join(\", \", customers.Select(cust => \"'\" + cust.Name + \"'\"));\n\nConsole.WriteLine(commaSepCustIds);\nConsole.WriteLine(commaSepCustNames);\n\nConsole.ReadLine();\n"
},
{
"answer_id": 10552595,
"author": "toddmo",
"author_id": 1045881,
"author_profile": "https://Stackoverflow.com/users/1045881",
"pm_score": 0,
"selected": false,
"text": "string text = string.Join(\", \", Array.ConvertAll(table.Rows.ToArray(), i => i[\"title\"]));\n"
},
{
"answer_id": 50547878,
"author": "Sapan Ghafuri",
"author_id": 2175997,
"author_profile": "https://Stackoverflow.com/users/2175997",
"pm_score": 2,
"selected": false,
"text": "string.Join(\", \", contactsCollection.Select(i => i.FirstName));\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9449/"
] |
330,496 | <p>I'm busy writing a class that monitors the status of RAS connections. I need to test to make sure that the connection is not only connected, but also that it can communicate with my web service. Since this class will be used in many future projects, I'd like a way to test the connection to the webservice without knowing anything about it.</p>
<p>I was thinking of passing the URL to the class so that it at least knows where to find it. Pinging the server is not a sufficient test. It is possible for the server to be available, but the service to be offline.</p>
<p>How can I effectively test that I'm able to get a response from the web service?</p>
| [
{
"answer_id": 1013945,
"author": "Blue Toque",
"author_id": 116268,
"author_profile": "https://Stackoverflow.com/users/116268",
"pm_score": 4,
"selected": false,
"text": "public static bool ServiceExists(\n string url, \n bool throwExceptions, \n out string errorMessage)\n{\n try\n {\n errorMessage = string.Empty;\n\n // try accessing the web service directly via it's URL\n HttpWebRequest request = \n WebRequest.Create(url) as HttpWebRequest;\n request.Timeout = 30000;\n\n using (HttpWebResponse response = \n request.GetResponse() as HttpWebResponse)\n {\n if (response.StatusCode != HttpStatusCode.OK)\n throw new Exception(\"Error locating web service\");\n }\n\n // try getting the WSDL?\n // asmx lets you put \"?wsdl\" to make sure the URL is a web service\n // could parse and validate WSDL here\n\n }\n catch (WebException ex)\n { \n // decompose 400- codes here if you like\n errorMessage = \n string.Format(\"Error testing connection to web service at\" + \n \" \\\"{0}\\\":\\r\\n{1}\", url, ex);\n Trace.TraceError(errorMessage);\n if (throwExceptions)\n throw new Exception(errorMessage, ex);\n } \n catch (Exception ex)\n {\n errorMessage = \n string.Format(\"Error testing connection to web service at \" + \n \"\\\"{0}\\\":\\r\\n{1}\", url, ex);\n Trace.TraceError(errorMessage);\n if (throwExceptions)\n throw new Exception(errorMessage, ex);\n return false;\n }\n\n return true;\n}\n"
},
{
"answer_id": 22401552,
"author": "Berend Engelbrecht",
"author_id": 434122,
"author_profile": "https://Stackoverflow.com/users/434122",
"pm_score": 0,
"selected": false,
"text": " HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL + \"?disco\");\n request.ClientCertificates.Add(\n new X509Certificate2(@\"c:\\mycertpath\\mycert.pfx\", \"<privatekeypassword>\")); // If server requires client certificate\n request.Timeout = 300000; // 5 minutes\n using (WebResponse response = request.GetResponse())\n using (Stream stream = response.GetResponseStream())\n using (StreamReader sr = new StreamReader(stream, Encoding.UTF8))\n {\n XmlDocument xd = new XmlDocument();\n xd.LoadXml(sr.ReadToEnd());\n return xd.DocumentElement.ChildNodes.Count > 0;\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6389/"
] |
330,497 | <p>I just stumbled across this bug in some legacy code:</p>
<pre><code>class MyAPIHandler
{
private:
int handle;
public:
void MyApiHandler() // default constructor
{
handle = 42;
};
};
</code></pre>
<p>It compiles fine, with no warnings - but the behaviour wasn't what I intended, because the constructor name is misspelt. This by itself would have produced a warning about "function does not return a value", but I guess I was on autopilot and added a "void" return type to 'fix' this.</p>
<p>Now, the bugfix was easy, but my question is this:-</p>
<p>What techniques could I use to prevent this type of bug recurring? </p>
<p>Some languages require an explicit "constructor" keyword, which should make this problem obvious. Unit testing, obviously should also have caught it. What else can I do?</p>
| [
{
"answer_id": 330511,
"author": "Vilx-",
"author_id": 41360,
"author_profile": "https://Stackoverflow.com/users/41360",
"pm_score": 0,
"selected": false,
"text": "#define CONSTRUCTOR\n class MyAPIHandler\n{\n public:\n CONSTRUCTOR MyAPIHandler()\n {\n // Deep magic\n }\n};\n"
},
{
"answer_id": 330553,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": true,
"text": "MyApiHandler() // default constructor\n: handle(42)\n{\n}\n"
},
{
"answer_id": 330920,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 0,
"selected": false,
"text": "MyAPIHandler mah;\nBOOST_CHECK_EQUAL(mah.handle, 42);\n"
},
{
"answer_id": 331763,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 1,
"selected": false,
"text": "class MyBase\n{\n // etc.\n virtual void doSomething() ;\n} ;\n\nclass MyDerived : public MyBase\n{\n // etc.\n virtual void DoSomething() ;\n} ;\n bool isOk(int value) { /* etc. */ }\nbool isOK(double value) { /* etc. */ }\n\nvoid doSomething(int value)\n{\n if(isOK(value)) // isOK(double) will be called\n {\n // Etc.\n }\n}\n"
},
{
"answer_id": 332177,
"author": "Carl",
"author_id": 13760,
"author_profile": "https://Stackoverflow.com/users/13760",
"pm_score": 0,
"selected": false,
"text": "class CHANGETHIS\n{\n public: \n CHANGETHIS();\n ~CHANGETHIS();\n}\n#error \"Finish this class definition\"\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
] |
330,500 | <p>This is a Windows Console application (actually a service) that a previous guy built 4 years ago and is installed and running. I now need to make some changes but can't even build the current version! Here is the build output:</p>
<pre><code>--------------------Configuration: MyApp - Win32 Debug--------------------
Compiling resources...
Compiling...
Main.cpp
winsock.cpp
Linking...
LINK : warning LNK4098: defaultlib "LIBCMTD" conflicts with use of other libs; use /NODEFAULTLIB:library
Main.obj : error LNK2001: unresolved external symbol _socket_dontblock
Debug/MyApp.exe : fatal error LNK1120: 1 unresolved externals
Error executing link.exe.
MyApp.exe - 2 error(s), 1 warning(s)
--------------------------------------------------------------------------
</code></pre>
<p>If I use <code>/NODEFAULTLIB</code> then I get loads of errors. The code does not actually use <code>_socket_noblock</code> but I can't find anything on it on the 'net. Presumably it is used by some library I am linking to but I don't know what library it is in.</p>
<p>--- Alistair.</p>
| [
{
"answer_id": 330531,
"author": "user41013",
"author_id": 41013,
"author_profile": "https://Stackoverflow.com/users/41013",
"pm_score": 2,
"selected": true,
"text": "_socket_noblock socket_noblock"
},
{
"answer_id": 330540,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 2,
"selected": false,
"text": "_socket_noblock"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41013/"
] |
330,529 | <p>What is the difference between the selectitem and selectitems tags in jsf?</p>
| [
{
"answer_id": 330552,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "selectitem selectitems SelectItem UISelectItem <h:selectOneMenu id=\"list1\">\n <f:selectItem itemLabel=\"Option 1\" itemValue=\"1\"></f:selectItem>\n</h:selectOneMenu>\n <select id=\"list1\" name=\"list1\" size=\"1\">\n <option value=\"1\">Option 1</option>\n</select>\n SelectItems UISelectItems <h:selectManyListbox id=\"list\">\n <f:selectItems value=\"#{optionBean.optionList}\"></f:selectItem>\n</h:selectManyListbox>\n <select id=\"list\" name=\"list\" multiple=\"true\" size=\"-2147483648\">\n <option value=\"1\">Option 1</option>\n <option value=\"2\">Option 2</option>\n <option value=\"3\">Option 3</option>\n</select>\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40933/"
] |
330,532 | <p>I'm looking for a complete solution to a automated "building" and testing of PHP application. I came across PhpUnderControl, a solution for running automated application builds created around Cruise Control.</p>
<p>Unfortunately PhpUC is still in it's early stages of development and I can't get it to work on windows box.</p>
<p>After few hours of trying I gave up on phpUc. I'm now trying to use Cruise Control alone. It works just fine when it comes to running whole build process. Every command I put into ant's build file runs ok.</p>
<p>The only problem I've got is that Cruise Control won't merge logs from run builds into project log file, therefore I'm not able to see any build results. But the sample project in Cruise control works ok, logs for builds are merged into project's log.</p>
<p>I'm wondering if Cruise Control is able to merge logs created by PHPUnit (in XML format) into project log or is it working for Java's JUnit files only. Has anyone tried to use Cruise Control alone on a php project?</p>
<p>here's the log section of project's configuration (config.xml):</p>
<pre><code><log dir="logs/${project.name}">
<merge dir="projects/${project.name}/build/logs/"/>
</log>
</code></pre>
<p>This is copy-pasted + paths changed from Cruise Control's sample project.</p>
<p>Any thoughts anyone please.</p>
<p>Thanks</p>
| [
{
"answer_id": 9148587,
"author": "VDH",
"author_id": 1190494,
"author_profile": "https://Stackoverflow.com/users/1190494",
"pm_score": 1,
"selected": false,
"text": " <log type=\"junit\" target=\"...../cruisecontrol-bin-2.8.4/projects/<projname>/build/logs/logfile.xml\" logIncompleteSkipped=\"false\"/>\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38769/"
] |
330,542 | <p>I'd like the iPhone virtual keyboard to appear pre-set to a particular language (Russian for example) when the user taps a UITextField. Is there a way to do this in Cocoa code?</p>
| [
{
"answer_id": 1612457,
"author": "slatvick",
"author_id": 72766,
"author_profile": "https://Stackoverflow.com/users/72766",
"pm_score": 2,
"selected": false,
"text": "self.searchBar.keyboardType = UIKeyboardTypeURL;\n"
},
{
"answer_id": 5871456,
"author": "Nestor",
"author_id": 149533,
"author_profile": "https://Stackoverflow.com/users/149533",
"pm_score": 1,
"selected": false,
"text": "#import <Foundation/Foundation.h>\n#import <AudioToolbox/AudioToolbox.h>\n\n@interface KoreanOnlyInput : NSObject <UITextFieldDelegate>\n{\n NSMutableCharacterSet* koreanUnicode; \n}\n\n@end\n #import \"KoreanOnlyInput.h\"\n\n@implementation KoreanOnlyInput\n\n- (id)init\n{\n self = [super init];\n if (self) {\n // From http://www.unicodemap.org/ :\n // 0x1100 - 0x11FF : Hangul Jamo (256)\n // 0x3130 - 0x318F : Hangul Compatibility Jamo (96)\n // 0xAC00 - 0xD7A3 : Hangul Syllables (11172)\n\n koreanUnicode = [[NSMutableCharacterSet alloc] init];\n NSRange range;\n\n range.location = 0x1100;\n range.length = 1 + 0x11FF - range.location;\n [koreanUnicode addCharactersInRange:range];\n\n range.location = 0x3130;\n range.length = 1 + 0x318F - range.location;\n [koreanUnicode addCharactersInRange:range];\n\n range.location = 0xAC00;\n range.length = 1 + 0xD7A3 - range.location;\n [koreanUnicode addCharactersInRange:range];\n }\n return self;\n}\n\n- (void)dealloc\n{\n [koreanUnicode release];\n [super dealloc];\n}\n\n- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string\n{\n if ([string isEqualToString:@\"\\n\"])\n return YES;\n\n BOOL shouldChange = YES; \n for (int i=0; i<[string length]; i++)\n {\n if (![koreanUnicode characterIsMember:[string characterAtIndex:i]])\n shouldChange = NO;\n }\n\n if (!shouldChange)\n {\n AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);\n }\n\n return shouldChange;\n}\n\n@end\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42100/"
] |
330,543 | <p>I have this php code, with which I am trying to generate a popup window that will contain the contents of a html file, however after adding in the script tags, no html is displayed. I tried echoing out $row2, but the word array is printed to the screen and nothing else.</p>
<pre><code><?php
session_start();
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"];
else
die("You should have a 'cmd' parameter in your URL");
$pk = $_GET["pk"];
$con = mysql_connect("localhost","root","geheim");
if(!$con)
{
die('Connection failed because of' .mysql_error());
}
mysql_select_db("ebay",$con);
if($cmd=="GetAuctionData")
{
$sql="SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'";
$sql2="SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'";
$htmlset = mysql_query($sql2);
$row2 = mysql_fetch_array($htmlset);
echo $row2;
echo '<script>
function makewindows(){
child1 = window.open ("about:blank");
child1.document.write('.$row2["ARTICLE_DESC"].');
child1.document.close();
}
</script>';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
echo "<div id='leftlayer'>
<strong>Article Number</strong> ".$row['ARTICLE_NO']."
<p><strong>Article Name</strong></p> ".$row['ARTICLE_NAME']."
<p><strong>Subtitle</strong></p> ".$row['SUBTITLE']."
<p><strong>Username</strong></p> ".$row['USERNAME']."
<p><strong>Total Selling</strong></p> ".$row['QUANT_TOTAL']."
<p><strong>Total Sold</strong></p> ".$row['QUANT_SOLD']."
<p><strong>Category</strong></p> ".$row['CATEGORY']."
<p><strong>Highest Bidder</strong></p> ".$row['BEST_BIDDER_ID']."
</div>
<div class='leftlayer2'>
<strong>Current Bid</strong> ".$row['CURRENT_BID']."
<p><strong>Start Price</strong></p> ".$row['START_PRICE']."
<p><strong>Buyitnow Price</strong></p> ".$row['BUYITNOW_PRICE']."
<p><strong>Bid Count</strong></p> ".$row['BID_COUNT']."
<p><strong>Start Date</strong></p> ".$row['ACCESSSTARTS']."
<p><strong>End Date</strong></p> ".$row['ACCESSENDS']."
<p><strong>Original End</strong></p> ".$row['ACCESSORIGIN_END']."
<p><strong>Auction Type</strong></p> ".$row['AUCTION_TYPE']."
</div>
<div class='leftlayer2'>
<strong>Private Auction</strong></p> ".$row['PRIVATE_AUCTION']."
<p><strong>Paypal Accepted</strong></p> ".$row['PAYPAL_ACCEPT']."
<p><strong>Auction Watched</strong></p> ".$row['WATCH']."
<p><strong>Finished</strong></p> ".$row['FINISHED']."
<p><strong>Country</strong></p> ".$row['COUNTRYCODE']."
<p><strong>Location</strong></p> ".$row['LOCATION']."
<p><strong>Conditions</strong></p> ".$row['CONDITIONS']."
</div>
<div class='leftlayer2'>
<strong>Auction Revised</strong></p> ".$row['REVISED']."
<p><strong>Cancelled</strong></p> ".$row['PRE_TERMINATED']."
<p><strong>Shipping to</strong></p> ".$row['SHIPPING_TO']."
<p><strong>Fee Insertion</strong></p> ".$row['FEE_INSERTION']."
<p><strong>Fee Final</strong></p> ".$row['FEE_FINAL']."
<p><strong>Fee Listing</strong></p> ".$row['FEE_LISTING']."
<p><a href='#' onclick='makewindows(); return false;'>Click for full description </a></p>
</div>";
$lastImg = $row['PIC_URL'];
echo "<div id='rightlayer'>Picture Picture
<img src=".$lastImg.">
</div>";
}
}
mysql_close($con);
?>
</code></pre>
<p>edit: I have fixed the errors that Roborg pointed out, however the script will still not load and does not give a precise error.</p>
<p>i have updated the code above</p>
| [
{
"answer_id": 330550,
"author": "Gonzalo Quero",
"author_id": 40996,
"author_profile": "https://Stackoverflow.com/users/40996",
"pm_score": 0,
"selected": false,
"text": "<script>"
},
{
"answer_id": 330561,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "</script> child1.document.write('.$row2[\"ARTICLE_DESC\"].') child1.document.write(' . json_encode($row2[\"ARTICLE_DESC\"]) . '); json_encode() <a href='#' onclick=makewindows()> <a href='#' onclick='makewindows(); return false;'> return false"
},
{
"answer_id": 330760,
"author": "method",
"author_id": 40883,
"author_profile": "https://Stackoverflow.com/users/40883",
"pm_score": 0,
"selected": false,
"text": "print_r($row2);"
},
{
"answer_id": 330780,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "$row2 = mysql_fetch_array($htmlset);\n $row2 mysql_result resource $result , int $row [, mixed $field ] // get the first field of the first row\n$fieldVal = mysql_result($htmlset, 0);\n\n// get the third field\n$fieldVal = mysql_result($htmlset, 0, 2);\n\n// get the first field of the 2nd row\n$fieldVal = mysql_result($htmlset, 1);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
330,545 | <p>I have a page with 3 layers, one for navigation, one for database records and one for results. When I click on a database record, the results are displayed in the result layer via ajax. For navigation, the links will simply be different queries. I am wondering if it would make sense to have each different query be sent as ajax data and palced into the records layer, or rather to have the query appended to the php file each time. Which is the more efficient approach?</p>
| [
{
"answer_id": 330550,
"author": "Gonzalo Quero",
"author_id": 40996,
"author_profile": "https://Stackoverflow.com/users/40996",
"pm_score": 0,
"selected": false,
"text": "<script>"
},
{
"answer_id": 330561,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 3,
"selected": true,
"text": "</script> child1.document.write('.$row2[\"ARTICLE_DESC\"].') child1.document.write(' . json_encode($row2[\"ARTICLE_DESC\"]) . '); json_encode() <a href='#' onclick=makewindows()> <a href='#' onclick='makewindows(); return false;'> return false"
},
{
"answer_id": 330760,
"author": "method",
"author_id": 40883,
"author_profile": "https://Stackoverflow.com/users/40883",
"pm_score": 0,
"selected": false,
"text": "print_r($row2);"
},
{
"answer_id": 330780,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "$row2 = mysql_fetch_array($htmlset);\n $row2 mysql_result resource $result , int $row [, mixed $field ] // get the first field of the first row\n$fieldVal = mysql_result($htmlset, 0);\n\n// get the third field\n$fieldVal = mysql_result($htmlset, 0, 2);\n\n// get the first field of the 2nd row\n$fieldVal = mysql_result($htmlset, 1);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
330,562 | <p>My usage-scenario may seem a bit unusual, but here it is: When using vim (it's one of about 4 different editors I use regularly), I use it in two different situations. The first is via the GUI, in which I'll have multiple buffers and have some settings different than when I use it from the command-line (by testing "<code>if has('gui_running')</code>"). The other is when I need to do something short-and-quick, from the command-line, such as make a small change to a dot-file or other type of config.</p>
<p>What I would <em>like</em> to do, is have sessions enabled for the GUI, but have any command-line invocations ignore them. That is, I don't want to bring up the full existing session on a CL invocation, nor do I want it (and whatever buffer/file it involved) to alter the session that the GUI is using. As I'm fairly new to the post-vi-functionality of vim, I'm not really sure how to pull this off.</p>
| [
{
"answer_id": 330689,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 4,
"selected": true,
"text": ".gvimrc .vimrc .vimrc au VimLeave * mksession ~/.gvimsession\nau VimEnter * source ~/.gvimsession\n"
},
{
"answer_id": 5851557,
"author": "connermcd",
"author_id": 733685,
"author_profile": "https://Stackoverflow.com/users/733685",
"pm_score": 2,
"selected": false,
"text": "au VimLeave * mksession! ~/.gvimsession\nau VimEnter * source ~/.gvimsession\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6421/"
] |
330,569 | <p>Is there a way to find a node matched on part of a value.</p>
<p>If I have the following:</p>
<pre><code><competition id="100" name="Barclays Premier League"/>
<competition id="101" name="CocaCola Championship" />
<competition id="102" name="CocaCola League 1" />
</code></pre>
<p>Given the string "Premier League" or even "Prem", how would I match the correct node and get id 100.</p>
<p>I have managed this using for-each and contains, but this is very inefficient and does not work fast enough for our requirements.</p>
| [
{
"answer_id": 330583,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 5,
"selected": true,
"text": "//competition[contains(@name,'Prem')]\n"
},
{
"answer_id": 330840,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 3,
"selected": false,
"text": "//competition[contains(@name, 'Prem')]/@id"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
330,571 | <p>I have a DataGrid that looks like this (slightly simplified here):</p>
<pre><code><asp:DataGrid ID="grdQuotas" runat="server" AutoGenerateColumns="False">
<HeaderStyle CssClass="quotas-header" />
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
Max order level</HeaderTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMaxOrderLevel" runat="server" DataSourceID="xdsOrderLevel"
DataTextField="Text" DataValueField="Value" SelectedValue='<%# Bind("MaxOrderLevel") %>'>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
<asp:XmlDataSource ID="xdsOrderLevel" runat="server" DataFile="~/App_Data/OrderLevels.xml">
</asp:XmlDataSource>
</code></pre>
<p>In my <code>Page_Load</code> event handler I am creating a <code>DataTable</code> containing default values and <code>DataBind</code>ing it to the <code>DataGrid</code>.</p>
<p>The problem is that this is taking place <em>before</em> the <code>DropDownList</code> <strong>ddlMaxOrderLevel</strong> has been bound to its <code>DataSource</code>, so I get a runtime error telling me that the <code>SelectedValue</code> cannot be set.</p>
<p>If <strong>ddlMaxOrderLevel</strong> was not in a <code>DataGrid</code> I could just call <code>DataBind()</code> on it. However I cannot do that in this scenario - since it is in an <code>ItemTemplate</code>.</p>
<p>Can anyone suggest a workaround or alternate approach?</p>
| [
{
"answer_id": 330642,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": false,
"text": " protected void dg_ItemDataBound(object sender, DataGridItemEventArgs e)\n {\n if (e.Item.ItemType != ListItemType.Header && e.Item.ItemType != ListItemType.Footer)\n {\n DropDownList dl = (DropDownList)((DataGridItem)e.Item).FindControl(\"ddlMaxOrderLevel\");\n\n dl.DataSource = levels;\n dl.DataBind();\n\n dl.SelectedValue = ((DataRowView)e.Item.DataItem)[\"number\"].ToString();\n\n\n }\n\n }\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39709/"
] |
330,585 | <p>Up till now we've been rewriting URL's using a custon 404 page: the url would not map to any file in the site, and we configured the IIS to send 404 error to a aspx page which redirected those url's to the correct URL.<br>
Now we want to stop using redirects, so after reading Scott Guthrie's article on Url Rewriting, I want to use the Application_BeginRequest in Global.asax. The thing is that a lot of our url's are not rewrites, and can get to the right place without any intervention. I'm worried that now every single request is going to have to go through the Application_BeginRequest method (even the un-rewritten url's), and I'm afraid it will slow down their loading time.<br>
What do you think? Is loading time an issue when using Application_BeginRequest?</p>
| [
{
"answer_id": 2243942,
"author": "adinas",
"author_id": 5754,
"author_profile": "https://Stackoverflow.com/users/5754",
"pm_score": 2,
"selected": false,
"text": "<modules runAllManagedModulesForAllRequests=\"true\">\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
330,590 | <p>I'm using a JComboBox with an ItemListener on it. When the value is changed, the itemStateChanged event is called twice. The first call, the ItemEvent is showing the original item selected. On the second time, it is showing the item that has been just selected by the user. Here's some tester code:</p>
<pre><code>public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItem("Four");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
System.out.println(e.getItem());
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
</code></pre>
<p>So when I changed the Combo box once from "One" to "Three" the console shows:<br><br></p>
<pre><code>One
Three
</code></pre>
<p>Is there a way I can tell using the ItemEvent maybe, that it's the second item (ie. the user selected item)? And if someone can explain why it gets called twice, that would be nice too!</p>
<p>Thanks</p>
| [
{
"answer_id": 330602,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 6,
"selected": true,
"text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\n\npublic class Tester {\n\n public Tester(){\n\n JComboBox box = new JComboBox();\n box.addItem(\"One\");\n box.addItem(\"Two\");\n box.addItem(\"Three\");\n box.addItem(\"Four\");\n\n box.addItemListener(new ItemListener(){\n public void itemStateChanged(ItemEvent e){\n System.out.println(e.getItem() + \" \" + e.getStateChange() );\n }\n });\n\n JFrame frame = new JFrame();\n frame.getContentPane().add(box);\n frame.pack();\n frame.setVisible(true);\n }\n\n public static void main(String [] args) {\n Tester tester = new Tester();\n }\n}\n"
},
{
"answer_id": 1167506,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "import java.awt.event.*;\n\njComboBox1.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n System.out.println(\"Hello\");\n }\n });\n"
},
{
"answer_id": 4507105,
"author": "Abdullah",
"author_id": 550926,
"author_profile": "https://Stackoverflow.com/users/550926",
"pm_score": -1,
"selected": false,
"text": "JComboBox.setFocusable(false)"
},
{
"answer_id": 5991418,
"author": "Hussain ",
"author_id": 752302,
"author_profile": "https://Stackoverflow.com/users/752302",
"pm_score": 2,
"selected": false,
"text": "public class Tester {\n\n private JComboBox box;\n\n public Tester() {\n\n box = new JComboBox();\n box.addItem(\"One\");\n box.addItem(\"Two\");\n box.addItem(\"Three\");\n box.addItem(\"Four\");\n\n box.addItemListener(new ItemListener() {\n\n public void itemStateChanged(ItemEvent e) {\n if (e.getStateChange() == 1) {\n\n JOptionPane.showMessageDialog(box, e.getItem());\n System.out.println(e.getItem());\n }\n }\n });\n\n JFrame frame = new JFrame();\n frame.getContentPane().add(box);\n frame.pack();\n frame.setVisible(true);\n }\n}\n"
},
{
"answer_id": 8782569,
"author": "qizer",
"author_id": 1137763,
"author_profile": "https://Stackoverflow.com/users/1137763",
"pm_score": 4,
"selected": false,
"text": " comboBox1.addItemListener(new ItemListener() {\n @Override\n public void itemStateChanged(ItemEvent e) {\n if(e.getStateChange() == ItemEvent.SELECTED) {\n comboBox1ItemStateChanged();\n }\n }\n });\n"
},
{
"answer_id": 20536327,
"author": "21stking",
"author_id": 1966096,
"author_profile": "https://Stackoverflow.com/users/1966096",
"pm_score": 3,
"selected": false,
"text": "private void dropDown_nameItemStateChanged(java.awt.event.ItemEvent evt) { \n\n\n if(evt.getStateChange() == ItemEvent.SELECTED)\n {\n String item = (String) evt.getItem();\n System.out.println(item);\n }\n\n}\n"
},
{
"answer_id": 41294861,
"author": "Kuldeep Melligeri",
"author_id": 1853256,
"author_profile": "https://Stackoverflow.com/users/1853256",
"pm_score": 0,
"selected": false,
"text": "dataMgr.MainInterface.jComboBoxPaymentStatusValueChangeHandle(MainInterface.java:1431), \ndataMgr.MainInterface.jComboBoxPaymentStatusItemStateChanged(MainInterface.java:1676), \ndataMgr.MainInterface.access$600(MainInterface.java:28), \ndataMgr.MainInterface$7.itemStateChanged(MainInterface.java:437), \njavax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223), \njavax.swing.JComboBox.selectedItemChanged(JComboBox.java:1271), \njavax.swing.JComboBox.contentsChanged(JComboBox.java:1330), \njavax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118), \njavax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93), \njavax.swing.JComboBox.setSelectedItem(JComboBox.java:576), javax.swing.JComboBox.setSelectedIndex(JComboBox.java:622), javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852), java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290), java.awt.Component.processMouseEvent(Component.java:6533), javax.swing.JComponent.processMouseEvent(JComponent.java:3324), javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501), java.awt.Component.processEvent(Component.java:6298), java.awt.Container.processEvent(Container.java:2236), java.awt.Component.dispatchEventImpl(Component.java:4889), java.awt.Container.dispatchEventImpl(Container.java:2294), java.awt.Component.dispatchEvent(Component.java:4711), java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888), java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525), java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466), java.awt.Container.dispatchEventImpl(Container.java:2280), java.awt.Window.dispatchEventImpl(Window.java:2746), java.awt.Component.dispatchEvent(Component.java:4711), java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758), java.awt.EventQueue.access$500(EventQueue.java:97), java.awt.EventQueue$3.run(EventQueue.java:709), java.awt.EventQueue$3.run(EventQueue.java:703), java.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86), java.awt.EventQueue$4.run(EventQueue.java:731), java.awt.EventQueue$4.run(EventQueue.java:729), java.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.awt.EventQueue.dispatchEvent(EventQueue.java:728), java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201), java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116), java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93), java.awt.EventDispatchThread.run(EventDispatchThread.java:82)]\n dataMgr.MainInterface.jComboBoxPaymentStatusValueChangeHandle(MainInterface.java:1431), \ndataMgr.MainInterface.jComboBoxPaymentStatusItemStateChanged(MainInterface.java:1676), \ndataMgr.MainInterface.access$600(MainInterface.java:28), \ndataMgr.MainInterface$7.itemStateChanged(MainInterface.java:437), \njavax.swing.JComboBox.fireItemStateChanged(JComboBox.java:1223), \njavax.swing.JComboBox.selectedItemChanged(JComboBox.java:1280), \njavax.swing.JComboBox.contentsChanged(JComboBox.java:1330), \njavax.swing.AbstractListModel.fireContentsChanged(AbstractListModel.java:118), \njavax.swing.DefaultComboBoxModel.setSelectedItem(DefaultComboBoxModel.java:93), \njavax.swing.JComboBox.setSelectedItem(JComboBox.java:576), \njavax.swing.JComboBox.setSelectedIndex(JComboBox.java:622), \njavax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:852), \njava.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290), \njava.awt.Component.processMouseEvent(Component.java:6533), \njavax.swing.JComponent.processMouseEvent(JComponent.java:3324), \njavax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:501), \njava.awt.Component.processEvent(Component.java:6298), java.awt.Container.processEvent(Container.java:2236), \njava.awt.Component.dispatchEventImpl(Component.java:4889), java.awt.Container.dispatchEventImpl(Container.java:2294), \njava.awt.Component.dispatchEvent(Component.java:4711), java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888), \njava.awt.LightweightDispatcher.processMouseEvent(Container.java:4525), java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466), \njava.awt.Container.dispatchEventImpl(Container.java:2280), java.awt.Window.dispatchEventImpl(Window.java:2746), \njava.awt.Component.dispatchEvent(Component.java:4711), java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758),\njava.awt.EventQueue.access$500(EventQueue.java:97), java.awt.EventQueue$3.run(EventQueue.java:709), \njava.awt.EventQueue$3.run(EventQueue.java:703), java.security.AccessController.doPrivileged(Native Method),\njava.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), \njava.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86), \njava.awt.EventQueue$4.run(EventQueue.java:731), java.awt.EventQueue$4.run(EventQueue.java:729), \njava.security.AccessController.doPrivileged(Native Method), java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76), java.awt.EventQueue.dispatchEvent(EventQueue.java:728), java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201), java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116), java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101), java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93), java.awt.EventDispatchThread.run(EventDispatchThread.java:82)]\n"
},
{
"answer_id": 44280016,
"author": "Junaid Khan",
"author_id": 6183777,
"author_profile": "https://Stackoverflow.com/users/6183777",
"pm_score": 2,
"selected": false,
"text": "box.addItemListener(new ItemListener(){\n public void itemStateChanged(ItemEvent e){\n if(e.getStateChange()== ItemEvent.SELECTED) {\n //this will trigger once only when actually the state is changed\n JOptionPane.showMessageDialog(null, \"Changed\");\n }\n }\n});\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21144/"
] |
330,601 | <p>Is there a way to make stack trace to display the whole generated SQL statement when there is an error instead just the first few characters of it?</p>
<p>This is what it currently displays</p>
<blockquote>
<p>...\Zend\Db\Adapter\Pdo\Abstract.php(220): Zend_Db_Adapter_Abstract->query('UPDATE "diction...', Array)</p>
</blockquote>
<p>..and I would like to see the whole update statement before sent to the db to track what is wrong with it.</p>
<p>Thanks for the help.
SWK</p>
| [
{
"answer_id": 332110,
"author": "Solid Rhino",
"author_id": 42111,
"author_profile": "https://Stackoverflow.com/users/42111",
"pm_score": 4,
"selected": false,
"text": "Zend_Debug::Dump($select);\nexit;\n $select = new Zend_Db_Select(Zend_Registry::get('db'));\n$select->from('string');\nZend_Debug::Dump($select->assemble());\nexit;\n // setup the database connection\n$db = Zend_Db::factory(Zend_Registry::get('config')->database->adapter,Zend_Registry::get('config')->database->params);\n\n// create a new profiler\nprofiler = new Zend_Db_Profiler_Firebug('All DB Queries');\n\n// enable profiling (this is only recommended in development mode, disable this in production mode)\n$profiler->setEnabled(true);\n// add the profiler to the database object\n$db->setProfiler($profiler);\n\n// setup the default adapter to use for database communication\nZend_Db_Table_Abstract::setDefaultAdapter($db);\n\n// register the database object to access it in other parts of the project\nZend_Registry::set('db',$db);\n\n/**\n*\n* This part is optional\n*\n* You can use this logger to log debug information to the firephp add-on for Firefox\n* This is handy for debugging but must be disabled in production mode\n*\n*/\n\n// create logger\n$logger = new Zend_Log();\n\n// create firebug writer\n$firebug_writer = new Zend_Log_Writer_Firebug();\n\n// add writer to logger\n$logger->addWriter($firebug_writer);\n\n// register the logger object to access it in other parts of the project\nZend_Registry::set('log',$logger);\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,609 | <p>I have an animation which moves some views around. When this animation completes I want the window to recalculate the keyview loop. My code is simmilar to the follow mock code:</p>
<pre><code>[NSAnimationContext beginGrouping];
[newView setAlpha: 0.0]; //hide newView
[self addSubView:newView];
//position the views
[[oldView animator] setFrame: newFrame1];
[[newView animator] setFrame: newFrame2];
[[newView animator] setAlpha: 1.0]; //fade-in newView
[NSAnimationContext endGrouping];
[[self window] recalculateKeyViewLoop];
</code></pre>
<p>The problem with this code is that <code>recalculateKeyViewLoop</code> is called before the views are in their new positions which means that the keyviewloop is wrong.</p>
<p>How do I fix this?</p>
<p>My first though is to call <code>recalculateKeyViewLoop</code> in a callback from when the animation ends but I can't figure out how to do this.</p>
| [
{
"answer_id": 331142,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 2,
"selected": false,
"text": "-animationForKey: CAAnimation"
},
{
"answer_id": 332464,
"author": "Ashley Clark",
"author_id": 4556,
"author_profile": "https://Stackoverflow.com/users/4556",
"pm_score": 3,
"selected": false,
"text": "setFrame: frameSize frameOrigin -animationForKey: animations CAAnimation *animation = [[view animationForKey:@\"frameOrigin\"] copy];\nanimation.delegate = self;\n[view setAnimations:[NSDictionary dictionaryWithObject:animation forKey:@\"frameOrigin\"]];\n"
},
{
"answer_id": 15201935,
"author": "lmirosevic",
"author_id": 399772,
"author_profile": "https://Stackoverflow.com/users/399772",
"pm_score": 0,
"selected": false,
"text": "NSWindow NSView CAAnimation *animation = [CABasicAnimation animation];\nanimation.delegate = self;\nself.window.animations = @{@\"frame\": animation};\n[[self.window animator] setFrame:NSMakeRect(0, 0, 400, 200) display:YES];\n animationDidStop:finished: self"
},
{
"answer_id": 17561999,
"author": "Jay Haase",
"author_id": 287343,
"author_profile": "https://Stackoverflow.com/users/287343",
"pm_score": 1,
"selected": false,
"text": "[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context){\n // Start some animations.\n [[myView animator] setFrameSize:newViewSize];\n [[myWindow animator] setFrame:newWindowFrame display:YES];\n} completionHandler:^{\n // This block will be invoked when all of the animations started above have completed or been cancelled.\n NSLog(@\"All done!\");\n}];\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
330,612 | <p>I have a table of time-series data of which I need to find all columns that contain at least one non-null value within a given time period. So far I am using the following query:</p>
<pre><code>select max(field1),max(field2),max(field3),...
from series where t_stamp between x and y
</code></pre>
<p>Afterwards I check each field of the result if it contains a non-null value. </p>
<p>The table has around 70 columns and a time period can contain >100k entries.</p>
<p>I wonder if there if there is a faster way to do this (using only standard sql). </p>
<p>EDIT:
Unfortunately, refactoring the table design is not an option for me.</p>
| [
{
"answer_id": 330626,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "COALESCE SELECT ... WHERE COALESCE(fild1, field2, field3) IS NOT NULL"
},
{
"answer_id": 330627,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 1,
"selected": false,
"text": "create table series (fieldno integer, t_stamp date);\n\nselect distinct fieldno from series where t_stamp between x and y;\n"
},
{
"answer_id": 330679,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "select count(field1),count(field2),count(field3),... \n from series where t_stamp between x and y\n"
},
{
"answer_id": 330681,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 0,
"selected": false,
"text": "SELECT CASE WHEN field1 IS NOT NULL THEN '' ELSE 'contains null' END AS field1_stat,\n CASE WHEN field2 IS NOT NULL THEN '' ELSE 'contains null' END AS field2_stat,\n... for every field to be checked\nFROM series\nWHERE foo IN bar\nGROUP BY CASE WHEN field1 IS NOT NULL THEN '' ELSE 'contains null' END,\n CASE WHEN field2 IS NOT NULL THEN '' ELSE 'contains null' END \n... etc\n"
},
{
"answer_id": 330766,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 1,
"selected": false,
"text": "select top 1 field1 from series where t_stamp between x and y and field1 is not null select top 1 field2 from series where t_stamp between x and y and field2 is not null select top 1 field3 from series where t_stamp between x and y and field3 is not null"
},
{
"answer_id": 330870,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 1,
"selected": false,
"text": "select 'field1' as fieldname from series \n where field1 is not null and t_stamp between x and y\nUNION\nselect 'field2' from series where field2 is not null \n... etc\n"
},
{
"answer_id": 331103,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 4,
"selected": true,
"text": "SELECT\n CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field1 IS NOT NULL) THEN 1 ELSE 0 END AS field1,\n CASE WHEN EXISTS (SELECT * FROM Series WHERE t_stamp BETWEEN @x AND @y AND field2 IS NOT NULL) THEN 1 ELSE 0 END AS field2,\n...\n"
}
] | 2008/12/01 | [
"https://Stackoverflow.com/questions/330612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33805/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.