qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
326,202
<p>What is a generic list manipulation function in C? (I saw this when I was going through some materials.)</p> <p>What is the difference between this function and a function which can accept elements of any kind?</p> <p>Are they same...? How can we implement them individually if they are not same?</p>
[ { "answer_id": 326211, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 4, "selected": true, "text": "typedef struct list_item list_item;\n\nstruct list_item\n{\n list_item *next;\n ...data for node...\n};\n ...data for node... void * typedef struct list list;\n\nstruct list\n{\n list *next;\n void *data;\n};\n void * void *car(list *lp); // Return the data for the first item on the list\nlist *cdr(list *lp); // Return the tail of the list\nlist *cons(list *lp1, list *lp2); // Construct a list from lists lp1 and lp2\n\nlist *cond(list *lp, void *data); // Append data item to list\n" }, { "answer_id": 326232, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "void* void* void* void* typedef struct list_node {\n struct list_node *next;\n void *data;\n} list_node;\n\nvoid list_insert(list_node *node, void *data) {\n // ...\n}\n #define DEFINE_LIST(type) \\\n typedef struct list_node_##type { \\\n struct list_node_##type *next; \\\n type data; \\\n }\n\n#define IMPLEMENT_LIST_INSERT(type) \\\n void list_##type##_insert(list_node_##type *node, type data) { \\\n ... \\\n }\n\nDEFINE_LIST(int); // defines struct list_node_int\nDEFINE_LIST(double); // defines struct list_node_double\nIMPLEMENT_LIST_INSERT(int); // defines list_int_insert\nIMPLEMENT_LIST_INSERT(double); // defines list_double_insert\n" }, { "answer_id": 327665, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "struct mystruct {\n ...\n /* Contains the next and prev pointers */\n struct list_head mylist;\n ...\n /* A single struct can be in several lists */\n struct list_head another_list;\n ...\n};\n\nstruct list_head mylist_head;\nstruct list_head another_list_head;\n struct list_head &(foo->mylist) &(foo->another_list) struct list_head struct list_head list_entry containter_of O(1)" }, { "answer_id": 11077360, "author": "pistonhead1", "author_id": 1462724, "author_profile": "https://Stackoverflow.com/users/1462724", "pm_score": 0, "selected": false, "text": "#define LIST_DEFINE(type) \\\n struct list_node_##type \\\n { \\\n type *data; \\`\n struct list_node_##type *next; \\\n };\n\nLIST_INSERT(&ListHead,&Data, DataType);\n ListHead Data DataType LIST_DELETE MACRO MACRO LIST_DELETE(&ListHead, DataType, myvar->data->str, char*);\n ListHead DataType myvar->data->str char* if((keytype)ListHead->data->key == (keytype)key)\n ListHead->data->myvar->data->str == myvar->data->str\n ListHead->data->myvar->data->str" }, { "answer_id": 13742217, "author": "user1251840", "author_id": 1251840, "author_profile": "https://Stackoverflow.com/users/1251840", "pm_score": 2, "selected": false, "text": "#ifndef _LISTE\n#define _LISTE\n#include <stdlib.h>\ntypedef struct liste_s {\n struct liste_s * suivant ;\n} * liste ;\n\n\n#define newl(t) ( (liste) malloc ( sizeof ( struct liste_s ) + sizeof ( t ) ) )\n#define elt(l,t) ( * ( ( t * ) ( l + 1 ) ) )\n\n#define liste_vide NULL\n#define videp(l) ( l == liste_vide )\n#define lvide() liste_vide\n#define cons(e,l) \\\n ({ liste res = newl(typeof(e)) ; \\\n res->suivant = l ; \\\n elt(res,typeof(e)) = e ; \\\n res ; }) \n\n#define hd(l,t) ({ liste res = l ; if ( videp(res) ) exit ( EXIT_FAILURE ) ; elt(res,t) ; })\n#define tl(l) ({ liste res = l ; if ( videp(res) ) exit ( EXIT_FAILURE ) ; res->suivant ;})\n\n\n#endif\n" }, { "answer_id": 33382693, "author": "mmcorrelo", "author_id": 1799943, "author_profile": "https://Stackoverflow.com/users/1799943", "pm_score": 0, "selected": false, "text": "typedef struct token {\n int id;\n char *name;\n struct token *next;\n} Token;\n void* tail(void* list, void* (*f)(void *)) {\n void *head = list;\n\n while(f(head) != NULL) {\n head = f(head);\n }\n\n return head;\n}\n void* nextToken(void *a) {\n Token *t = (Token *) t;\n return (void *) (a->next);\n}\n Token *listTokens;\n(...)\nToken *lastToken = tail(listTokens, nextToken);\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
326,205
<p>What is forward reference in C with respect to pointers?</p> <p>Can I get an example?</p>
[ { "answer_id": 326214, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 5, "selected": true, "text": "struct MyStruct;\nstruct MyStruct *ptr;\nstruct MyStruct var; // ILLEGAL\nptr->member; // ILLEGAL\n\nstruct MyStruct {\n // ...\n};\n\n// Or:\n\ntypedef struct MyStruct MyStruct;\nMyStruct *ptr;\nMyStruct var; // ILLEGAL\nptr->member; // ILLEGAL\n\nstruct MyStruct {\n // ...\n};\n" }, { "answer_id": 326259, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "struct MyStruct *ptr; // this is a forward reference.\n\nstruct MyStruct\n{\n struct MyStruct *next; // another forward reference - this is much more useful\n // some data members\n};\n" }, { "answer_id": 326302, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "struct Plop\n{\n int n;\n float f;\n};\n struct Plop; // Instead of including Plop.h, just use a forward declaration to speed up compile time\n\nvoid doSomething(Plop* plop);\nvoid doNothing(Plop* plop);\n #include \"PlopUtils.h\"\n#include \"Plop.h\" // now we need to include the header in order to work with the type\n\nvoid doSomething(Plop* plop)\n{\n plop->n ...\n}\n\nvoid doNothing(Plop* plop);\n{\n plop->f ...\n}\n" }, { "answer_id": 326621, "author": "Mike Dunlavey", "author_id": 23771, "author_profile": "https://Stackoverflow.com/users/23771", "pm_score": 2, "selected": false, "text": " ....\n ... foo(a,b) + 1 ... // assumes foo returns int\n ....\n\n double foo(double x, double y){ ... } // violates earlier assumption\n double foo(double x, double y); // this is the forward declaration\n\n ....\n ... foo(a,b) + 1 ... // correct assumptions made\n ....\n\n double foo(double x, double y){ ... } // this is the real declaration\n" }, { "answer_id": 326995, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "struct foo;\n\nstruct bar\n{\n struct foo *f;\n};\n\nstruct foo\n{\n struct bar *b;\n};\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
326,206
<p>I'm developing a web tool using JSP, where there are many users of multiple kind (i.e. administrators, guest, write-enabled users, ...). Since this will be a subscription based system (i.e. user pay for a 3/6/12 month subscription), I need to enforce at most 1 login per user at the same time. For example, say Mr. John Smith subscribes to this system; I don't want him to give his login info to a friend of his so that they'll both be using the system from 2 different computers at the same time. How can I manage this situation?</p>
[ { "answer_id": 493992, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 1, "selected": false, "text": "HttpSession.getId() request.getSession().getId() request.getSession().invalidate()" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,223
<p>I have an abstract base class and I want to declare a field or a property that will have a different value in each class that inherits from this parent class. </p> <p>I want to define it in the baseclass so I can reference it in a base class method - for example overriding ToString to say "This object is of type <i>property/field</i>". I have got three ways that I can see of doing this, but I was wondering - what is the best or accepted way of doing this? Newbie question, sorry.</p> <p><strong>Option 1:</strong><br> Use an abstract Property and override it on the inherited classes. This benefits from being enforced (you have to override it) and it is clean. But, it feels slightly wrong to return a hard-code value rather than encapsulate a field and it is a few lines of code instead of just. I also have to declare a body for "set" but that is less important (and there is probably a way to avoid that which I am not aware of). </p> <pre><code>abstract class Father { abstract public int MyInt { get; set;} } class Son : Father { public override int MyInt { get { return 1; } set { } } } </code></pre> <p><strong>Option 2</strong><br> I can declare a public field (or a protected field) and explicitly override it in the inherited class. The example below will give me a warning to use "new" and I can probably do that, but it feels wrong and it breaks the polymorphism, which was the whole point. Doesn't seem like a good idea...</p> <pre><code>abstract class Mother { public int MyInt = 0; } class Daughter : Mother { public int MyInt = 1; } </code></pre> <p><strong>Option 3</strong><br> I can use a protected field and set the value in the constructor. This seems pretty tidy but relies on me ensuring the constructor always sets this and with multiple overloaded constructors there is always a chance some code path won't set the value.</p> <pre><code>abstract class Aunt { protected int MyInt; } class Niece : Aunt { public Niece() { MyInt = 1; } } </code></pre> <p>It's a bit of a theoretical question and I guess the answer has to be option 1 as it is the only <i>safe</i> option but I am just getting to grips with C# and wanted to ask this of people with more experience.</p>
[ { "answer_id": 326230, "author": "Winston Smith", "author_id": 35086, "author_profile": "https://Stackoverflow.com/users/35086", "pm_score": 0, "selected": false, "text": "abstract class Base \n{\n protected int myInt;\n protected abstract void setMyInt();\n}\n\nclass Derived : Base \n{\n override protected void setMyInt()\n {\n myInt = 3;\n }\n}\n abstract class Father\n{\n abstract public int MyInt { get; }\n}\n\nclass Son : Father\n{\n public override int MyInt\n {\n get { return 1; }\n }\n}\n" }, { "answer_id": 326231, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 1, "selected": false, "text": "abstract class Aunt\n{\n protected int MyInt;\n protected Aunt(int myInt)\n {\n MyInt = myInt;\n }\n\n}\n" }, { "answer_id": 326237, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 3, "selected": false, "text": "abstract class Father\n{\n //Do you need it public?\n protected readonly int MyInt;\n}\n\nclass Son : Father\n{\n public Son()\n {\n MyInt = 1;\n }\n}\n" }, { "answer_id": 326242, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "abstract class Mother\n{\n private readonly int myInt;\n public int MyInt { get { return myInt; } }\n\n protected Mother(int myInt)\n {\n this.myInt = myInt;\n }\n}\n\nclass Daughter : Mother\n{\n public Daughter() : base(1)\n {\n }\n}\n" }, { "answer_id": 327496, "author": "Preets", "author_id": 41766, "author_profile": "https://Stackoverflow.com/users/41766", "pm_score": 8, "selected": true, "text": "abstract class Parent\n{\n abstract public int MyInt { get; }\n}\n\nclass Father : Parent\n{\n public override int MyInt\n {\n get { /* Apply formula \"X\" and return a value */ }\n }\n}\n\nclass Mother : Parent\n{\n public override int MyInt\n {\n get { /* Apply formula \"Y\" and return a value */ }\n }\n}\n" }, { "answer_id": 19962974, "author": "Joshua G", "author_id": 754485, "author_profile": "https://Stackoverflow.com/users/754485", "pm_score": 4, "selected": false, "text": "class x\n{\n private int _myInt;\n public virtual int myInt { get { return _myInt; } set { _myInt = value; } }\n}\n\nclass y : x\n{\n private int _myYInt;\n public override int myInt { get { return _myYInt; } set { _myYInt = value; } }\n}\n" }, { "answer_id": 33486284, "author": "8r13n", "author_id": 5517408, "author_profile": "https://Stackoverflow.com/users/5517408", "pm_score": 0, "selected": false, "text": "namespace Core.Text.Menus\n{\n public abstract class AbstractBaseClass\n {\n public string SELECT_MODEL;\n public string BROWSE_RECORDS;\n public string SETUP;\n }\n}\n\nnamespace Core.Text.Menus\n{\n public class English : AbstractBaseClass\n {\n public English()\n {\n base.SELECT_MODEL = \"Select Model\";\n base.BROWSE_RECORDS = \"Browse Measurements\";\n base.SETUP = \"Setup Instrument\";\n }\n }\n}\n" }, { "answer_id": 51546133, "author": "Keith Aymar", "author_id": 1112172, "author_profile": "https://Stackoverflow.com/users/1112172", "pm_score": 2, "selected": false, "text": "virtual //you may want to also use interfaces.\ninterface IFather\n{\n int MyInt { get; set; }\n}\n\n\npublic class Father : IFather\n{\n //defaulting the value of this property to 1\n private int myInt = 1;\n\n public virtual int MyInt\n {\n get { return myInt; }\n set { myInt = value; }\n }\n}\n\npublic class Son : Father\n{\n public override int MyInt\n {\n get {\n\n //demonstrating that you can access base.properties\n //this will return 1 from the base class\n int baseInt = base.MyInt;\n\n //add 1 and return new value\n return baseInt + 1;\n }\n set\n {\n //sets the value of the property\n base.MyInt = value;\n }\n }\n}\n Son son = new Son();\n//son.MyInt will equal 2\n" }, { "answer_id": 57162980, "author": "Belomestnykh Sergey", "author_id": 6312101, "author_profile": "https://Stackoverflow.com/users/6312101", "pm_score": 0, "selected": false, "text": " internal abstract class AbstractClass\n {\n //Properties for parameterization from concrete class\n protected abstract string Param1 { get; }\n protected abstract string Param2 { get; }\n\n //Internal fields need for manage state of object\n private string var1;\n private string var2;\n\n internal AbstractClass(string _var1, string _var2)\n {\n this.var1 = _var1;\n this.var2 = _var2;\n }\n\n internal void CalcResult()\n {\n //The result calculation uses Param1, Param2, var1, var2;\n }\n }\n\n internal class ConcreteClassFirst : AbstractClass\n {\n private string param1;\n private string param2;\n protected override string Param1 { get { return param1; } }\n protected override string Param2 { get { return param2; } }\n\n public ConcreteClassFirst(string _var1, string _var2) : base(_var1, _var2) { }\n\n internal void CalcParams()\n {\n //The calculation param1 and param2\n }\n }\n\n internal class ConcreteClassSecond : AbstractClass\n {\n private string param1;\n private string param2;\n\n protected override string Param1 { get { return param1; } }\n\n protected override string Param2 { get { return param2; } }\n\n public ConcreteClassSecond(string _var1, string _var2) : base(_var1, _var2) { }\n\n internal void CalcParams()\n {\n //The calculation param1 and param2\n }\n }\n\n static void Main(string[] args)\n {\n string var1_1 = \"val1_1\";\n string var1_2 = \"val1_2\";\n\n ConcreteClassFirst concreteClassFirst = new ConcreteClassFirst(var1_1, var1_2);\n concreteClassFirst.CalcParams();\n concreteClassFirst.CalcResult();\n\n string var2_1 = \"val2_1\";\n string var2_2 = \"val2_2\";\n\n ConcreteClassSecond concreteClassSecond = new ConcreteClassSecond(var2_1, var2_2);\n concreteClassSecond.CalcParams();\n concreteClassSecond.CalcResult();\n\n //Param1 and Param2 are not visible in main method\n }\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11534/" ]
326,233
<p>I have a GridView populated from an ObjectDataSource with two items in its DataKeyNames field. One is the primary key, ID, the other is a category field (the category field is used to add header rows to delineate categories).</p> <p>Displaying works fine, but I'm trying to create a Delete action. The object's delete method only needs the ID field and in the ObjectDataSource even if I define the method as only needing an ID field, .net complains because it is looking for a method which has both the fields defined in DataKeyNames.</p> <p>It works if I add a parameter for the category to the delete method, but it's annoying to have a parameter defined that isn't used for anything.</p> <p>Can I configure the ObjectDataSource and GridView objects to have two values for DataKeyNames but specific which would should be passed to which methods?</p> <p>The (simplified) definitions for the two objects are:</p> <pre><code>&lt;asp:ObjectDataSource ID="ObjDS1" runat="server" SelectMethod="getAllItems" TypeName="Items" DeleteMethod="deleteItem"&gt; &lt;DeleteParameters&gt; &lt;asp:Parameter Name="ID" Type="Int32" /&gt; &lt;!-- This shouldn't be necessary: --&gt; &lt;asp:Parameter Name="Category" Type="String" /&gt; &lt;/DeleteParameters&gt; &lt;/asp:ObjectDataSource&gt; &lt;asp:GridView ID="gvJItems" runat="server" AutoGenerateColumns="False" DataKeyNames="ID,Category" DataSourceID="ObjDS1"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="ID" Visible="false" HeaderText="ID" /&gt; &lt;asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="85%"/&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="lbDelete" Runat="server" OnClientClick="return confirm('Are you sure you want to delete this?');" CommandName="Delete"&gt;Delete&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre>
[ { "answer_id": 9117075, "author": "Ken Parker", "author_id": 1185766, "author_profile": "https://Stackoverflow.com/users/1185766", "pm_score": 1, "selected": false, "text": "ObjectDataSource void ODS_Updating(Object sender, ObjectDataSourceMethodEventArgs e)\n{\n e.InputParameters.Remove(\"Type_ID\");\n e.InputParameters.Remove(\"Document_ID\");\n e.InputParameters.Remove(\"State_ID\");\n}\n DataKeys" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
326,277
<p>I'm trying to verify that a parameter is an instance of a specific class in Rails:</p> <pre><code>def schedule(action, *args) if arg.is_a? Aircraft ... end end </code></pre> <p>I'm doing this in a library class (the file is in <em>lib/</em>) and I get an <strong>uninitialized constant Aircraft</strong> error. Aircraft is a model class, with a corresponding <em>aircraft.rb</em> file in <em>app/models</em>.</p> <p>Can I use model classes and instances in a library? How?</p> <hr> <p><strong>Error context:</strong></p> <p>The error happens in RSpec tests; the code works in the browser. I tried requiring the model in the <em>_spec.rb</em> file, no success at the moment.</p>
[ { "answer_id": 326395, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 2, "selected": false, "text": "require File.dirname(__FILE__) + \"/../app/models/aircraft\"\n task :my_task => :environment do\n # something happens...\nend \n" }, { "answer_id": 326471, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 2, "selected": false, "text": "require File.dirname(__FILE__) + '/../spec_helper'\n ruby script/generate rspec\n" }, { "answer_id": 5000341, "author": "Autodidact", "author_id": 60072, "author_profile": "https://Stackoverflow.com/users/60072", "pm_score": 0, "selected": false, "text": "if arg.is_a? ::Aircraft" }, { "answer_id": 5093098, "author": "Peeja", "author_id": 4937, "author_profile": "https://Stackoverflow.com/users/4937", "pm_score": 1, "selected": false, "text": "#schedule Spaceship #schedule #schedule Aircraft #schedule def schedule(action, vehicle)\n if vehicle.is_an?(Aircraft)\n possible_days = case action\n when \"travel\"\n [\"Mon\", \"Wed\", \"Fri\"]\n when \"repair\"\n [\"Sat\", \"Sun\"]\n end\n possible_days.rand\n elsif vehicle.is_a?(Spaceship)\n possible_days = case action\n when \"travel\"\n [\"Sat\", \"Tue\", \"Thu\"]\n when \"repair\"\n [\"Sun\", \"Mon\"]\n end\n possible_days.rand\n end\nend\n def schedule(action, vehicle)\n vehicle.days_action_can_be_performed(action).rand\nend\n\n\nclass Aircraft\n def days_action_can_be_performed(action)\n possible_days = case action\n when \"travel\"\n [\"Mon\", \"Wed\", \"Fri\"]\n when \"repair\"\n [\"Sat\", \"Sun\"]\n end\n possible_days\n end\nend\n\nclass Spaceship\n def days_action_can_be_performed(action)\n possible_days = case action\n when \"travel\"\n [\"Sat\", \"Tue\", \"Thu\"]\n when \"repair\"\n [\"Sun\", \"Mon\"]\n end\n possible_days\n end\nend\n #days_action_can_be_performed #schedule" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/341/" ]
326,309
<pre><code>abstract class Foo { private List&lt;Object&gt; container; private bool update; Foo Foo() { container = new List&lt;object&gt;(); update = false; } public abstract Bar CreateBar(); public void BeginUpdate() { if (!update) { Thread update_thread = new Thread(new ThreadStart(Update)); update_thread.Start(); } } private void Update() { update = true; while (update) { lock (container) { if (...) container.Add(this.CreateBar()); else container.Remove(...); } Thread.Sleep(1337); } } public void EndUpdate() { update = false; } public List&lt;Object&gt; Objects { get { lock (container) { return this.container; } } } } </code></pre> <p>When something outside of Foo calls the Foo's Object accessor like,</p> <pre><code>List&lt;Objects&gt; objects = foo_instance.Objects; foreach (Object o in objects) { Thread.Sleep(31173); } </code></pre> <p>How will the locking occur? Will the thread running Update() have to wait until the above foreach is done processing objects list? I would like that these two would work simultaneously, is the only solution to make a deep copy of objects?</p>
[ { "answer_id": 326319, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 3, "selected": true, "text": "public List<Object> Objects\n{\n get\n {\n lock (container)\n {\n return this.container;\n }\n }\n}\n" }, { "answer_id": 326337, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "List<Objects> objects = foo_instance.Objects;\nforeach (Object o in objects)\n{ \n Thread.Sleep(31173);\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,321
<p>I am trying to create an expression tree that represents the following:</p> <pre><code>myObject.childObjectCollection.Any(i =&gt; i.Name == "name"); </code></pre> <p>Shortened for clarity, I have the following:</p> <pre><code>//'myObject.childObjectCollection' is represented here by 'propertyExp' //'i =&gt; i.Name == "name"' is represented here by 'predicateExp' //but I am struggling with the Any() method reference - if I make the parent method //non-generic Expression.Call() fails but, as per below, if i use &lt;T&gt; the //MethodInfo object is always null - I can't get a reference to it private static MethodCallExpression GetAnyExpression&lt;T&gt;(MemberExpression propertyExp, Expression predicateExp) { MethodInfo method = typeof(Enumerable).GetMethod("Any", new[]{ typeof(Func&lt;IEnumerable&lt;T&gt;, Boolean&gt;)}); return Expression.Call(propertyExp, method, predicateExp); } </code></pre> <p>What am I doing wrong? Anyone have any suggestions?</p>
[ { "answer_id": 326496, "author": "Barry Kelly", "author_id": 3712, "author_profile": "https://Stackoverflow.com/users/3712", "pm_score": 7, "selected": true, "text": "GetAnyExpression<T> propertyExp.Type GetAnyExpression<T> propertyExp Expression GetAnyExpression Expression Enumerable.Any<T> Any LambdaExpression Expression Any MemberExpression MemberExpression Expression IEnumerable<> Any static MethodBase GetGenericMethod(Type type, string name, Type[] typeArgs, \n Type[] argTypes, BindingFlags flags)\n{\n int typeArity = typeArgs.Length;\n var methods = type.GetMethods()\n .Where(m => m.Name == name)\n .Where(m => m.GetGenericArguments().Length == typeArity)\n .Select(m => m.MakeGenericMethod(typeArgs));\n\n return Type.DefaultBinder.SelectMethod(flags, methods.ToArray(), argTypes, null);\n}\n propertyExp Expression Expression List<T> IEnumerable<T> static bool IsIEnumerable(Type type)\n{\n return type.IsGenericType\n && type.GetGenericTypeDefinition() == typeof(IEnumerable<>);\n}\n\nstatic Type GetIEnumerableImpl(Type type)\n{\n // Get IEnumerable implementation. Either type is IEnumerable<T> for some T, \n // or it implements IEnumerable<T> for some T. We need to find the interface.\n if (IsIEnumerable(type))\n return type;\n Type[] t = type.FindInterfaces((m, o) => IsIEnumerable(m), null);\n Debug.Assert(t.Length == 1);\n return t[0];\n}\n Type IEnumerable<T> static Expression CallAny(Expression collection, Delegate predicate)\n{\n Type cType = GetIEnumerableImpl(collection.Type);\n collection = Expression.Convert(collection, cType);\n\n Type elemType = cType.GetGenericArguments()[0];\n Type predType = typeof(Func<,>).MakeGenericType(elemType, typeof(bool));\n\n // Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)\n MethodInfo anyMethod = (MethodInfo)\n GetGenericMethod(typeof(Enumerable), \"Any\", new[] { elemType }, \n new[] { cType, predType }, BindingFlags.Static);\n\n return Expression.Call(\n anyMethod,\n collection,\n Expression.Constant(predicate));\n}\n Main() static void Main()\n{\n // sample\n List<string> strings = new List<string> { \"foo\", \"bar\", \"baz\" };\n\n // Trivial predicate: x => x.StartsWith(\"b\")\n ParameterExpression p = Expression.Parameter(typeof(string), \"item\");\n Delegate predicate = Expression.Lambda(\n Expression.Call(\n p,\n typeof(string).GetMethod(\"StartsWith\", new[] { typeof(string) }),\n Expression.Constant(\"b\")),\n p).Compile();\n\n Expression anyCall = CallAny(\n Expression.Constant(strings),\n predicate);\n\n // now test it.\n Func<bool> a = (Func<bool>) Expression.Lambda(anyCall).Compile();\n Console.WriteLine(\"Found? {0}\", a());\n Console.ReadLine();\n}\n" }, { "answer_id": 18129261, "author": "Aaron Heusser", "author_id": 2662996, "author_profile": "https://Stackoverflow.com/users/2662996", "pm_score": 4, "selected": false, "text": "static Expression CallAny(Expression collection, Expression predicateExpression)\n{\n Type cType = GetIEnumerableImpl(collection.Type);\n collection = Expression.Convert(collection, cType); // (see \"NOTE\" below)\n\n Type elemType = cType.GetGenericArguments()[0];\n Type predType = typeof(Func<,>).MakeGenericType(elemType, typeof(bool));\n\n // Enumerable.Any<T>(IEnumerable<T>, Func<T,bool>)\n MethodInfo anyMethod = (MethodInfo)\n GetGenericMethod(typeof(Enumerable), \"Any\", new[] { elemType }, \n new[] { cType, predType }, BindingFlags.Static);\n\n return Expression.Call(\n anyMethod,\n collection,\n predicateExpression);\n}\n public class Blog\n{\n public int BlogId { get; set; }\n public string Name { get; set; }\n\n public virtual List<Post> Posts { get; set; }\n}\n\npublic class Post\n{\n public int PostId { get; set; }\n public string Title { get; set; }\n public DateTime Date { get; set; }\n\n public int BlogId { get; set; }\n public virtual Blog Blog { get; set; }\n}\n\npublic class BloggingContext : DbContext\n{\n public DbSet<Blog> Blogs { get; set; }\n public DbSet<Post> Posts { get; set; }\n}\n static void Main()\n{\n Database.SetInitializer<BloggingContext>(\n new DropCreateDatabaseAlways<BloggingContext>());\n\n using (var ctx = new BloggingContext())\n {\n // insert some data\n var blog = new Blog(){Name = \"blog\"};\n blog.Posts = new List<Post>() \n { new Post() { Title = \"p1\", Date = DateTime.Parse(\"01/01/2001\") } };\n blog.Posts = new List<Post>()\n { new Post() { Title = \"p2\", Date = DateTime.Parse(\"01/01/2002\") } };\n blog.Posts = new List<Post>() \n { new Post() { Title = \"p3\", Date = DateTime.Parse(\"01/01/2003\") } };\n ctx.Blogs.Add(blog);\n\n blog = new Blog() { Name = \"blog 2\" };\n blog.Posts = new List<Post>()\n { new Post() { Title = \"p1\", Date = DateTime.Parse(\"01/01/2001\") } };\n ctx.Blogs.Add(blog);\n ctx.SaveChanges();\n\n\n // first, do a hard-coded Where() with Any(), to demonstrate that\n // Linq-to-SQL can handle it\n var cutoffDateTime = DateTime.Parse(\"12/31/2001\");\n var hardCodedResult = \n ctx.Blogs.Where((b) => b.Posts.Any((p) => p.Date > cutoffDateTime));\n var hardCodedResultCount = hardCodedResult.ToList().Count;\n Debug.Assert(hardCodedResultCount > 0);\n\n\n // now do a logically equivalent Where() with Any(), but programmatically\n // build the expression tree\n var blogsWithRecentPostsExpression = \n BuildExpressionForBlogsWithRecentPosts(cutoffDateTime);\n var dynamicExpressionResult = \n ctx.Blogs.Where(blogsWithRecentPostsExpression);\n var dynamicExpressionResultCount = dynamicExpressionResult.ToList().Count;\n Debug.Assert(dynamicExpressionResultCount > 0);\n Debug.Assert(dynamicExpressionResultCount == hardCodedResultCount);\n }\n}\n private Expression<Func<Blog, Boolean>> BuildExpressionForBlogsWithRecentPosts(\n DateTime cutoffDateTime)\n{\n var blogParam = Expression.Parameter(typeof(Blog), \"b\");\n var postParam = Expression.Parameter(typeof(Post), \"p\");\n\n // (p) => p.Date > cutoffDateTime\n var left = Expression.Property(postParam, \"Date\");\n var right = Expression.Constant(cutoffDateTime);\n var dateGreaterThanCutoffExpression = Expression.GreaterThan(left, right);\n var lambdaForTheAnyCallPredicate = \n Expression.Lambda<Func<Post, Boolean>>(dateGreaterThanCutoffExpression, \n postParam);\n\n // (b) => b.Posts.Any((p) => p.Date > cutoffDateTime))\n var collectionProperty = Expression.Property(blogParam, \"Posts\");\n var resultExpression = CallAny(collectionProperty, lambdaForTheAnyCallPredicate);\n return Expression.Lambda<Func<Blog, Boolean>>(resultExpression, blogParam);\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
326,339
<p>I've heard some people saying that enums are evil and shouldn't be used in web services because of the mismatches that could occur between the server and the client if some values are assigned, or if the enum is marked with the <a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute(VS.71).aspx" rel="noreferrer">Flags</a> attribute. They also said that web services exposing enums are harder to maintain but couldn't really give me viable arguments. So from your experience what are the pros and cons of using enums in a WCF web service?</p>
[ { "answer_id": 375054, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 3, "selected": false, "text": "xsd:enumeration" }, { "answer_id": 21148284, "author": "BalintN", "author_id": 1617585, "author_profile": "https://Stackoverflow.com/users/1617585", "pm_score": 2, "selected": false, "text": "enum ErrorCodes\n{\n OK = 0,\n GenericError = 100,\n SomeOtherError = 101,\n}\n enum ErrorCodes\n{\n OK,\n GenericError,\n SomeOtherError,\n}\n" }, { "answer_id": 34519520, "author": "Scott Hannen", "author_id": 5101046, "author_profile": "https://Stackoverflow.com/users/5101046", "pm_score": 0, "selected": false, "text": "[DataContract]\npublic class EnumValue<T> where T : struct\n{\n [DataMember]\n private string _raw = string.Empty;\n\n [IgnoreDataMember]\n private bool _parsed;\n\n [IgnoreDataMember]\n private T _parsedValue;\n\n public EnumValue()\n {\n Set(default(T));\n }\n\n public EnumValue(T value)\n {\n Set(value);\n }\n\n internal T Value\n {\n get\n {\n if (_parsed) return _parsedValue;\n if (!Enum.TryParse<T>(_raw, out _parsedValue))\n {\n _parsedValue = default(T);\n }\n _parsed = true;\n return _parsedValue;\n }\n }\n\n public void Set(T value)\n {\n _raw = value.ToString();\n _parsedValue = value;\n _parsed = true;\n }\n}\n\npublic static class EnumValueExtensions\n{\n public static T GetValue<T>(this EnumValue<T> enumValue) where T : struct\n {\n return enumValue == null ? default(T) : enumValue.Value;\n }\n\n public static bool EqualsValue<T>(this EnumValue<T> enumValue, T compareTo) where T : struct\n {\n return (enumValue.GetValue().Equals(compareTo));\n }\n}\n" }, { "answer_id": 49871562, "author": "Noctis", "author_id": 1698987, "author_profile": "https://Stackoverflow.com/users/1698987", "pm_score": 1, "selected": false, "text": "enum public enum { orange, banana, mango }\n public enum { orange=1, banana=2, grape=3, mango=4 }\n public enum { wcfBugBane=0, orange=1, banana=2, grape=3, mango=4 }\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29407/" ]
326,344
<p>I've read a little bit about unit testing and was wondering how YOU unit test. Apparently unit testing is supposed to break a program down into very small "units" and test functionality from there.</p> <p>But I'm wondering, is it enough to unit test a class? Or do you take it even further and unit test algorithms, formulas, etc.? Or do you broaden it to unit test asp pages/functionality? Or do you unit test at all?</p>
[ { "answer_id": 326624, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 1, "selected": false, "text": "template<class TYPE> inline TYPE MIN(const TYPE & x, const TYPE & y) { return x > y ? y : x; }\ntemplate<class TYPE> inline TYPE MAX(const TYPE & x, const TYPE & y) { return x < y ? y : x; }\n SHOW(MIN(3,4)); SHOW(MAX(3,4));\n #define SHOW(X) std::cout << # X \" = \" << (X) << std::endl\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38317/" ]
326,350
<p>I want to do a simple role authentication in .NET - but am lost in the profusion of apis...</p> <p>I would like to have a web.config per directory with role access like:</p> <pre><code>&lt;authorization&gt; &lt;allow roles="admin"/&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; </code></pre> <p>And in my login page, where I do FormsAuthentication.RedirectFromLoginPage I want to specify the role of the logged in user (admin, user, etc...) I have no need for the RoleManagementProviders and the overkilled feature (in my case) of RoleManagement. </p> <p>What API do I need to user to just specify the role of a user?</p> <p>Thanks</p>
[ { "answer_id": 362838, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 0, "selected": false, "text": "<connectionStrings>\n <add name=\"LocalPolicyStore\" connectionString=\"msxml://C:/AzManStore.xml\"/>\n</connectionStrings>\n <roleManager enabled=\"true\" defaultProvider=\"RoleManagerAzManProvider\">\n <providers>\n <add name=\"RoleManagerAzManProvider\"\n type=\"System.Web.Security.AuthorizationStoreRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, publicKeyToken=b03f5f7f11d50a3a\"\n applicationName=\"MyApp\"\n connectionStringName=\"LocalPolicyStore\"/>\n </providers>\n</roleManager>\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37955/" ]
326,352
<p>I'm using some meta-programming to generate a bunch of methods in ruby like so:</p> <pre><code>class EmotionalObject def self.mood( name, *details ) define_method(name) do # ... end end mood :happy, #... mood :sad, #... mood :ebuillent, #... #... end </code></pre> <p>I know that I can pass <code>rdoc</code> '-A mood' to get it to recognize my mood generation code as attributes, which is handy, since then they at least get recognized.</p> <p>However, they're really more like regular methods than attributes, so I don't want them listed under the 'Attributes:' section when I look at the documentation using <code>ri</code>. I don't have any regular attributes, so is there any simple way I can just change the title of this section to be 'Moods:' or something like that, so my users are at least curious enough to type <code>ri EmotionalObject#happy</code>.</p>
[ { "answer_id": 362838, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 0, "selected": false, "text": "<connectionStrings>\n <add name=\"LocalPolicyStore\" connectionString=\"msxml://C:/AzManStore.xml\"/>\n</connectionStrings>\n <roleManager enabled=\"true\" defaultProvider=\"RoleManagerAzManProvider\">\n <providers>\n <add name=\"RoleManagerAzManProvider\"\n type=\"System.Web.Security.AuthorizationStoreRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, publicKeyToken=b03f5f7f11d50a3a\"\n applicationName=\"MyApp\"\n connectionStringName=\"LocalPolicyStore\"/>\n </providers>\n</roleManager>\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9859/" ]
326,365
<p>Is there a way to change the connection string of a DataBase object in Enterprise Library at runtime? I've found <a href="http://blog.benday.com/archive/2005/05/05/357.aspx" rel="nofollow noreferrer">this</a> link but its a little bit outdated (2005)</p> <p>I've also found <a href="https://stackoverflow.com/questions/63546/vs2005-c-programmatically-change-connection-string-contained-in-appconfig">this</a> but it seems to apply to .Net in general, I was wondering if there was something that could be done specifically for EntLib.</p> <p>I was just passing the connection string name to the CreateDatabase() method in DatabaseFactory object and that worked til yesterday that my project manager asked me to support more than one database instance. It happens that we have to have one database per state (one for CA, one for FL, etc...) so my software needs to cycle through all databases and do something with data but it will use the same config file.</p> <p>Thanks in advance.</p>
[ { "answer_id": 2028370, "author": "Junior Mayhé", "author_id": 66708, "author_profile": "https://Stackoverflow.com/users/66708", "pm_score": 2, "selected": false, "text": "using Microsoft.Practices.EnterpriseLibrary.Data;\nusing Microsoft.Practices.EnterpriseLibrary.Configuration;\nusing Microsoft.Practices.EnterpriseLibrary.Data.Configuration;\n\nDatabaseSettings settings = new DatabaseSettings();\n\n// This maps to <databaseType> element in data config file\nDatabaseTypeData type = new DatabaseTypeData(\"Sql Server\", \"Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\");\nsettings.DatabaseTypes.Add(type);\n\n// This maps to <connectionString> element in data config file\nConnectionStringData connectionString = new ConnectionStringData(\"localhost.EntLibQuickStarts\");\n\n// Followings map to <parameter> elements in data config file\nParameterData param = new ParameterData(\"server\", \"localhost\");\nconnectionString.Parameters.Add(param);\n\nparam = new ParameterData(\"database\", \"EntLibQuickStarts\");\nconnectionString.Parameters.Add(param);\n\nparam = new ParameterData(\"integrated security\", \"true\");\nconnectionString.Parameters.Add(param);\n\nsettings.ConnectionStrings.Add(connectionString);\n\n// Too bad compiler gets confused InstanceData with System.Diagnostics.InstanceData. It maps to <instance> element in data config file\nMicrosoft.Practices.EnterpriseLibrary.Data.Configuration.InstanceData instance = new Microsoft.Practices.EnterpriseLibrary.Data.Configuration.InstanceData(\"localhost\", \"Sql Server\", \"localhost.EntLibQuickStarts\");\nsettings.Instances.Add(instance);\n\nConfigurationDictionary configurations = new ConfigurationDictionary();\n\n// This is how to tie DatabaseSettings with ConfigurationDictionary. It maps to <configurationSection name=\"dataConfiguration\"> element in App.config file configurations.Add(\"dataConfiguration\", settings);\nConfigurationContext context = ConfigurationManager.CreateContext(configurations);\n\nDatabase database = new DatabaseProviderFactory(context).CreateDatabase(\"localhost\");\n" }, { "answer_id": 5334296, "author": "bentz", "author_id": 655259, "author_profile": "https://Stackoverflow.com/users/655259", "pm_score": 4, "selected": false, "text": "database mydb = new EnterpriseLibrary.Data.Sql.SqlDatabase(\"connection string here\");\n" }, { "answer_id": 21873862, "author": "Sujoy Roy Chowdhury", "author_id": 3326940, "author_profile": "https://Stackoverflow.com/users/3326940", "pm_score": 2, "selected": false, "text": "var builder = new ConfigurationSourceBuilder();\n\n builder.ConfigureData()\n .ForDatabaseNamed(\"LocalSqlServer1\")\n .ThatIs.ASqlDatabase()\n .WithConnectionString(@\"Data Source=PCNAME\\SQLEXPRESS;Initial Catalog=ContactDB;Integrated Security=True\")\n .ForDatabaseNamed(\"LocalSqlServer2\")\n .ThatIs.ASqlDatabase()\n .WithConnectionString(@\"Data Source=PCNAME\\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True\");\n\n var configSource = new DictionaryConfigurationSource();\n builder.UpdateConfigurationWithReplace(configSource);\n\nMicrosoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); \n\nDatabase destinationDatabase = DatabaseFactory.CreateDatabase(\"LocalSqlServer2\"); \n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14533/" ]
326,384
<p>Yesterday I've tried to get serious about rightly caching some PHP generated pages (think "Articles with comments"). Big fail.</p> <p>Long story short: I set the ETag header, set the Last-Modified one and check server side every Article browser request with them to see if I can send back a 304.</p> <p>The problem is simple: the browser (tried with FF 3, so far), after 1 or 2 reloads, suddendly stops checking back the freshness of the page and uses its cached copy.</p> <p>For what I have understood, using ETag and Last-Modified, the browser MUST check with the server on every request (otherwise, why we should use ETag at all?).</p> <p>I tried also playing with Cache-Control or Expires... nothing. One way or another, the browser stops checking, or does not send back the ETag...</p> <p>I'm really frustrated... does anyone happen to have this thing sorted out?</p>
[ { "answer_id": 334224, "author": "mkoeller", "author_id": 33433, "author_profile": "https://Stackoverflow.com/users/33433", "pm_score": -1, "selected": false, "text": "about:cache\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27958/" ]
326,387
<p>I'm watching Stephen A Bohlen's excellent <a href="http://www.summerofnhibernate.com/" rel="nofollow noreferrer">Summer of NHibernate</a> series, and have been watching him interact with CodeRush. I've recently installed ReSharper (I'm a ReSharper newbie), and I'm trying to find some of the ReSharper productivity equivalents that Stephen is demonstrating (tangentially) with CodeRush.</p> <p>As an example, he demonstrates highlighting a code block that looks like this:</p> <pre><code>ISession session = GetSession(); session.xxx </code></pre> <p>and then turning it into </p> <pre><code>using (ISession session = GetSession()) { session.xxx } </code></pre> <p>He does this by highlighting the block he wants to <em>surround</em> with the using statement and then invoking some CodeRush template. I've been unable to figure out how to do the equivalent thing with ReSharper. I found the ReSharper Surround command (within the Code command), but when you select the <strong>using</strong> statement, it does surround your highlighted code block, but it does not seem <em>smart</em> enough to put the first line within the using clause. That is, it results in:</p> <pre><code>using () { ISession session = GetSession(); session.xxx } </code></pre> <p>which requires me to move the first line into the using clause. Am I missing an easier way?</p>
[ { "answer_id": 327778, "author": "Howard Pinsley", "author_id": 7961, "author_profile": "https://Stackoverflow.com/users/7961", "pm_score": 0, "selected": false, "text": "Class1 c = new Class1();\n using System;\n\nnamespace DataAccessLayerTest {\n public class Class1 : IDisposable {\n public void Moo()\n {\n Console.Out.WriteLine(\"Moo\");\n }\n public void Dispose()\n {\n }\n }\n\n public class Class2 {\n public void m()\n {\n Class1 c = new Class1();\n c.Moo();\n }\n }\n}\n" }, { "answer_id": 426810, "author": "SwampyFox", "author_id": 32044, "author_profile": "https://Stackoverflow.com/users/32044", "pm_score": 1, "selected": false, "text": "1 IList<Supplier> returnValue;\n2 ISession session = SessionProvider.GetSession();\n3 returnValue = session.CreateQuery(\"select from Supplier s\").List<Supplier>();\n4 return returnValue;\n 1 IList<Supplier> returnValue;\n2 using (ISession session = SessionProvider.GetSession())\n3 {\n4 returnValue = session.CreateQuery(\"select from Supplier s\").List<Supplier>();\n5 }\n6 return returnValue;\n" }, { "answer_id": 30773894, "author": "Matas Vaitkevicius", "author_id": 1509764, "author_profile": "https://Stackoverflow.com/users/1509764", "pm_score": 0, "selected": false, "text": "using" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
326,390
<p>I've been using the idiom below for some time now. And it seems to be the most wide-spread, at least on the sites I've visited.</p> <p>Is there a better/different way to read a file into a string in Java?</p> <pre><code>private String readFile(String file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader (file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); String ls = System.getProperty("line.separator"); try { while((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append(ls); } return stringBuilder.toString(); } finally { reader.close(); } } </code></pre>
[ { "answer_id": 326413, "author": "DaWilli", "author_id": 33974, "author_profile": "https://Stackoverflow.com/users/33974", "pm_score": 9, "selected": false, "text": "org.apache.commons.io.FileUtils.readFileToString() File String import java.io.*;\nimport java.nio.charset.*;\nimport org.apache.commons.io.*;\n\npublic String readFile() throws IOException {\n File file = new File(\"data.txt\");\n return FileUtils.readFileToString(file, StandardCharsets.UTF_8);\n}\n" }, { "answer_id": 326430, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "open(file).read()" }, { "answer_id": 326440, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 12, "selected": true, "text": "String String content = Files.readString(path, encoding);\n static String readFile(String path, Charset encoding)\n throws IOException\n{\n byte[] encoded = Files.readAllBytes(Paths.get(path));\n return new String(encoded, encoding);\n}\n List<String> List<String> lines = Files.readAllLines(Paths.get(path), encoding);\n Files.lines() Stream<String> IOException UncheckedIOException Stream try (Stream<String> lines = Files.lines(path, encoding)) {\n lines.forEach(System.out::println);\n}\n Stream close() Stream close() lines() BufferedReader StandardCharsets String content = readFile(\"test.txt\", StandardCharsets.UTF_8);\n Charset String content = readFile(\"test.txt\", Charset.defaultCharset());\n" }, { "answer_id": 326448, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 6, "selected": false, "text": "private String readFile(String pathname) throws IOException {\n\n File file = new File(pathname);\n StringBuilder fileContents = new StringBuilder((int)file.length()); \n\n try (Scanner scanner = new Scanner(file)) {\n while(scanner.hasNextLine()) {\n fileContents.append(scanner.nextLine() + System.lineSeparator());\n }\n return fileContents.toString();\n }\n}\n" }, { "answer_id": 326531, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": false, "text": "java.nio.charset.Charset public static String readFile(String file, String csName)\n throws IOException {\n Charset cs = Charset.forName(csName);\n return readFile(file, cs);\n}\n\npublic static String readFile(String file, Charset cs)\n throws IOException {\n // No real need to close the BufferedReader/InputStreamReader\n // as they're only wrapping the stream\n FileInputStream stream = new FileInputStream(file);\n try {\n Reader reader = new BufferedReader(new InputStreamReader(stream, cs));\n StringBuilder builder = new StringBuilder();\n char[] buffer = new char[8192];\n int read;\n while ((read = reader.read(buffer, 0, buffer.length)) > 0) {\n builder.append(buffer, 0, read);\n }\n return builder.toString();\n } finally {\n // Potential issue here: if this throws an IOException,\n // it will mask any others. Normally I'd use a utility\n // method which would log exceptions and swallow them\n stream.close();\n } \n}\n" }, { "answer_id": 326612, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 3, "selected": false, "text": "for(String line = reader.readLine(); line != null; line = reader.readLine()) {\n stringBuilder.append(line);\n stringBuilder.append(ls);\n}\n" }, { "answer_id": 2224417, "author": "Scott S. McCoy", "author_id": 198676, "author_profile": "https://Stackoverflow.com/users/198676", "pm_score": 2, "selected": false, "text": "public static String slurp (final File file)\nthrows IOException {\n StringBuilder result = new StringBuilder();\n\n BufferedReader reader = new BufferedReader(new FileReader(file));\n\n try {\n char[] buf = new char[1024];\n\n int r = 0;\n\n while ((r = reader.read(buf)) != -1) {\n result.append(buf, 0, r);\n }\n }\n finally {\n reader.close();\n }\n\n return result.toString();\n}\n" }, { "answer_id": 2224519, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 6, "selected": false, "text": "import com.google.common.base.Charsets;\nimport com.google.common.io.Files;\n\n// ...\n\nString text = Files.toString(new File(path), Charsets.UTF_8);\n Files#toString Files.asCharSource(new File(path), StandardCharsets.UTF_8).read(); InputStream in = new FileInputStream(file);\nbyte[] b = new byte[file.length()];\nint len = b.length;\nint total = 0;\n\nwhile (total < len) {\n int result = in.read(b, total, len - total);\n if (result == -1) {\n break;\n }\n total += result;\n}\n\nreturn new String( b , Charsets.UTF_8 );\n" }, { "answer_id": 2661480, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 4, "selected": false, "text": "public static String readFileAsString(String filePath) throws IOException {\n DataInputStream dis = new DataInputStream(new FileInputStream(filePath));\n try {\n long len = new File(filePath).length();\n if (len > Integer.MAX_VALUE) throw new IOException(\"File \"+filePath+\" too large, was \"+len+\" bytes.\");\n byte[] bytes = new byte[(int) len];\n dis.readFully(bytes);\n return new String(bytes, \"UTF-8\");\n } finally {\n dis.close();\n }\n}\n" }, { "answer_id": 7449797, "author": "Pablo Grisafi", "author_id": 254307, "author_profile": "https://Stackoverflow.com/users/254307", "pm_score": 8, "selected": false, "text": "Scanner Scanner scanner = new Scanner( new File(\"poem.txt\") );\nString text = scanner.useDelimiter(\"\\\\A\").next();\nscanner.close(); // Put this call in a finally block\n Scanner scanner = new Scanner( new File(\"poem.txt\"), \"UTF-8\" );\nString text = scanner.useDelimiter(\"\\\\A\").next();\nscanner.close(); // Put this call in a finally block\n scanner.close() try (Scanner scanner = new Scanner( new File(\"poem.txt\"), \"UTF-8\" )) {\n String text = scanner.useDelimiter(\"\\\\A\").next();\n}\n Scanner IOException java.io java.util" }, { "answer_id": 7796072, "author": "Home in Time", "author_id": 999478, "author_profile": "https://Stackoverflow.com/users/999478", "pm_score": 5, "selected": false, "text": "public static String readFileToString(File file) throws IOException\n public static List<String> readLines(File file) throws IOException\n" }, { "answer_id": 7864972, "author": "barjak", "author_id": 112053, "author_profile": "https://Stackoverflow.com/users/112053", "pm_score": 2, "selected": false, "text": "RandomAccessFile.readFully public static String readFileContent(String filename, Charset charset) throws IOException {\n RandomAccessFile raf = null;\n try {\n raf = new RandomAccessFile(filename, \"r\");\n byte[] buffer = new byte[(int)raf.length()];\n raf.readFully(buffer);\n return new String(buffer, charset);\n } finally {\n closeStream(raf);\n }\n} \n\n\nprivate static void closeStream(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException ex) {\n // do nothing\n }\n }\n}\n" }, { "answer_id": 9291920, "author": "wau", "author_id": 1061891, "author_profile": "https://Stackoverflow.com/users/1061891", "pm_score": 2, "selected": false, "text": "Reader input = new FileReader();\nStringWriter output = new StringWriter();\ntry {\n IOUtils.copy(input, output);\n} finally {\n input.close();\n}\nString fileContents = output.toString();\n" }, { "answer_id": 10176143, "author": "user590444", "author_id": 590444, "author_profile": "https://Stackoverflow.com/users/590444", "pm_score": 6, "selected": false, "text": "import java.nio.file.Files;\n String readFile(String filename) {\n File f = new File(filename);\n try {\n byte[] bytes = Files.readAllBytes(f.toPath());\n return new String(bytes,\"UTF-8\");\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n" }, { "answer_id": 15428420, "author": "Henry", "author_id": 863519, "author_profile": "https://Stackoverflow.com/users/863519", "pm_score": 2, "selected": false, "text": "fileInputStream.available() public String readStringFromInputStream(FileInputStream fileInputStream) {\n StringBuffer stringBuffer = new StringBuffer();\n try {\n byte[] buffer;\n while (fileInputStream.available() > 0) {\n buffer = new byte[fileInputStream.available()];\n fileInputStream.read(buffer);\n stringBuffer.append(new String(buffer, \"ISO-8859-1\"));\n }\n } catch (FileNotFoundException e) {\n } catch (IOException e) { }\n return stringBuffer.toString();\n}\n" }, { "answer_id": 20563130, "author": "Ajk", "author_id": 1521167, "author_profile": "https://Stackoverflow.com/users/1521167", "pm_score": 2, "selected": false, "text": "private String readFile(String pathname) throws IOException {\n\nFile file = new File(pathname);\nStringBuilder fileContents = new StringBuilder((int)file.length());\nScanner scanner = new Scanner(file);\nString lineSeparator = System.getProperty(\"line.separator\");\n\ntry {\n while(scanner.hasNextLine()) { \n fileContents.append(scanner.nextLine() + lineSeparator);\n }\n return fileContents.toString();\n} finally {\n scanner.close();\n}\n}\n private String readFile(String pathname) throws IOException {\n File file = new File(pathname);\n StringBuilder fileContents = new StringBuilder((int) file.length());\n Scanner scanner = new Scanner(new BufferedReader(new FileReader(file)));\n String lineSeparator = System.getProperty(\"line.separator\");\n\n try {\n if (scanner.hasNextLine()) {\n fileContents.append(scanner.nextLine());\n }\n while (scanner.hasNextLine()) {\n fileContents.append(lineSeparator + scanner.nextLine());\n }\n return fileContents.toString();\n } finally {\n scanner.close();\n }\n}\n" }, { "answer_id": 26626047, "author": "Andrei N", "author_id": 278345, "author_profile": "https://Stackoverflow.com/users/278345", "pm_score": 6, "selected": false, "text": "String result = Files.lines(Paths.get(\"file.txt\"))\n .parallel() // for parallel processing \n .map(String::trim) // to change line \n .filter(line -> line.length() > 2) // to filter some lines by a predicate \n .collect(Collectors.joining()); // to join lines\n sample/lambda/BulkDataOperations String out = String.join(\"\\n\", Files.readAllLines(Paths.get(\"file.txt\")));\n" }, { "answer_id": 27805207, "author": "Ilya Gazman", "author_id": 1129332, "author_profile": "https://Stackoverflow.com/users/1129332", "pm_score": 3, "selected": false, "text": "Files static String readFile(File file, String charset)\n throws IOException\n{\n FileInputStream fileInputStream = new FileInputStream(file);\n byte[] buffer = new byte[fileInputStream.available()];\n int length = fileInputStream.read(buffer);\n fileInputStream.close();\n return new String(buffer, 0, length, charset);\n}\n" }, { "answer_id": 33983716, "author": "Haakon Løtveit", "author_id": 1418838, "author_profile": "https://Stackoverflow.com/users/1418838", "pm_score": 2, "selected": false, "text": "public String fileToString(File file, Charset charset) {\n Scanner fileReader = new Scanner(file, charset);\n fileReader.useDelimiter(\"\\\\Z\"); // \\Z means EOF.\n String out = fileReader.next();\n fileReader.close();\n return out;\n}\n" }, { "answer_id": 36724425, "author": "Moritz Petersen", "author_id": 1277252, "author_profile": "https://Stackoverflow.com/users/1277252", "pm_score": 4, "selected": false, "text": "String content = new String(Files.readAllBytes(Paths.get(filename)), \"UTF-8\");\n java.nio.file String content = Files.readString(path);\n" }, { "answer_id": 40299794, "author": "Jobin", "author_id": 2893693, "author_profile": "https://Stackoverflow.com/users/2893693", "pm_score": 7, "selected": false, "text": "import java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\n String content = new String(Files.readAllBytes(Paths.get(\"readMe.txt\")), StandardCharsets.UTF_8);\n String content = Files.readString(Paths.get(\"readMe.txt\"));\n" }, { "answer_id": 40994903, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "import java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.stream.Stream;\n\npublic Class ReadFile{\n public static String readFile(String filePath) {\n StringBuilder stringBuilder = new StringBuilder();\n String ls = System.getProperty(\"line.separator\");\n try {\n\n try (Stream<String> lines = Files.lines(Paths.get(filePath), StandardCharsets.UTF_8)) {\n for (String line : (Iterable<String>) lines::iterator) {\n\n\n stringBuilder.append(line);\n stringBuilder.append(ls);\n\n\n }\n }\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return stringBuilder.toString(); \n\n\n}\n\n}\n" }, { "answer_id": 41077389, "author": "satnam", "author_id": 210791, "author_profile": "https://Stackoverflow.com/users/210791", "pm_score": 2, "selected": false, "text": "String data = IO.from(new File(\"data.txt\")).toString();\n" }, { "answer_id": 41670919, "author": "Devram Kandhare", "author_id": 2206934, "author_profile": "https://Stackoverflow.com/users/2206934", "pm_score": 1, "selected": false, "text": "File file = new File(\"input.txt\");\nBufferedInputStream bin = new BufferedInputStream(new FileInputStream(\n file));\nbyte[] buffer = new byte[(int) file.length()];\nbin.read(buffer);\nString fileStr = new String(buffer);\n" }, { "answer_id": 42082895, "author": "jamesjara", "author_id": 762956, "author_profile": "https://Stackoverflow.com/users/762956", "pm_score": 2, "selected": false, "text": " try\n{\n String content = new Scanner(new File(\"file.txt\")).useDelimiter(\"\\\\Z\").next();\n System.out.println(content);\n}\ncatch(FileNotFoundException e)\n{\n System.out.println(\"not found!\");\n}\n" }, { "answer_id": 42260208, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "public String fromFileInJar(String path) {\n try ( Scanner scanner \n = new Scanner(getClass().getResourceAsStream(path))) {\n return scanner.useDelimiter(\"\\\\A\").next();\n }\n}\n / my.jar/com/some/thing/a.txt\n String myTxt = fromFileInJar(\"/com/com/thing/a.txt\");\n" }, { "answer_id": 42800158, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 2, "selected": false, "text": "String sMessage = String.join(\"\\n\", reader.lines().collect(Collectors.toList()));\n" }, { "answer_id": 49598618, "author": "Muskovets", "author_id": 7013460, "author_profile": "https://Stackoverflow.com/users/7013460", "pm_score": 2, "selected": false, "text": "public String readAll(String fileName) throws IOException {\n List<String> lines = Files.readAllLines(new File(fileName).toPath());\n return String.join(\"\\n\", lines.toArray(new String[lines.size()]));\n}\n" }, { "answer_id": 50581691, "author": "Yash", "author_id": 5081877, "author_profile": "https://Stackoverflow.com/users/5081877", "pm_score": 5, "selected": false, "text": "Resources Files static Charset charset = com.google.common.base.Charsets.UTF_8;\npublic static String guava_ServerFile( URL url ) throws IOException {\n return Resources.toString( url, charset );\n}\npublic static String guava_DiskFile( File file ) throws IOException {\n return Files.toString( file, charset );\n}\n static Charset encoding = org.apache.commons.io.Charsets.UTF_8;\npublic static String commons_IOUtils( URL url ) throws IOException {\n java.io.InputStream in = url.openStream();\n try {\n return IOUtils.toString( in, encoding );\n } finally {\n IOUtils.closeQuietly(in);\n }\n}\npublic static String commons_FileUtils( File file ) throws IOException {\n return FileUtils.readFileToString( file, encoding );\n /*List<String> lines = FileUtils.readLines( fileName, encoding );\n return lines.stream().collect( Collectors.joining(\"\\n\") );*/\n}\n public static String streamURL_Buffer( URL url ) throws IOException {\n java.io.InputStream source = url.openStream();\n BufferedReader reader = new BufferedReader( new InputStreamReader( source ) );\n //List<String> lines = reader.lines().collect( Collectors.toList() );\n return reader.lines().collect( Collectors.joining( System.lineSeparator() ) );\n}\npublic static String streamFile_Buffer( File file ) throws IOException {\n BufferedReader reader = new BufferedReader( new FileReader( file ) );\n return reader.lines().collect(Collectors.joining(System.lineSeparator()));\n}\n \\A static String charsetName = java.nio.charset.StandardCharsets.UTF_8.toString();\npublic static String streamURL_Scanner( URL url ) throws IOException {\n java.io.InputStream source = url.openStream();\n Scanner scanner = new Scanner(source, charsetName).useDelimiter(\"\\\\A\");\n return scanner.hasNext() ? scanner.next() : \"\";\n}\npublic static String streamFile_Scanner( File file ) throws IOException {\n Scanner scanner = new Scanner(file, charsetName).useDelimiter(\"\\\\A\");\n return scanner.hasNext() ? scanner.next() : \"\";\n}\n java.nio.file.Files.readAllBytes public static String getDiskFile_Java7( File file ) throws IOException {\n byte[] readAllBytes = java.nio.file.Files.readAllBytes(Paths.get( file.getAbsolutePath() ));\n return new String( readAllBytes );\n}\n BufferedReader InputStreamReader public static String getDiskFile_Lines( File file ) throws IOException {\n StringBuffer text = new StringBuffer();\n FileInputStream fileStream = new FileInputStream( file );\n BufferedReader br = new BufferedReader( new InputStreamReader( fileStream ) );\n for ( String line; (line = br.readLine()) != null; )\n text.append( line + System.lineSeparator() );\n return text.toString();\n}\n public static void main(String[] args) throws IOException {\n String fileName = \"E:/parametarisation.csv\";\n File file = new File( fileName );\n\n String fileStream = commons_FileUtils( file );\n // guava_DiskFile( file );\n // streamFile_Buffer( file );\n // getDiskFile_Java7( file );\n // getDiskFile_Lines( file );\n System.out.println( \" File Over Disk : \\n\"+ fileStream );\n\n\n try {\n String src = \"https://code.jquery.com/jquery-3.2.1.js\";\n URL url = new URL( src );\n\n String urlStream = commons_IOUtils( url );\n // guava_ServerFile( url );\n // streamURL_Scanner( url );\n // streamURL_Buffer( url );\n System.out.println( \" File Over Network : \\n\"+ urlStream );\n } catch (MalformedURLException e) {\n e.printStackTrace();\n }\n}\n" }, { "answer_id": 50961164, "author": "Saikat", "author_id": 1594823, "author_profile": "https://Stackoverflow.com/users/1594823", "pm_score": 4, "selected": false, "text": "java.nio.file public String readStringFromFile(String filePath) throws IOException {\n String fileContent = new String(Files.readAllBytes(Paths.get(filePath)));\n return fileContent;\n}\n" }, { "answer_id": 51045324, "author": "leventov", "author_id": 648955, "author_profile": "https://Stackoverflow.com/users/648955", "pm_score": 5, "selected": false, "text": "String file = ...\nPath path = Paths.get(file);\nString content = Files.readString(path);\n// Or readString(path, someCharset), if you need a Charset different from UTF-8\n" }, { "answer_id": 53002842, "author": "Nitin", "author_id": 5672261, "author_profile": "https://Stackoverflow.com/users/5672261", "pm_score": 2, "selected": false, "text": "java.nio.Files public String readFile() throws IOException {\n File fileToRead = new File(\"file path\");\n List<String> fileLines = Files.readAllLines(fileToRead.toPath());\n return StringUtils.join(fileLines, StringUtils.EMPTY);\n}\n" }, { "answer_id": 70991313, "author": "Madhav Balakrishnan Nair", "author_id": 17678908, "author_profile": "https://Stackoverflow.com/users/17678908", "pm_score": 0, "selected": false, "text": "Scanner sc = new Scanner(new File(\"yourFile.txt\"));\nsc.useDelimiter(\"\\\\Z\");\n\nString s = sc.next();\n" }, { "answer_id": 74480704, "author": "Omkar T", "author_id": 9752209, "author_profile": "https://Stackoverflow.com/users/9752209", "pm_score": 0, "selected": false, "text": "val fileAsString = file.bufferedReader().use { it.readText() }\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20654/" ]
326,392
<p>I'm using a MSSQL database and would like to create a column that only has 4 possible values. Is there any way to define a 2-bit column? I see the bit datatype and then the next smallest is tinyint which is 1 full byte.</p> <p>If there is no such field, I'd be interesting in finding out why not.</p> <p>Thanks.</p>
[ { "answer_id": 326521, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 1, "selected": false, "text": "CREATE TABLE [dbo].[testTable](\n [colA] [bit] NOT NULL,\n [colB] [bit] NOT NULL,\n [CalcCol] AS (case [colA] when (1) then (2) else (0) end+[colB])\n) ON [PRIMARY]\n CREATE TABLE [dbo].[testTable](\n [colA] [bit] NOT NULL,\n [colB] [bit] NOT NULL,\n [CalcCol] As \n (Case ColA \n When 0 Then Case ColB WHen 0 Then ValueA Else ValueB End\n Else Case ColB WHen 0 Then ValueC Else ValueD End\n End)\n) ON [PRIMARY]\n Update TestTable Set \n colA = Case When Value In (ValueA, ValueB) Then 0 Else 1 End, \n colB = Case When Value In (ValueA, ValueC) Then 0 Else 1 End \nWhere ... \n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41662/" ]
326,393
<p>Can someone show me how to fix the width of a column in a datatable with JSF?</p> <p>My code currently reads:</p> <pre><code>&lt;h:column&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="Data Field 1" /&gt; &lt;/f:facet&gt; &lt;h:commandLink id="dataLink" action="#{pc_SearchResultsFragment.setField1}"&gt; &lt;h:outputText value="#{(qi.data1 != null) ? '' : qi.data1}"/&gt; &lt;/h:commandLink&gt; &lt;/h:column&gt; </code></pre> <p>Thanks!</p>
[ { "answer_id": 326565, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": -1, "selected": true, "text": "<h:column>\n <f:facet name=\"header\">\n <h:outputText value=\"Data Field 1\" />\n </f:facet>\n <h:commandLink id=\"dataLink\" action=\"#{pc_SearchResultsFragment.setField1}\">\n <h:outputText value=\"#{(qi.data1 != null) ? '' : qi.data1}\"/> \n </h:commandLink>\n <%-- <f:attribute name=\"width\" value=\"20\" /> fixed width --%>\n <%-- or --%>\n <%-- <f:attribute name=\"width\" value=\"20%\" /> percentage --%>\n\n <%-- also available (not a complete list, just some of the more\n common supported attributes) --%>\n <%-- <f:attribute name=\"align\" value=\"left\" /> --%>\n <%-- <f:attribute name=\"height\" value=\"20\" /> --%>\n <%-- <f:attribute name=\"nowrap\" value=\"true\" /> --%>\n <%-- <f:attribute name=\"valign\" value=\"top\" /> --%>\n <%-- <f:attribute name=\"bgcolor\" value=\"red\" /> --%>\n <%-- <f:attribute name=\"style\" value=\"color:White;\" /> --%>\n</h:column>\n" }, { "answer_id": 327660, "author": "Alexandru Luchian", "author_id": 32188, "author_profile": "https://Stackoverflow.com/users/32188", "pm_score": 4, "selected": false, "text": "<h:dataTable value=\"#{action.items}\" var=\"name\" \nstyleClass=\"tableClass\" columnClasses=\"first,second\">\n .first {\n\n width: 250px;\n\n}\n" }, { "answer_id": 46302967, "author": "Cem Hünerkar", "author_id": 8627938, "author_profile": "https://Stackoverflow.com/users/8627938", "pm_score": 0, "selected": false, "text": "style <h:column pt:style=\"width:20px;text-align:center;\"></h:column>\n <td style=\"width:20px;text-align:center;\"></td>\n xmlns:pt=\"http://xmlns.jcp.org/jsf/passthrough\"" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23249/" ]
326,396
<p>I am working with:</p> <pre><code>#top ul li.corner span.right-corner:hover { background-image:url("images/corner-right-over.gif"); width:4px; height:15px; float:left; } #top ul li.corner span.left-corner:hover { background-image:url("images/corner-left-over.gif"); float:left; width:4px; height:15px; } </code></pre> <p>And I can't seem to get the <code>:hover</code> working properly? Not sure why, does anyone have any suggestions?</p>
[ { "answer_id": 326427, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": ":hover <a>" }, { "answer_id": 326515, "author": "defeated", "author_id": 16997, "author_profile": "https://Stackoverflow.com/users/16997", "pm_score": 4, "selected": true, "text": "#top ul li.corner span.right-corner, #top ul li.corner span.left-corner\n{\n display: block;\n}\n" }, { "answer_id": 12495983, "author": "ZeeshanIqbal", "author_id": 1683234, "author_profile": "https://Stackoverflow.com/users/1683234", "pm_score": 3, "selected": false, "text": "<!DOCTYPE html>" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,405
<p>I have an abstract base class and derived class:</p> <pre><code>type TInterfaceMethod = class public destructor Destroy; virtual; abstract; procedure Calculate; virtual; abstract; procedure PrepareForWork; virtual; abstract; end; type ConcreteMethod = class(TInterfaceMethod) private matrix: TMinMatrix; public constructor Create(var matr: TMinMatrix); procedure Calculate; override; procedure PrepareForWork; override; destructor Destroy; end; </code></pre> <p>Do I really need to make base-class destructor virtual, as in C++, or it`ll be OK if it is not virtual?<br> By the way, did I use "override" right or I need "overload"?</p>
[ { "answer_id": 326456, "author": "gabr", "author_id": 4997, "author_profile": "https://Stackoverflow.com/users/4997", "pm_score": 3, "selected": true, "text": "type\n TInterfaceMethod = class abstract\n public\n destructor Destroy; override; abstract;\n procedure Calculate; virtual; abstract;\n procedure PrepareForWork; virtual; abstract;\n end;\n\n TConcreteMethod = class(TInterfaceMethod)\n private\n matrix: TMinMatrix;\n public\n constructor Create(var matr: TMinMatrix);\n procedure Calculate; override;\n procedure PrepareForWork; override;\n destructor Destroy; override;\n end;\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28298/" ]
326,425
<p>I have a problem with formatting the data when doing an query to an Oracle database.</p> <p>What I want to do is to export some data into the formatbelow into a textfile;</p> <pre><code> 1IN20071001 40005601054910101200 1 65 </code></pre> <ul> <li>First number (1 above) = Company number (position 1-5, blanks infront)</li> <li>IN or UT = IN for clockin and UT for clockout (position 6-7)</li> <li>20071001 = Date(business date) in the format YYYYMMDD (pos 8-15)</li> <li>400056010549 = EmployeeID (pos 16-33, right alignment, blanks infront)</li> <li>101012 = Time in format TTMMSS (pos 34-39)</li> <li>00 = FT, always 00 (pos 40-41)</li> <li>Blanks = Always 8 empty spaces (pos 42-49)</li> <li>1 = Not sure what this is used for, but it should always be 1 (pos 50, right alignment, blanks infront)</li> <li>65 = “Kostnadsställe”, ENT_HR_EMPLOYEE.USERALPHA6 (pos 51-55, right alignment, blanks infront)</li> </ul> <p>Currently I'm using the query below, but this is where my SQL knowledge ends... </p> <pre><code>COLUMN one FORMAT a5 HEADER JUSTIFY RIGHT COLUMN two FORMAT a8 HEADER two COLUMN three FORMAT a18 HEADER three JUSTIFY RIGHT COLUMN four FORMAT a5 HEADER three JUSTIFY RIGHT SELECT h.fkod AS one, 'IN', SUBSTR(t.clockindatetime,0,4) || SUBSTR(t.clockindatetime,6,2) || SUBSTR(t.clockindatetime,9,2) AS two, i.employeeid AS three SUBSTR(t.clockindatetime,11,6) || '00 1', h.fkod AS four FROM ent_time_card_detail t, max_employeeid_history i, ent_hr_employee h WHERE h.enthremployeeid = t.enthremployeeid AND h.payrollid = i.userid AND t.clockindatetime &gt;= i.from_date AND (t.clockindatetime &lt; i.to_date OR i.to_date IS NULL); </code></pre> <p>Any SQL-pro's out there that can help me finish the formatting?</p>
[ { "answer_id": 326459, "author": "hamishmcn", "author_id": 3590, "author_profile": "https://Stackoverflow.com/users/3590", "pm_score": 2, "selected": false, "text": "TO_CHAR(t.clockindatetime, 'YYYYMMDD') TO_CHAR(t.clockindatetime, 'HHMISS') TO_CHAR(t.clockindatetime, 'HH24MISS')" }, { "answer_id": 326758, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SELECT lpad('1',5) || 'IN' ||\n TO_CHAR(t.clockindatetime, 'YYYYMMDD') ||\n lpad(i.employeeid,18) ||\n TO_CHAR(t.clockindatetime, 'HH24MISS') ||\n '00 1' ||\n lpad('h.useralpha6',5)\nFROM ent_time_card_detail t,\n max_employeeid_history i,\n ent_hr_employee h\nWHERE h.enthremployeeid = t.enthremployeeid\nAND h.payrollid = i.userid\nAND t.clockindatetime >= i.from_date\nAND (t.clockindatetime < i.to_date OR i.to_date IS NULL);\n 1IN20081106 1234123412101500 1 64 \n 1IN20081106 234512385100 1 64 \n 1IN20081107 234515261900 1 64 \n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,429
<p>I teach the third required intro course in a CS department. One of my homework assignments asks students to speed up code they have written for a previous assignment. Factor-of-ten speedups are routine; factors of 100 or 1000 are not unheard of. (For a factor of 1000 speedup you have to have made rookie mistakes with malloc().)</p> <p>Programs are improved by a sequence is small changes. I ask students to record and describe each change and the resulting improvement.</p> <p>While you're improving a program it is also possible to break it. Wouldn't it be nice to back out?</p> <p>You can see where I'm going with this: my students would benefit enormously from version control. But there are some caveats:</p> <ul> <li>Our computing environment is locked down. Anything that depends on a central repository is suspect.</li> <li>Our students are incredibly overloaded. Not just classes but jobs, sports, music, you name it. For them to use a new tool it has to be incredibly easy and have obvious benefits.</li> <li>Our students do most work in pairs. Getting bits back and forth between accounts is problematic. Could this problem also be solved by distributed version control?</li> <li>Complexity is the enemy. I know setting up a CVS repository is too baffling---I myself still have trouble because I only do it once a year. I'm told SVN is even harder.</li> </ul> <p>Here are my comments on existing systems:</p> <ul> <li>I think central version control (CVS or SVN) is ruled out because our students don't have the administrative privileges needed to make a repository that they can share with one other student. (We are stuck with Unix file permissions.) Also, setup on CVS or SVN is too hard.</li> <li>darcs is way easy to set up, but it's not obvious how you share things. darcs send (to send patches by email) seems promising but it's not clear how to set it up.</li> <li>The introductory documentation for git is not for beginners. Like CVS setup, it's something I myself have trouble with.</li> </ul> <p>I'm soliciting suggestions for what source-control to use with beginning students. I suspect we can find resources to put a thin veneer over an existing system and to simplify existing documentation. We probably don't have resources to write new documentation. </p> <p>So, what's really easy to <strong>setup</strong>, <strong>commit</strong>, <strong>revert</strong>, and <strong>share changes with a partner</strong> but does not have to be easy to merge or to work at scale? </p> <p>A key constraint is that <strong>programming pairs have to be able to share work with each other and only each other</strong>, and <strong>pairs change every week</strong>. Our infrastructure is Linux, Solaris, and Windows with a netapp filer. I doubt my IT staff wants to create a Unix group for each pair of students. Is there an easier solution I've overlooked?</p> <p>(Thanks for the accepted answer, which beats the others on account of its excellent reference to <a href="http://www-cs-students.stanford.edu/~blynn/gitmagic/" rel="noreferrer">Git Magic</a> as well as the helpful comments.)</p>
[ { "answer_id": 885773, "author": "cjs", "author_id": 107294, "author_profile": "https://Stackoverflow.com/users/107294", "pm_score": 2, "selected": false, "text": "$ svnadmin create /home/cjs/repo\n$ mkdir my-project\n$ cd my-project\n$ vi hello.c\n [...hack hack hack...]\n$ svn import -m 'Initial project import.' file:///home/cjs/repo\nAdding hello.c\n\nCommitted revision 1.\n" }, { "answer_id": 2019404, "author": "GS - Apologise to Monica", "author_id": 96982, "author_profile": "https://Stackoverflow.com/users/96982", "pm_score": 3, "selected": false, "text": "darcs send darcs send <remote repo> _darcs/prefs/email darcs apply <patch file> _darcs/prefs/email" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41661/" ]
326,450
<p>I want to test my Entities that are built using Entity Framework. My concern is that using Entity Framework means directly working with data source. So any ideas how to unit testing Entity Framework based components?</p>
[ { "answer_id": 7860963, "author": "James McLachlan", "author_id": 217499, "author_profile": "https://Stackoverflow.com/users/217499", "pm_score": 3, "selected": false, "text": "<add name=\"DrinksEntities\" \n connectionString=\"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient\n ;provider connection string=&quot;Data Source=localhost\\sqlexpress;Initial Catalog=Drinks2;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;\" \n providerName=\"System.Data.EntityClient\" />\n <add name=\"DrinksEntities\" \n connectionString=\"metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient\n ;provider connection string=&quot;Data Source=.\\SQLEXPRESS;attachdbfilename=|DataDirectory|\\Inventory.mdf;Integrated Security=True;user instance=True;MultipleActiveResultSets=True;Application Name=EntityFramework&quot;\" \n providerName=\"System.Data.EntityClient\" />\n" }, { "answer_id": 16990817, "author": "Yaur", "author_id": 184025, "author_profile": "https://Stackoverflow.com/users/184025", "pm_score": 2, "selected": false, "text": "public interface IRepository\n{\n IQueryable<T> GetObjectSet<T>();\n}\n public interface IQuery<T>\n{\n IQueryable<T> DoQuery(IQueryable<T> collection);\n}\n [TestMethod]\npublic void TestQueryFoo()\n{\n using(var repo = new SqlRepository(\"bogus connection string\"))\n {\n var query = new FooQuery(); // implements IQuery<Foo>\n var result = query.DoQuery(repo.GetObjectSet<Foo>()); // as long as we don't enumerate the IQueryable EF won't notice that the connection string is bogus\n var sqlString = ((System.Data.Objects.ObjectQuery)query).ToTraceString(); // This will throw if the query can't be compiled to SQL\n }\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18908/" ]
326,454
<p>In this abbreviated code, the inline event works - the "event" is passed to the testKeyPress function </p> <pre><code>&lt;textarea id="source" onkeydown= "showCursPos(this); var tf=testKeyPress(event); document.onkeypress=function(){return tf}; document.onkeydown=function(){return tf}; " &gt;&lt;/textarea&gt; function testKeyPress(e){ if (e.ctrlKey==true ){ if (e.which == null ){kcode=e.keyCode; } // IE else if (e.which &gt; 0){kcode=e.which; } // gecko return testValidity(kcode); //returns true-false } } </code></pre> <p>However, in this anonymous version, the event is not passed in gecko: </p> <pre><code>&lt;textarea id="source"&gt;&lt;/textarea&gt; $("source").onkeydown = function(){ showCursPos(this); // this function works // next event is passed in IE, but not gecko var tf=testKeyPress(event); // remaining functions work if value is forced document.onkeypress=function(){return tf}; document.onkeydown=function(){return tf}; } </code></pre> <p>How does one pass the function's own event? </p>
[ { "answer_id": 326473, "author": "Dennis C", "author_id": 40214, "author_profile": "https://Stackoverflow.com/users/40214", "pm_score": 3, "selected": true, "text": "var e=arguments[0] || event; // Firefox via the argument, but IE don't\n <xxx onkeydown=\"func(event);\"> xxx.ononkeydown=function(event){func(event);};" }, { "answer_id": 326673, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$(\"source\").onkeydown = function(){ \n var e=arguments[0] || event; \n showCursPos(this); \n var tf=testKeyPress(e); \n document.onkeypress=function(){return tf}; \n document.onkeydown=function(){return tf}; \n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,463
<p>A remote site is supplying a data structure in a js file.</p> <p>I can include this file in my page to access the data and display it in my page.</p> <pre><code>&lt;head&gt; &lt;script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>Does anyone know how I use PHP to take this data and store in it a database?</p>
[ { "answer_id": 326469, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": true, "text": "<?php\n$url = \"http://www.example.co.uk/includes/js/data.js\";\ncurl_setopt($ch, CURLOPT_URL, $url);\ncurl_setopt($ch, CURLOPT_RETURNTRANSFER, true);\n...\n\n$output = curl_exec($ch);\n$info = curl_getinfo($ch);\n\nif ($output === false || $info['http_code'] != 200) {\n $error = \"No cURL data returned for $url [\". $info['http_code']. \"]\";\n if (curl_error($ch))\n $error .= \"\\n\". curl_error($ch);\n }\nelse {\n $js_data = json_decode($output);\n // 'OK' status; save $class members in the database, or the $output directly, \n // depending on what you want to actually do.\n ...\n}\n\n//Display $error or do something about it\n\n?>\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33167/" ]
326,476
<p>Given numbers like 499, 73433, 2348 what VBA can I use to round to the nearest 5 or 10? or an arbitrary number?</p> <p>By 5:</p> <pre><code> 499 -&gt; 500 2348 -&gt; 2350 7343 -&gt; 7345 </code></pre> <p>By 10:</p> <pre><code> 499 -&gt; 500 2348 -&gt; 2350 7343 -&gt; 7340 </code></pre> <p>etc.</p>
[ { "answer_id": 326489, "author": "Fredou", "author_id": 40868, "author_profile": "https://Stackoverflow.com/users/40868", "pm_score": 0, "selected": false, "text": "'nearest\n n = 5\n 'n = 10\n\n 'value\n v = 496\n 'v = 499 \n 'v = 2348 \n 'v = 7343\n\n 'mod\n m = (v \\ n) * n\n\n 'diff between mod and the val\n i = v-m\n\n\n if i >= (n/2) then \n msgbox m+n\n else\n msgbox m\n end if\n" }, { "answer_id": 326506, "author": "Fredou", "author_id": 40868, "author_profile": "https://Stackoverflow.com/users/40868", "pm_score": 0, "selected": false, "text": " msgbox round(1.5) 'result to 2\n msgbox round(2.5) 'yes, result to 2 too\n" }, { "answer_id": 12731182, "author": "matt wilkie", "author_id": 14420, "author_profile": "https://Stackoverflow.com/users/14420", "pm_score": 6, "selected": true, "text": "X = 1234 'number to round\nN = 5 'rounding factor\nround(X/N)*N 'result is 1235\n int(1234.564) 'result is 1235\n msgbox round(1.5) 'result to 2\nmsgbox round(2.5) 'yes, result to 2 too\n" }, { "answer_id": 19969542, "author": "ana", "author_id": 2990516, "author_profile": "https://Stackoverflow.com/users/2990516", "pm_score": 0, "selected": false, "text": "Function Round_Up(ByVal d As Double) As Integer\n Dim result As Integer\n result = Math.Round(d)\n If result >= d Then\n Round_Up = result\n Else\n Round_Up = result + 1\n End If\nEnd Function\n" }, { "answer_id": 25026426, "author": "Joey", "author_id": 3889610, "author_profile": "https://Stackoverflow.com/users/3889610", "pm_score": 2, "selected": false, "text": "a = inputbox(\"number to be rounded\")\n b = inputbox(\"Round to nearest _______ \")\n\n\n strc = Round(A/B)\n strd = strc*B\n\n\n msgbox( a & \", Rounded to the nearest \" & b & \", is\" & vbnewline & strd)\n" }, { "answer_id": 35512379, "author": "James Berard", "author_id": 5952757, "author_profile": "https://Stackoverflow.com/users/5952757", "pm_score": 1, "selected": false, "text": "Public Enum RoundingDirection\n Nearest\n Up\n Down\nEnd Enum\n\nPublic Shared Function GetRoundedNumber(ByVal number As Decimal, ByVal multiplier As Decimal, ByVal direction As RoundingDirection) As Decimal\n Dim nearestValue As Decimal = (CInt(number / multiplier) * multiplier)\n Select Case direction\n Case RoundingDirection.Nearest\n Return nearestValue\n Case RoundingDirection.Up\n If nearestValue >= number Then\n Return nearestValue\n Else\n Return nearestValue + multiplier\n End If\n Case RoundingDirection.Down\n If nearestValue <= number Then\n Return nearestValue\n Else\n Return nearestValue - multiplier\n End If\n End Select\nEnd Function\n dim decTotal as Decimal = GetRoundedNumber(CDec(499), CDec(0.05), RoundingDirection.Up)\n" }, { "answer_id": 55944194, "author": "AlexLaforge", "author_id": 3487940, "author_profile": "https://Stackoverflow.com/users/3487940", "pm_score": 0, "selected": false, "text": "'Rounds a number to the nearest unit, never exceeding the actual value\nfunction RoundToNearestOrBelow(num, r)\n\n '@param num Long/Integer/Double The number to be rounded\n '@param r Long The rounding value\n '@return OUT Long The rounded value\n\n 'Example usage :\n ' Round 47 to the nearest 5 : it will return 45\n ' Response.Write RoundToNearestBelow(47, 5)\n\n Dim OUT : OUT = num\n\n Dim rounded : rounded = Round((((num)) / r), 0) * r\n\n if (rounded =< num) then\n OUT = rounded\n else\n OUT = rounded - r\n end if\n\n 'Return\n RoundToNearestOrBelow = OUT\n\nend function 'RoundToNearestOrBelow\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14420/" ]
326,487
<p>I am working on a program which manipulates images of different sizes. Many of these manipulations read pixel data from an input and write to a separate output (e.g. blur). This is done on a per-pixel basis.</p> <p>Such image mapulations are very stressful on the CPU. I would like to use multithreading to speed things up. How would I do this? I was thinking of creating one thread per row of pixels.</p> <p>I have several requirements:</p> <ul> <li>Executable size must be minimized. In other words, I can't use massive libraries. What's the most light-weight, portable threading library for C/C++?</li> <li>Executable size must be minimized. I was thinking of having a function forEachRow(fp* ) which runs a thread for each row, or even a forEachPixel(fp* ) where fp operates on a single pixel in its own thread. Which is best? <ul> <li>Should I use normal functions or functors or functionoids or some lambda functions or ... something else?</li> <li>Some operations use optimizations which require information from the previous pixel processed. This makes forEachRow favorable. Would using forEachPixel be better even considering this?</li> </ul></li> <li>Would I need to lock my read-only and write-only arrays? <ul> <li>The input is only read from, but many operations require input from more than one pixel in the array.</li> <li>The ouput is only written once per pixel.</li> </ul></li> <li>Speed is also important (of course), but optimize executable size takes precedence.</li> </ul> <p>Thanks.</p> <p><strong>More information on this topic for the curious: <a href="https://stackoverflow.com/questions/615264/c-parallelization-libraries-openmp-vs-thread-building-blocks">C++ Parallelization Libraries: OpenMP vs. Thread Building Blocks</a></strong></p>
[ { "answer_id": 326493, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 3, "selected": false, "text": "boost::thread boost::gil" }, { "answer_id": 326523, "author": "Vilx-", "author_id": 41360, "author_profile": "https://Stackoverflow.com/users/41360", "pm_score": 0, "selected": false, "text": "#ifdef" }, { "answer_id": 326524, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 4, "selected": true, "text": "#pragma omp #pragma omp parallel for\nfor (i=0; i < numPixels; i++)\n{\n pGrayScaleBitmap[i] = (unsigned BYTE)\n (pRGBBitmap[i].red * 0.299 +\n pRGBBitmap[i].green * 0.587 +\n pRGBBitmap[i].blue * 0.114);\n}\n" }, { "answer_id": 327143, "author": "Mr.Ree", "author_id": 37946, "author_profile": "https://Stackoverflow.com/users/37946", "pm_score": 4, "selected": false, "text": "* pthread_create, pthread_detach.\n* pthread_mutexattr_init, pthread_mutexattr_settype, pthread_mutex_init,\n* pthread_mutexattr_destroy, pthread_mutex_destroy, pthread_mutex_lock,\n* pthread_mutex_trylock, pthread_mutex_unlock, pthread_mutex_timedlock.\n* sem_init, sem_destroy, sem_post, sem_wait, sem_trywait, sem_timedwait.\n /*ThreadA:*/ while(1){ mutex.lock(); printf(\"a\\n\"); usleep(100000); mutex.unlock(); }\n/*ThreadB:*/ while(1){ mutex.lock(); printf(\"b\\n\"); usleep(100000); mutex.unlock(); }\n" }, { "answer_id": 2072850, "author": "Rick", "author_id": 67753, "author_profile": "https://Stackoverflow.com/users/67753", "pm_score": 1, "selected": false, "text": "#pragma omp parallel for \nfor (i=0; i < numPixels; i++) \n{ ...} \n parallel_for(0,numPixels,1,ToGrayScale());\n parallel_for(0,numPixels,1,[&](int i)\n{ \n pGrayScaleBitmap[i] = (unsigned BYTE) \n (pRGBBitmap[i].red * 0.299 + \n pRGBBitmap[i].green * 0.587 + \n pRGBBitmap[i].blue * 0.114); \n});\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39992/" ]
326,509
<p>I am looking for the best way to make my desktop java program run in the background (<strong>daemon/service</strong>?) across most platforms (Windows, Mac OS, Linux [Ubuntu in particular]).</p> <p>By "best way" I am hoping to find a way that will:</p> <ol> <li>require a <strong>minimum</strong> amount of platform-specific code. </li> <li>not require the user to do anything a general computer user couldn't/wouldn't do </li> <li>not be a resource hog.</li> </ol> <p>I understand that my requirements may be unrealistic but I am hoping there is some sort of "best practice" for this type of situation.</p> <p>How to go forward?</p>
[ { "answer_id": 398959, "author": "pro", "author_id": 352728, "author_profile": "https://Stackoverflow.com/users/352728", "pm_score": 4, "selected": false, "text": "* void load(String[] arguments): Here open the configuration files, create the trace file, create the ServerSockets, the Threads\n* void start(): Start the Thread, accept incoming connections\n* void stop(): Inform the Thread to live the run(), close the ServerSockets\n* void destroy(): Destroy any object created in init()\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24998/" ]
326,558
<p>If I have srand(2) declared in my main of my driver file, do I need to declare srand(2) in my code file which is being linked with my driver?</p> <p>Thanks.</p> <p><strong>edit</strong></p> <p>(from user's comment below)</p> <p>If I do,</p> <pre><code>srand(2); srand(2); </code></pre> <p>will I get the seed as 2? or something else?</p>
[ { "answer_id": 326564, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 1, "selected": false, "text": "#include <stdlib.h> // Driver.cpp\n#include <stdlib.h>\n#include \"otherfile.h\"\n\nint main()\n{\n srand(2);\n Somefunc();\n}\n // OtherFile.cpp\n#include <stdlib.h>\n#include \"otherfile.h\"\n\nvoid SomeFunc()\n{\n // You don't need to call srand() here, since it's already been called in driver.cpp\n int j = rand();\n}\n" }, { "answer_id": 1343298, "author": "Brian", "author_id": 2831, "author_profile": "https://Stackoverflow.com/users/2831", "pm_score": 0, "selected": false, "text": "srand(2);\nsrand(2);\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,571
<p>I have a string with a length that is a multiple of 8 that contains only 0's and 1's. I want to convert the string into a byte array suitable for writing to a file. For instance, if I have the string "0010011010011101", I want to get the byte array [0x26, 0x9d], which, when written to file, will give 0x269d as the binary (raw) contents.</p> <p>How can I do this in Python?</p>
[ { "answer_id": 326587, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": ">>> s = \"0010011010011101\"\n>>> [int(s[x:x+8], 2) for x in range(0, len(s), 8)]\n[38, 157]\n" }, { "answer_id": 326594, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "py> data = \"0010011010011101\"\npy> data = [data[8*i:8*(i+1)] for i in range(len(data)/8)]\npy> data\n['00100110', '10011101']\npy> data = [int(i, 2) for i in data]\npy> data\n[38, 157]\npy> data = ''.join(chr(i) for i in data)\npy> data\n'&\\x9d'\n" }, { "answer_id": 326614, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import array\nintList= [int(s[x:x+8], 2) for x in range(0, len(s), 8)]\nbyteArray= array.array('B', intList)\n" }, { "answer_id": 68200364, "author": "shrewmouse", "author_id": 2464381, "author_profile": "https://Stackoverflow.com/users/2464381", "pm_score": 0, "selected": false, "text": ">>> import math,sys\n>>> s='0010011010011101'\n>>> int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder)\nb'\\x9d&'\n>>> with open('/tmp/blah', 'wb') as f:\n... f.write(int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder))\n... \n2\n>>> quit()\n [root@localhost prbs]# od -x /tmp/blah\n0000000 269d\n0000002\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5624/" ]
326,580
<p>I am using the following jquery code:</p> <pre><code>$("#top ul li.corner").mouseover(function(){ $("span.left-corner").addClass("left-corner-hover"); $("span.right-corner").addClass("right-corner-hover"); $("span.content").addClass("content-hover"); }).mouseout(function(){ $("span.left-corner").removeClass("left-corner-hover"); $("span.right-corner").removeClass("right-corner-hover"); $("span.content").removeClass("content-hover"); }); </code></pre> <p>But as you see in the selector that is going to do every li.corner that the mouse is over. i am trying to get it to do only the one the mouse is over, how would I achieve that?</p>
[ { "answer_id": 326587, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": ">>> s = \"0010011010011101\"\n>>> [int(s[x:x+8], 2) for x in range(0, len(s), 8)]\n[38, 157]\n" }, { "answer_id": 326594, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 4, "selected": true, "text": "py> data = \"0010011010011101\"\npy> data = [data[8*i:8*(i+1)] for i in range(len(data)/8)]\npy> data\n['00100110', '10011101']\npy> data = [int(i, 2) for i in data]\npy> data\n[38, 157]\npy> data = ''.join(chr(i) for i in data)\npy> data\n'&\\x9d'\n" }, { "answer_id": 326614, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import array\nintList= [int(s[x:x+8], 2) for x in range(0, len(s), 8)]\nbyteArray= array.array('B', intList)\n" }, { "answer_id": 68200364, "author": "shrewmouse", "author_id": 2464381, "author_profile": "https://Stackoverflow.com/users/2464381", "pm_score": 0, "selected": false, "text": ">>> import math,sys\n>>> s='0010011010011101'\n>>> int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder)\nb'\\x9d&'\n>>> with open('/tmp/blah', 'wb') as f:\n... f.write(int(s,2).to_bytes(math.ceil(len(s)/8),sys.byteorder))\n... \n2\n>>> quit()\n [root@localhost prbs]# od -x /tmp/blah\n0000000 269d\n0000002\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,596
<p>I'm writing a global error handling "module" for one of my applications.</p> <p>One of the features I want to have is to be able to easily wrap a function with a <code>try{} catch{}</code> block, so that all calls to that function will automatically have the error handling code that'll call my global logging method. (To avoid polluting the code everywhere with try/catch blocks).</p> <p>This is, however, slightly beyond my understanding of the low-level functioning of JavaScript, the <code>.call</code> and <code>.apply</code> methods, and the <code>this</code> keyword.</p> <p>I wrote this code, based on Prototype's <code>Function.wrap</code> method:</p> <pre><code>Object.extend(Function.prototype, { TryCatchWrap: function() { var __method = this; return function() { try { __method.apply(this, arguments) } catch(ex) { ErrorHandler.Exception(ex); } } } }); </code></pre> <p>Which is used like this:</p> <pre><code>function DoSomething(a, b, c, d) { document.write(a + b + c) alert(1/e); } var fn2 = DoSomething.TryCatchWrap(); fn2(1, 2, 3, 4); </code></pre> <p>That code works perfectly. It prints out 6, and then calls my global error handler.</p> <p>My question is: will this break something when the function I'm wrapping is within an object, and it uses the "this" operator? I'm slightly worried since I'm calling .apply, passing something there, I'm afraid this may break something.</p>
[ { "answer_id": 326693, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 7, "selected": true, "text": "var makeSafe = function(fn){\n return function(){\n try{\n return fn.apply(this, arguments);\n }catch(ex){\n ErrorHandler.Exception(ex);\n }\n };\n};\n function fnOriginal(a){\n console.log(1/a);\n};\n\nvar fn2 = makeSafe(fnOriginal);\nfn2(1);\nfn2(0);\nfn2(\"abracadabra!\");\n\nvar obj = {\n method1: function(x){ /* do something */ },\n method2: function(x){ /* do something */ }\n};\n\nobj.safeMethod1 = makeSafe(obj.method1);\nobj.method1(42); // the original method\nobj.safeMethod1(42); // the \"safe\" method\n\n// let's override a method completely\nobj.method2 = makeSafe(obj.method2);\n Function.prototype.TryCatchWrap = function(){\n var fn = this; // because we call it on the function itself\n // let's copy the rest from makeSafe()\n return function(){\n try{\n return fn.apply(this, arguments);\n }catch(ex){\n ErrorHandler.Exception(ex);\n }\n };\n};\n" }, { "answer_id": 13110117, "author": "DigitalDemenz", "author_id": 1780991, "author_profile": "https://Stackoverflow.com/users/1780991", "pm_score": 2, "selected": false, "text": " Boolean.prototype.XOR =\n// ^- Note that it's a captial 'B' and so\n// you'll work on the Class and not the >b<oolean object\n function( bool2 ) { \n\n var bool1 = this.valueOf();\n // 'this' refers to the actual object - and not to 'XOR'\n\n return (bool1 == true && bool2 == false)\n || (bool1 == false && bool2 == true);\n } \n\nalert ( \"true.XOR( false ) => \" true.XOR( false ) );\n" }, { "answer_id": 37275818, "author": "mikemaccana", "author_id": 123671, "author_profile": "https://Stackoverflow.com/users/123671", "pm_score": 4, "selected": false, "text": "function doThing(){\n console.log(...arguments)\n}\n \nfunction wrap(someFunction){\n function wrappedFunction(){\n var newArguments = [...arguments]\n newArguments.push('SECRET EXTRA ARG ADDED BY WRAPPER!')\n console.log(`You're about to run a function with these arguments: \\n ${newArguments}`)\n return someFunction(...newArguments)\n }\n return wrappedFunction\n}\n doThing('one', 'two', 'three')\n const wrappedDoThing = wrap(doThing)\nwrappedDoThing('one', 'two', 'three')\n one two three SECRET EXTRA ARG ADDED BY WRAPPER!\n wrap process.exit() var wrap = require('lodash.wrap');\n\nvar log = console.log.bind(console)\n\nvar RESTART_FLUSH_DELAY = 3 * 1000\n\nprocess.exit = wrap(process.exit, function(originalFunction) {\n log('Waiting', RESTART_FLUSH_DELAY, 'for buffers to flush before restarting')\n setTimeout(originalFunction, RESTART_FLUSH_DELAY)\n});\n\nprocess.exit(1);\n" }, { "answer_id": 55988649, "author": "Roman", "author_id": 4791116, "author_profile": "https://Stackoverflow.com/users/4791116", "pm_score": 1, "selected": false, "text": "//Our function\nfunction myFunction() {\n //For example we do this:\n document.getElementById('demo').innerHTML = Date();\n return;\n}\n\n//Our wrapper - middleware\nfunction wrapper(fn) {\n try {\n return function(){\n console.info('We add something else', Date());\n return fn();\n }\n }\n catch (error) {\n console.info('The error: ', error);\n }\n}\n\n//We use wrapper - middleware\nmyFunction = wrapper(myFunction);\n //Our function\nlet myFunction = () => {\n //For example we do this:\n document.getElementById('demo').innerHTML = Date();\n return;\n}\n\n//Our wrapper - middleware\nconst wrapper = func => {\n try {\n return () => {\n console.info('We add something else', Date());\n return func();\n }\n }\n catch (error) {\n console.info('The error: ', error);\n }\n}\n\n//We use wrapper - middleware\nmyFunction = wrapper(myFunction);\n" }, { "answer_id": 65218118, "author": "Arik", "author_id": 1655245, "author_profile": "https://Stackoverflow.com/users/1655245", "pm_score": 0, "selected": false, "text": "\nfunction wrap(originalFunction, { inject, wrapper } = {}) {\n\n const wrapperFn = function(...args) {\n if (typeof inject === 'function') {\n inject(originalFunction, this);\n }\n if (typeof wrapper === 'function') {\n return wrapper(originalFunction, this, args);\n }\n return originalFunction.apply(this, args);\n };\n\n // copy the original function's props onto the wrapper\n for(const prop in originalFunction) {\n if (originalFunction.hasOwnProperty(prop)) {\n wrapperFn[prop] = originalFunction[prop];\n }\n }\n return wrapperFn;\n}\n \n// create window.a()\n(function() {\n\n const txt = 'correctly'; // outer scope variable\n \n window.a = function a(someText) { // our target\n if (someText === \"isn't\") {\n throw('omg');\n }\n return ['a', someText, window.a.c, txt].join(' ');\n };\n \n window.a.c = 'called'; // a.c property example\n})();\n\nconst originalFunc = window.a;\nconsole.log(originalFunc('is')); // logs \"a is called correctly\"\n\nwindow.a = wrap(originalFunc);\nconsole.log(a('is')); // logs \"a is called correctly\"\n\nwindow.a = wrap(originalFunc, { inject(func, thisArg) { console.log('injected function'); }});\nconsole.log(a('is')); // logs \"injected function\\na is called correctly\"\n\nwindow.a = wrap(originalFunc, { wrapper(func, thisArg, args) { console.log(`doing something else instead of ${func.name}(${args.join(', ')})`); }});\nconsole.log(a('is')); // logs \"doing something else instead of a(is)\"\n\nwindow.a = wrap(originalFunc, {\n wrapper(func, thisArg, args) {\n try {\n return func.apply(thisArg, args);\n } catch(err) {\n console.error('got an exception');\n }\n }\n});\na(\"isn't\"); // error message: \"got an exception\"\n" }, { "answer_id": 67413137, "author": "JAN", "author_id": 779111, "author_profile": "https://Stackoverflow.com/users/779111", "pm_score": 1, "selected": false, "text": "const fnOriginal = (a, b, c, d) => {\n console.log(a);\n console.log(b);\n console.log(c);\n console.log(d);\n return 'Return value from fnOriginal';\n};\n\n\nconst wrapperFunction = fn => {\n return function () {\n try {\n const returnValuFromOriginal = fn.apply(this, arguments);\n console.log('Adding a new line from Wrapper :', returnValuFromOriginal);\n } catch (ex) {\n ErrorHandler.Exception(ex);\n }\n };\n};\n\nconst fnWrapped = wrapperFunction(fnOriginal);\nfnWrapped(1, 2, 3, 4);\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ]
326,628
<p>What is prefered way of setting html title (in head) for view when using master pages?</p> <p>One way is by using Page.Title in .aspx file, but that requires in master page which can mess with HTML code. So, lets assume no server side controls, only pure html. Any better ideas? </p> <p>UPDATE: I would like to set title in view NOT in the controller or model.</p>
[ { "answer_id": 326848, "author": "dtc", "author_id": 32892, "author_profile": "https://Stackoverflow.com/users/32892", "pm_score": 2, "selected": false, "text": "<head>" }, { "answer_id": 326918, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 4, "selected": false, "text": "<%= ViewData[\"Title\"] %> ContentPlaceHolder" }, { "answer_id": 329082, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": -1, "selected": false, "text": "<script type=\"text/javascript>\n document.title = \"Hello World\";\n</script>\n" }, { "answer_id": 334155, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": -1, "selected": true, "text": "<head runat=server visible=false>\n" }, { "answer_id": 335882, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "Title=\"\" <%@ %>" }, { "answer_id": 630075, "author": "reddi.eth", "author_id": 12722, "author_profile": "https://Stackoverflow.com/users/12722", "pm_score": 1, "selected": false, "text": "Page.Title=\"...\" Page_Load() <title> <title>" }, { "answer_id": 653151, "author": "Andrew Csontos", "author_id": 73550, "author_profile": "https://Stackoverflow.com/users/73550", "pm_score": 5, "selected": false, "text": "<asp:ContentPlaceHolder id=\"init\" runat=\"server\"></asp:ContentPlaceHolder>\n<head runat=\"server\"> \n <asp:ContentPlaceHolder ID=\"title\" runat=\"server\">\n <title><%=this.Page.Title%></title>\n </asp:ContentPlaceHolder>\n</head>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"title\" runat=\"server\">\n <title>Home Page</title>\n</asp:Content>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"init\" runat=\"server\">\n <%this.Title = \"Home Page\";%>\n</asp:Content>\n" }, { "answer_id": 25305776, "author": "Venugopal M", "author_id": 2132005, "author_profile": "https://Stackoverflow.com/users/2132005", "pm_score": 1, "selected": false, "text": "<title>\n <%:MyTitle + \" :: \" %>\n <asp:ContentPlaceHolder ID=\"TitleContent\" runat=\"server\">\n </asp:ContentPlaceHolder>\n</title>\n <asp:Content ID=\"Content1\" ContentPlaceHolderID=\"TitleContent\" runat=\"server\">\n<%:\"My Home Page\"%>\n" }, { "answer_id": 30220640, "author": "Stace", "author_id": 4896728, "author_profile": "https://Stackoverflow.com/users/4896728", "pm_score": 0, "selected": false, "text": "public static class Application\n{\n static string title;\n\n public static string Title\n {\n get { return title; }\n set { title = value; }\n }\n}\n Application.Title = \"Silly Application\";\n <div id=\"divApplicationTitle\">\n <asp:HyperLink runat=\"server\" NavigateUrl=\"~/Default.aspx\"><asp:Image ID=\"imgApplicationImage\" runat=\"server\" SkinID=\"skinApplicationLogo\" /><%=Application.Title%></asp:HyperLink> \n</div> \n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28912/" ]
326,634
<p>I had a discussion with a colleague at work, it was about SQL queries and sorting. He has the opinion that you should let the server do any sorting before returning the rows to the client. I on the other hand thinks that the server is probably busy enough as it is, and it must be better for performance to let the client handle the sorting after it has fetched the rows. </p> <p>Anyone which strategy is best for the overall performance of a multi-user system?</p>
[ { "answer_id": 635179, "author": "Walden Leverich", "author_id": 2673770, "author_profile": "https://Stackoverflow.com/users/2673770", "pm_score": 2, "selected": false, "text": "SELECT TOP 1 price \nFROM itemprice \nWHERE ItemNumber = ? \n AND effectivedate <= getdate() \nORDER BY effectivedate DESC\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4422/" ]
326,650
<p>The line-height property usually takes care of vertical alignment, but not with inputs. Is there a way to automatically center text without playing around with padding?</p>
[ { "answer_id": 327509, "author": "Chris Hawes", "author_id": 22776, "author_profile": "https://Stackoverflow.com/users/22776", "pm_score": 6, "selected": false, "text": "height : 36px; //for other browsers\nline-height: 36px; // for IE\n" }, { "answer_id": 327620, "author": "Gerhard Dinhof", "author_id": 898, "author_profile": "https://Stackoverflow.com/users/898", "pm_score": 5, "selected": true, "text": "<div style=\"line-height: 60px; height: 60px; border: 1px solid black;\">\n <input type=\"text\" value=\"foo\" />&nbsp;\n</div>\n" }, { "answer_id": 945812, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "<input type=\"text\" style=\"padding: 11px 0px 11px 0px; font-size: 20px;\" />\n" }, { "answer_id": 2285002, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": ".form-text {\n color: white;\n outline: none;\n background-image: url(input_text.png);\n border-width: 0px;\n padding: 0px 10px 0px 10px;\n margin: 0px;\n width: 274px;\n height: 24px;\n line-height: 24px;\n vertical-align: middle;\n}\n" }, { "answer_id": 5347939, "author": "Sparky", "author_id": 594235, "author_profile": "https://Stackoverflow.com/users/594235", "pm_score": 2, "selected": false, "text": "<input type=\"text\" style=\"padding-top:8px; padding-bottom:8px; margin: 0; border: solid 1px #000000; font-size:22px;\" />\n" }, { "answer_id": 6487895, "author": "MPS", "author_id": 816664, "author_profile": "https://Stackoverflow.com/users/816664", "pm_score": -1, "selected": false, "text": "display: table-cel\n Vertical-Align: Middle;\n" }, { "answer_id": 7114859, "author": "JimP", "author_id": 178688, "author_profile": "https://Stackoverflow.com/users/178688", "pm_score": 3, "selected": false, "text": " #search #searchbox {\n height: 21px;\n line-height: 21px;\n}\n" }, { "answer_id": 9595363, "author": "Morningseven", "author_id": 1247860, "author_profile": "https://Stackoverflow.com/users/1247860", "pm_score": 0, "selected": false, "text": "<ul>\n <li>First group of text here.</li>\n <li><input type=\"\" value=\"\" /></li>\n</ul>\n ul li {\n display: block;\n float: left;\n}\n" }, { "answer_id": 12841518, "author": "Gew", "author_id": 1622142, "author_profile": "https://Stackoverflow.com/users/1622142", "pm_score": 0, "selected": false, "text": "height: 21px;\nline-height: 21px; /* FOR IE */\n" }, { "answer_id": 16811367, "author": "Peter Waegemans", "author_id": 2249716, "author_profile": "https://Stackoverflow.com/users/2249716", "pm_score": 2, "selected": false, "text": "line-height vertical-align line-height" }, { "answer_id": 17400403, "author": "Web Designer cum Promoter", "author_id": 1012591, "author_profile": "https://Stackoverflow.com/users/1012591", "pm_score": 1, "selected": false, "text": "input[type=text]\n{\n height: 15px; \n line-height: 15px;\n}\n" }, { "answer_id": 24236719, "author": "GusRuss89", "author_id": 1466282, "author_profile": "https://Stackoverflow.com/users/1466282", "pm_score": 0, "selected": false, "text": "box-sizing: content-box;" }, { "answer_id": 54607426, "author": "Diego Favero", "author_id": 688689, "author_profile": "https://Stackoverflow.com/users/688689", "pm_score": 0, "selected": false, "text": ".InVertAlign {\n height: 40px;\n line-height: 40px;\n font-size: 2em;\n padding: 0px 14px 3px 5px;\n}\n <input type=\"text\" class=\"InVertAlign\" />\n" }, { "answer_id": 62524453, "author": "A Duv", "author_id": 9323308, "author_profile": "https://Stackoverflow.com/users/9323308", "pm_score": 0, "selected": false, "text": "padding-top: 0.5rem" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29595/" ]
326,672
<p>I'm trying to use System.IO.File.Replace to update a file, and it's throwing System.IOException if the destination file is on a NAS.</p> <p>According to <a href="http://msdn.microsoft.com/en-us/library/9d9h163f(VS.80).aspx" rel="nofollow noreferrer">MSDN</a>, if the destination file is on a different volume, this method throws an exception. It's right, but how do I detect if two files are on "different volumes"?</p> <p>Path.GetPathRoot returns different strings if I specify the same file using drive letters, mapped drives, or UNC paths. I can't catch System.IOException because that is thrown in a variety of cases, not just if the files are on different volumes.</p>
[ { "answer_id": 326785, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 2, "selected": true, "text": "catch IOException\n File.Copy( src,dest+\".tmp\", true )\n File.Replace( dest+\".tmp\", dest, dest_backup )\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22437/" ]
326,675
<p>I know that most people recommend using HttpRuntime.Cache because it has more flexibility... etc. But what if you want the object to persist in the cache for the life of the application? Is there any big downside to using the Application[] object to cache things?</p>
[ { "answer_id": 326766, "author": "Tom Jelen", "author_id": 28399, "author_profile": "https://Stackoverflow.com/users/28399", "pm_score": 5, "selected": true, "text": "HttpApplicationState HttpApplicationState DataSet HttpApplicationState" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
326,679
<p>I'm writing a bit of code to display a bar (or line) graph in our software. Everything's going fine. The thing that's got me stumped is labeling the Y axis.</p> <p>The caller can tell me how finely they want the Y scale labeled, but I seem to be stuck on exactly what to label them in an "attractive" kind of way. I can't describe "attractive", and probably neither can you, but we know it when we see it, right?</p> <p>So if the data points are:</p> <pre><code> 15, 234, 140, 65, 90 </code></pre> <p>And the user asks for 10 labels on the Y axis, a little bit of finagling with paper and pencil comes up with:</p> <pre><code> 0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250 </code></pre> <p>So there's 10 there (not including 0), the last one extends just beyond the highest value (234 &lt; 250), and it's a "nice" increment of 25 each. If they asked for 8 labels, an increment of 30 would have looked nice:</p> <pre><code> 0, 30, 60, 90, 120, 150, 180, 210, 240 </code></pre> <p>Nine would have been tricky. Maybe just have used either 8 or 10 and call it close enough would be okay. And what to do when some of the points are negative?</p> <p>I can see Excel tackles this problem nicely. </p> <p>Does anyone know a general-purpose algorithm (even some brute force is okay) for solving this? I don't have to do it quickly, but it should look nice.</p>
[ { "answer_id": 326734, "author": "Pyrolistical", "author_id": 21838, "author_profile": "https://Stackoverflow.com/users/21838", "pm_score": 3, "selected": false, "text": "1. 2^n, for some integer n. eg. ..., .25, .5, 1, 2, 4, 8, 16, ...\n2. 10^n, for some integer n. eg. ..., .01, .1, 1, 10, 100\n3. n/5 == 0, for some positive integer n, eg, 5, 10, 15, 20, 25, ...\n4. n/2 == 0, for some positive integer n, eg, 2, 4, 6, 8, 10, 12, 14, ...\n min_point and max_point.\n - start_label, where start_label < min_point and start_label is an integer\n- end_label, where end_label > max_point and end_label is an integer\n- label_offset, where label_offset is \"nice\"\n (end_label - start_label)/label_offset == label_count\n start_label to 0\n end_label\n" }, { "answer_id": 326746, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 8, "selected": true, "text": "15, 234, 140, 65, 90 with 10 ticks\n 15, 234, 140, 65, 90 with 8 ticks\n double range = ...;\nint tickCount = ...;\ndouble unroundedTickSize = range/(tickCount-1);\ndouble x = Math.ceil(Math.log10(unroundedTickSize)-1);\ndouble pow10x = Math.pow(10, x);\ndouble roundedTickRange = Math.ceil(unroundedTickSize / pow10x) * pow10x;\nreturn roundedTickRange;\n" }, { "answer_id": 1525198, "author": "Drew Noakes", "author_id": 24874, "author_profile": "https://Stackoverflow.com/users/24874", "pm_score": 3, "selected": false, "text": "public static class AxisUtil\n{\n public static float CalculateStepSize(float range, float targetSteps)\n {\n // calculate an initial guess at step size\n float tempStep = range/targetSteps;\n\n // get the magnitude of the step size\n float mag = (float)Math.Floor(Math.Log10(tempStep));\n float magPow = (float)Math.Pow(10, mag);\n\n // calculate most significant digit of the new step size\n float magMsd = (int)(tempStep/magPow + 0.5);\n\n // promote the MSD to either 1, 2, or 5\n if (magMsd > 5.0)\n magMsd = 10.0f;\n else if (magMsd > 2.0)\n magMsd = 5.0f;\n else if (magMsd > 1.0)\n magMsd = 2.0f;\n\n return magMsd*magPow;\n }\n}\n" }, { "answer_id": 9007526, "author": "Scott Guthrie", "author_id": 1169777, "author_profile": "https://Stackoverflow.com/users/1169777", "pm_score": 5, "selected": false, "text": "#!/usr/bin/php -q\n<?php\n\nfunction makeYaxis($yMin, $yMax, $ticks = 10)\n{\n // This routine creates the Y axis values for a graph.\n //\n // Calculate Min amd Max graphical labels and graph\n // increments. The number of ticks defaults to\n // 10 which is the SUGGESTED value. Any tick value\n // entered is used as a suggested value which is\n // adjusted to be a 'pretty' value.\n //\n // Output will be an array of the Y axis values that\n // encompass the Y values.\n $result = array();\n // If yMin and yMax are identical, then\n // adjust the yMin and yMax values to actually\n // make a graph. Also avoids division by zero errors.\n if($yMin == $yMax)\n {\n $yMin = $yMin - 10; // some small value\n $yMax = $yMax + 10; // some small value\n }\n // Determine Range\n $range = $yMax - $yMin;\n // Adjust ticks if needed\n if($ticks < 2)\n $ticks = 2;\n else if($ticks > 2)\n $ticks -= 2;\n // Get raw step value\n $tempStep = $range/$ticks;\n // Calculate pretty step value\n $mag = floor(log10($tempStep));\n $magPow = pow(10,$mag);\n $magMsd = (int)($tempStep/$magPow + 0.5);\n $stepSize = $magMsd*$magPow;\n\n // build Y label array.\n // Lower and upper bounds calculations\n $lb = $stepSize * floor($yMin/$stepSize);\n $ub = $stepSize * ceil(($yMax/$stepSize));\n // Build array\n $val = $lb;\n while(1)\n {\n $result[] = $val;\n $val += $stepSize;\n if($val > $ub)\n break;\n }\n return $result;\n}\n\n// Create some sample data for demonstration purposes\n$yMin = 60;\n$yMax = 330;\n$scale = makeYaxis($yMin, $yMax);\nprint_r($scale);\n\n$scale = makeYaxis($yMin, $yMax,5);\nprint_r($scale);\n\n$yMin = 60847326;\n$yMax = 73425330;\n$scale = makeYaxis($yMin, $yMax);\nprint_r($scale);\n?>\n # ./test1.php\nArray\n(\n [0] => 60\n [1] => 90\n [2] => 120\n [3] => 150\n [4] => 180\n [5] => 210\n [6] => 240\n [7] => 270\n [8] => 300\n [9] => 330\n)\n\nArray\n(\n [0] => 0\n [1] => 90\n [2] => 180\n [3] => 270\n [4] => 360\n)\n\nArray\n(\n [0] => 60000000\n [1] => 62000000\n [2] => 64000000\n [3] => 66000000\n [4] => 68000000\n [5] => 70000000\n [6] => 72000000\n [7] => 74000000\n)\n" }, { "answer_id": 11283950, "author": "mario", "author_id": 1494528, "author_profile": "https://Stackoverflow.com/users/1494528", "pm_score": 1, "selected": false, "text": "//get proper scale for y\n$maximoyi_temp= max($institucion); //get max value from data array\n for ($i=10; $i< $maximoyi_temp; $i=($i*10)) { \n if (($divisor = ($maximoyi_temp / $i)) < 2) break; //get which divisor will give a number between 1-2 \n } \n $factor_d = $maximoyi_temp / $i;\n $factor_d = ceil($factor_d); //round up number to 2\n $maximoyi = $factor_d * $i; //get new max value for y\n if ( ($maximoyi/ $maximoyi_temp) > 2) $maximoyi = $maximoyi /2; //check if max value is too big, then split by 2\n" }, { "answer_id": 13989277, "author": "Neil", "author_id": 148593, "author_profile": "https://Stackoverflow.com/users/148593", "pm_score": 0, "selected": false, "text": "public struct Interval\n{\n public readonly double Min, Max, TickRange;\n\n public static Interval Find(double min, double max, int tickCount, double padding = 0.05)\n {\n double range = max - min;\n max += range*padding;\n min -= range*padding;\n\n var attempts = new List<Interval>();\n for (int i = tickCount; i > tickCount / 2; --i)\n attempts.Add(new Interval(min, max, i));\n\n return attempts.MinBy(a => a.Max - a.Min);\n }\n\n private Interval(double min, double max, int tickCount)\n {\n var candidates = (min <= 0 && max >= 0 && tickCount <= 8) ? new[] {2, 2.5, 3, 4, 5, 7.5, 10} : new[] {2, 2.5, 5, 10};\n\n double unroundedTickSize = (max - min) / (tickCount - 1);\n double x = Math.Ceiling(Math.Log10(unroundedTickSize) - 1);\n double pow10X = Math.Pow(10, x);\n TickRange = RoundUp(unroundedTickSize/pow10X, candidates) * pow10X;\n Min = TickRange * Math.Floor(min / TickRange);\n Max = TickRange * Math.Ceiling(max / TickRange);\n }\n\n // 1 < scaled <= 10\n private static double RoundUp(double scaled, IEnumerable<double> candidates)\n {\n return candidates.First(candidate => scaled <= candidate);\n }\n}\n" }, { "answer_id": 39791189, "author": "panos", "author_id": 3213035, "author_profile": "https://Stackoverflow.com/users/3213035", "pm_score": 1, "selected": false, "text": "function calculateStartingPoint($min, $ticks, $times, $scale) {\n\n $starting_point = $min - floor((($ticks - $times) * $scale)/2);\n\n if ($starting_point < 0) {\n $starting_point = 0;\n } else {\n $starting_point = floor($starting_point / $scale) * $scale;\n $starting_point = ceil($starting_point / $scale) * $scale;\n $starting_point = round($starting_point / $scale) * $scale;\n }\n return $starting_point;\n}\n\nfunction calculateYaxis($min, $max, $ticks = 7)\n{\n print \"Min = \" . $min . \"\\n\";\n print \"Max = \" . $max . \"\\n\";\n\n $range = $max - $min;\n $step = floor($range/$ticks);\n print \"First step is \" . $step . \"\\n\";\n $available_steps = array(5, 10, 20, 25, 30, 40, 50, 100, 150, 200, 300, 400, 500);\n $distance = 1000;\n $scale = 0;\n\n foreach ($available_steps as $i) {\n if (($i - $step < $distance) && ($i - $step > 0)) {\n $distance = $i - $step;\n $scale = $i;\n }\n }\n\n print \"Final scale step is \" . $scale . \"\\n\";\n\n $times = floor($range/$scale);\n print \"range/scale = \" . $times . \"\\n\";\n\n print \"floor(times/2) = \" . floor($times/2) . \"\\n\";\n\n $starting_point = calculateStartingPoint($min, $ticks, $times, $scale);\n\n if ($starting_point + ($ticks * $scale) < $max) {\n $ticks += 1;\n }\n\n print \"starting_point = \" . $starting_point . \"\\n\";\n\n // result calculation\n $result = [];\n for ($x = 0; $x <= $ticks; $x++) {\n $result[] = $starting_point + ($x * $scale);\n }\n return $result;\n}\n" }, { "answer_id": 43167984, "author": "Arthur", "author_id": 5784628, "author_profile": "https://Stackoverflow.com/users/5784628", "pm_score": 2, "selected": false, "text": " var range = Math.abs(xMax - xMin); //both can be negative\n var rangeOrder = Math.floor(Math.log10(range)) - 1; \n var power10 = Math.pow(10, rangeOrder);\n var maxRound = (xMax > 0) ? Math.ceil(xMax / power10) : Math.floor(xMax / power10);\n var minRound = (xMin < 0) ? Math.floor(xMin / power10) : Math.ceil(xMin / power10);\n var fullRange = Math.abs(maxRound - minRound);\n var tickSize = Math.ceil(fullRange / (this.XTickCount - 1));\n\n //You can set nice looking ticks if you want\n //You can find exemplary method below \n tickSize = this.NiceLookingTick(tickSize);\n\n //Here you can write a method to determine if you need zero tick\n //You can find exemplary method below\n var isZeroNeeded = this.HasZeroTick(maxRound, minRound, tickSize);\n if (isZeroNeeded) {\n\n var positiveTicksCount = 0;\n var negativeTickCount = 0;\n\n if (maxRound != 0) {\n\n positiveTicksCount = Math.ceil(maxRound / tickSize);\n XUpperBound = tickSize * positiveTicksCount * power10;\n }\n\n if (minRound != 0) {\n negativeTickCount = Math.floor(minRound / tickSize);\n XLowerBound = tickSize * negativeTickCount * power10;\n }\n\n XTickRange = tickSize * power10;\n this.XTickCount = positiveTicksCount - negativeTickCount + 1;\n }\n else {\n var delta = (tickSize * (this.XTickCount - 1) - fullRange) / 2.0;\n\n if (delta % 1 == 0) {\n XUpperBound = maxRound + delta;\n XLowerBound = minRound - delta;\n }\n else {\n XUpperBound = maxRound + Math.ceil(delta);\n XLowerBound = minRound - Math.floor(delta);\n }\n\n XTickRange = tickSize * power10;\n XUpperBound = XUpperBound * power10;\n XLowerBound = XLowerBound * power10;\n }\n this.NiceLookingTick = function (tickSize) {\n\n var NiceArray = [1, 2, 2.5, 3, 4, 5, 10];\n\n var tickOrder = Math.floor(Math.log10(tickSize));\n var power10 = Math.pow(10, tickOrder);\n tickSize = tickSize / power10;\n\n var niceTick;\n var minDistance = 10;\n var index = 0;\n\n for (var i = 0; i < NiceArray.length; i++) {\n var dist = Math.abs(NiceArray[i] - tickSize);\n if (dist < minDistance) {\n minDistance = dist;\n index = i;\n }\n }\n\n return NiceArray[index] * power10;\n}\n\nthis.HasZeroTick = function (maxRound, minRound, tickSize) {\n\n if (maxRound * minRound < 0)\n {\n return true;\n }\n else if (Math.abs(maxRound) < tickSize || Math.round(minRound) < tickSize) {\n\n return true;\n }\n else {\n\n return false;\n }\n}\n" }, { "answer_id": 55151115, "author": "Petr Syrov", "author_id": 2670547, "author_profile": "https://Stackoverflow.com/users/2670547", "pm_score": 2, "selected": false, "text": "extension Int {\n\n static func makeYaxis(yMin: Int, yMax: Int, ticks: Int = 10) -> [Int] {\n var yMin = yMin\n var yMax = yMax\n var ticks = ticks\n // This routine creates the Y axis values for a graph.\n //\n // Calculate Min amd Max graphical labels and graph\n // increments. The number of ticks defaults to\n // 10 which is the SUGGESTED value. Any tick value\n // entered is used as a suggested value which is\n // adjusted to be a 'pretty' value.\n //\n // Output will be an array of the Y axis values that\n // encompass the Y values.\n var result = [Int]()\n // If yMin and yMax are identical, then\n // adjust the yMin and yMax values to actually\n // make a graph. Also avoids division by zero errors.\n if yMin == yMax {\n yMin -= ticks // some small value\n yMax += ticks // some small value\n }\n // Determine Range\n let range = yMax - yMin\n // Adjust ticks if needed\n if ticks < 2 { ticks = 2 }\n else if ticks > 2 { ticks -= 2 }\n\n // Get raw step value\n let tempStep: CGFloat = CGFloat(range) / CGFloat(ticks)\n // Calculate pretty step value\n let mag = floor(log10(tempStep))\n let magPow = pow(10,mag)\n let magMsd = Int(tempStep / magPow + 0.5)\n let stepSize = magMsd * Int(magPow)\n\n // build Y label array.\n // Lower and upper bounds calculations\n let lb = stepSize * Int(yMin/stepSize)\n let ub = stepSize * Int(ceil(CGFloat(yMax)/CGFloat(stepSize)))\n // Build array\n var val = lb\n while true {\n result.append(val)\n val += stepSize\n if val > ub { break }\n }\n return result\n }\n\n}\n" }, { "answer_id": 56442190, "author": "Hjalmar Snoep", "author_id": 8174954, "author_profile": "https://Stackoverflow.com/users/8174954", "pm_score": 1, "selected": false, "text": "var min=52;\nvar max=173;\nvar actualHeight=500; // 500 pixels high graph\n\nvar tickCount =Math.round(actualHeight/100); \n// we want lines about every 100 pixels.\n\nif(tickCount <3) tickCount =3; \nvar range=Math.abs(max-min);\nvar unroundedTickSize = range/(tickCount-1);\nvar x = Math.ceil(Math.log10(unroundedTickSize)-1);\nvar pow10x = Math.pow(10, x);\nvar roundedTickRange = Math.ceil(unroundedTickSize / pow10x) * pow10x;\nvar min_rounded=roundedTickRange * Math.floor(min/roundedTickRange);\nvar max_rounded= roundedTickRange * Math.ceil(max/roundedTickRange);\nvar nr=tickCount;\nvar str=\"\";\nfor(var x=min_rounded;x<=max_rounded;x+=roundedTickRange)\n{\n str+=x+\", \";\n}\nconsole.log(\"nice Y axis \"+str); \n" }, { "answer_id": 58593674, "author": "chickens", "author_id": 1602301, "author_profile": "https://Stackoverflow.com/users/1602301", "pm_score": 1, "selected": false, "text": "const niceScale = ( minPoint, maxPoint, maxTicks) => {\n const niceNum = ( localRange, round) => {\n var exponent,fraction,niceFraction;\n exponent = Math.floor(Math.log10(localRange));\n fraction = localRange / Math.pow(10, exponent);\n if (round) {\n if (fraction < 1.5) niceFraction = 1;\n else if (fraction < 3) niceFraction = 2;\n else if (fraction < 7) niceFraction = 5;\n else niceFraction = 10;\n } else {\n if (fraction <= 1) niceFraction = 1;\n else if (fraction <= 2) niceFraction = 2;\n else if (fraction <= 5) niceFraction = 5;\n else niceFraction = 10;\n }\n return niceFraction * Math.pow(10, exponent);\n }\n const result = [];\n const range = niceNum(maxPoint - minPoint, false);\n const stepSize = niceNum(range / (maxTicks - 1), true);\n const lBound = Math.floor(minPoint / stepSize) * stepSize;\n const uBound = Math.ceil(maxPoint / stepSize) * stepSize;\n for(let i=lBound;i<=uBound;i+=stepSize) result.push(i);\n return result;\n};\nconsole.log(niceScale(15,234,6));\n// > [0, 100, 200, 300]" }, { "answer_id": 68708675, "author": "gogo", "author_id": 4521081, "author_profile": "https://Stackoverflow.com/users/4521081", "pm_score": 0, "selected": false, "text": "function tickEvery(range, ticks) {\n return Math.ceil((range / ticks) / Math.pow(10, Math.ceil(Math.log10(range / ticks) - 1))) * Math.pow(10, Math.ceil(Math.log10(range / ticks) - 1));\n}\n\nfunction update() {\n const range = document.querySelector(\"#range\").value;\n const ticks = document.querySelector(\"#ticks\").value;\n const result = tickEvery(range, ticks);\n document.querySelector(\"#result\").textContent = `With range ${range} and ${ticks} ticks, tick every ${result} for a total of ${Math.ceil(range / result)} ticks at ${new Array(Math.ceil(range / result)).fill(0).map((v, n) => Math.round(n * result)).join(\", \")}`;\n}\n\nupdate(); <input id=\"range\" min=\"1\" max=\"10000\" oninput=\"update()\" style=\"width:100%\" type=\"range\" value=\"5000\" width=\"40\" />\n<br/>\n<input id=\"ticks\" min=\"1\" max=\"20\" oninput=\"update()\" type=\"range\" style=\"width:100%\" value=\"10\" />\n<p id=\"result\" style=\"font-family:sans-serif\"></p>" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8173/" ]
326,686
<p>Just came across this quote in a book on OOP that I'm reading,</p> <blockquote> <p>A child is only allowed to augment functionality and add functionality. A child is never allowed to remove functionality. If you do find that a child need to remove functionality, this is an indication that the child should appear before the parent in the inheritance hierarchy!</p> </blockquote> <p>But my question is, isn't this what overriding does?</p>
[ { "answer_id": 326704, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": 0, "selected": false, "text": "namespace CompanyA {\n class Phone {\n public void Dial() {\n // do work to dial the phone here\n }\n }\n}\n namespace CompanyB {\n class BetterPhone: CompanyA.Phone {\n public void Dial() {\n Console.WriteLine(\"BetterPhoneDial\");\n EstablishConenction();\n base.Dial();\n }\n }\n}\n" }, { "answer_id": 326716, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "class Parent {\n public void method_one(){ \n print \"Hello\";\n }\n}\n\nclass Child extends Parent {\n public void method_one(){\n // do nothing\n }\n }\n class Parent {\n public void method_one(){ \n print \"Hello\";\n }\n}\n\nclass Child extends Parent {\n // Attempt remove the method visibility, thus remove funcionality \n private void method_one(){ \n // do nothing\n }\n }\n" }, { "answer_id": 2506428, "author": "RockWorld", "author_id": 185550, "author_profile": "https://Stackoverflow.com/users/185550", "pm_score": 0, "selected": false, "text": "\npublic interface IContract\n{\n void DoWork();\n}\n\npublic class BaseContract: IContract\n{\n public virtual void DoWork()\n {\n //perform operation A\n }\n}\n \npublic class EnhancedContract: BaseContract\n{\n public override void DoWork()\n {\n //perform operation B\n base.DoWork();\n //perform operation C\n }\n}\n \npublic class EnhancedWork:IContract\n{\n public void DoWork()\n {\n //perform operation D\n }\n}\n \nEnhancedContract e = new EnhancedContract();\nBaseContract b = e;\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38317/" ]
326,689
<p>So I started with a web services project (just a dynamic web project) that builds and debugs correctly from eclipse. We've pulled a chunk of common code out that we want to put into a shared library so now those classes are going into a separate jar project that the web project references.</p> <p>On the web project, I did Project->Properties->Java Build Path->Projects->Add and added the jar project. And this correctly solved all the compile-time classpath problems and everything builds fine. But at runtime, when the tomcat server fires up, spring attempts to inject some of the classes contained in the jar file and I get a NoClassDefFoundError.</p> <p>My .class and properties files and the contents of my META-INF directory are showing up in the ./build directory, but my WEB-INF/lib directory seems to be referenced in-place, and the jar dependency doesn't get copied in to it to show up as part of the Web App Library.</p> <p>What is the magical incantation to tell eclipse that the other jar project needs to be available to tomcat at runtime? From our ant build script, we first just build the other project into WEB-INF/lib and everything works fine, but not for eclipse debugging.</p>
[ { "answer_id": 7908055, "author": "Anoop Isaac", "author_id": 1015324, "author_profile": "https://Stackoverflow.com/users/1015324", "pm_score": 3, "selected": false, "text": "properties > deployment assembly > add > project" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409/" ]
326,754
<p>It seems that I can't control the NSApp delegate from within a System Preferences pane, which is understandable. Is there any other way I can have my object notified when the program becomes active?</p>
[ { "answer_id": 326777, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 2, "selected": false, "text": "mainViewDidLoad: // These messages get sent to the a preference panel just before and\n// just after it becomes the currently selected preference panel.\n- (void) willSelect;\n- (void) didSelect;\n\n// The willUnselect message gets sent to the currently selected preference panel\n// just before and just after it gets swapped out for another preference panel\n- (void) willUnselect;\n- (void) didUnselect;\n" }, { "answer_id": 326878, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 3, "selected": true, "text": "application{Will,Did}{Become,Resign}Active: NSApplication{Will,Did}{Become,Resign}ActiveNotification NSNotificationCenter" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4103/" ]
326,757
<p>I'm trying to update a hashtable in a loop but getting an error: System.InvalidOperationException: Collection was modified; enumeration operation may not execute.</p> <pre><code>private Hashtable htSettings_m = new Hashtable(); htSettings_m.Add("SizeWidth", "728"); htSettings_m.Add("SizeHeight", "450"); string sKey = ""; string sValue = ""; foreach (DictionaryEntry deEntry in htSettings_m) { // Get value from Registry and assign to sValue. // ... // Change value in hashtable. sKey = deEntry.Key.ToString(); htSettings_m[sKey] = sValue; } </code></pre> <p>Is there way around it or maybe there is a better data structure for such purpose?</p>
[ { "answer_id": 326767, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 1, "selected": false, "text": "deEntry.Value = sValue\n" }, { "answer_id": 326768, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 3, "selected": false, "text": "Hashtable table = new Hashtable(); // ps, I would prefer the generic dictionary..\nHashtable updates = new Hashtable();\n\nforeach (DictionaryEntry entry in table)\n{\n // logic if something needs to change or nog\n if (needsUpdate)\n {\n updates.Add(key, newValue);\n }\n}\n\n// now do the actual update\nforeach (DictionaryEntry upd in updates)\n{\n table[upd.Key] = upd.Value;\n}\n" }, { "answer_id": 326774, "author": "keithwarren7", "author_id": 40714, "author_profile": "https://Stackoverflow.com/users/40714", "pm_score": 5, "selected": true, "text": " System.Collections.Hashtable ht = new System.Collections.Hashtable();\n\n ht.Add(\"test1\", \"test2\");\n ht.Add(\"test3\", \"test4\");\n\n List<string> keys = new List<string>();\n foreach (System.Collections.DictionaryEntry de in ht)\n keys.Add(de.Key.ToString());\n\n foreach(string key in keys)\n {\n ht[key] = DateTime.Now;\n Console.WriteLine(ht[key]);\n }\n" }, { "answer_id": 326776, "author": "Stephen Martin", "author_id": 12845, "author_profile": "https://Stackoverflow.com/users/12845", "pm_score": -1, "selected": false, "text": "private Hashtable htSettings_m = new Hashtable();\n\nhtSettings_m.Add(\"SizeWidth\", \"728\"); \nhtSettings_m.Add(\"SizeHeight\", \"450\"); \nstring sValue = \"\"; \nforeach (string sKey in htSettings_m.Keys) \n{ \n // Get value from Registry and assign to sValue \n // ... \n // Change value in hashtable. \n htSettings_m[sKey] = sValue; \n}\n" }, { "answer_id": 326780, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 0, "selected": false, "text": "foreach (String sKey in htSettings_m.Keys)\n{ // Get value from Registry and assign to sValue.\n // ... \n // Change value in hashtable.\n htSettings_m[sKey] = sValue;\n}\n" }, { "answer_id": 327163, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "foreach (string key in new List<string>(dictionary.Keys))\n Int32.MaxValue" }, { "answer_id": 2476770, "author": "Gian Marco", "author_id": 66629, "author_profile": "https://Stackoverflow.com/users/66629", "pm_score": 2, "selected": false, "text": "var dictionary = new Dictionary<string, string>();\nforeach(var key in dictionary.Keys.ToArray())\n{\n dictionary[key] = \"new value\";\n}\n" }, { "answer_id": 3470778, "author": "Okan", "author_id": 418756, "author_profile": "https://Stackoverflow.com/users/418756", "pm_score": 0, "selected": false, "text": "Dictionary<string,bool> dict = new Dictionary<string,bool>();\n\nfor (int i = 0; i < dict.Count; i++)\n{\n string key = dict.ElementAt(i).Key;\n dict[key] = false;\n}\n" }, { "answer_id": 15709486, "author": "NateN", "author_id": 2225433, "author_profile": "https://Stackoverflow.com/users/2225433", "pm_score": 0, "selected": false, "text": "List<string> keyList = htSettings_m.Keys.Cast<string>().ToList();\nforeach (string key in keyList) {\n" }, { "answer_id": 28996197, "author": "Slogmeister Extraordinaire", "author_id": 1772150, "author_profile": "https://Stackoverflow.com/users/1772150", "pm_score": 0, "selected": false, "text": "private Hashtable htSettings_m = new Hashtable();\nhtSettings_m.Add(\"SizeWidth\", \"728\");\nhtSettings_m.Add(\"SizeHeight\", \"450\");\nstring sKey = \"\";\nstring sValue = \"\";\n\nArrayList htSettings_ary = new ArrayList(htSettings_m.Keys)\nforeach (DictionaryEntry deEntry in htSettings_ary)\n{\n // Get value from Registry and assign to sValue.\n // ...\n // Change value in hashtable.\n sKey = deEntry.Key.ToString();\n htSettings_m[sKey] = sValue;\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
326,764
<p>Is there a shortcut for giving a limit and order when accessing a has_many relation in an ActiveRecord model?</p> <p>For example, here's what I'd like to express:</p> <pre><code>@user.posts(:limit =&gt; 5, :order =&gt; "title") </code></pre> <p>As opposed to the longer version:</p> <pre><code>Post.find(:all, :limit =&gt; 5, :order =&gt; "title", :conditions =&gt; ['user_id = ?', @user.id]) </code></pre> <p>I know you can specify it directly in the has_many relationship, but is there a way to do it on the fly, such as showing 10 posts on one page, but only 3 on another?</p>
[ { "answer_id": 326795, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 3, "selected": false, "text": " has_many :posts, :class_name => \"BlogPost\", :foreign_key => \"owner_id\",\n :order => \"items.published_at desc\", :include => [:creator] do\n def recent(limit=3)\n find(:all, :limit => limit, :order => \"items.published_at desc\")\n end\n end\n Blog.posts.recent\n Blog.posts.recent(5)\n" }, { "answer_id": 326875, "author": "Milan Novota", "author_id": 26123, "author_profile": "https://Stackoverflow.com/users/26123", "pm_score": 1, "selected": false, "text": "@user.posts.ordered('title ASC').limited(5)\n" }, { "answer_id": 327861, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 2, "selected": false, "text": "class Post < ActiveRecord::Base\n named_scope :limited, lambda {|*num| {:limit => num.empty? ? DEFAULT_LIMIT : num.first}}\nend\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19964/" ]
326,770
<p>I have a python module that defines a number of classes:</p> <pre><code>class A(object): def __call__(self): print "ran a" class B(object): def __call__(self): print "ran b" class C(object): def __call__(self): print "ran c" </code></pre> <p>From within the module, how might I add an attribute that gives me all of the classes?</p> <p>dir() gives me the names of everything from within my module, but I can't seem to figure out how to go from the name of a class to the class itself from <em>within</em> the module.</p> <p>From outside of the module, I can simply use <code>getattr(mod, 'A')</code>, but I don't have a <code>self</code> kind of module from within the module itself.</p> <p>This seems pretty obvious. Can someone tell me what I'm missing?</p>
[ { "answer_id": 326789, "author": "Igal Serban", "author_id": 25737, "author_profile": "https://Stackoverflow.com/users/25737", "pm_score": 4, "selected": true, "text": "import sys\ngetattr(sys.modules[__name__], 'A')\n" }, { "answer_id": 326796, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 3, "selected": false, "text": "import sys\nimport types\nthis_module = sys.modules[__name__]\n[x for x in\n [getattr(this_module, x) for x in dir(this_module)]\n if type(x) == types.ClassType]\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39975/" ]
326,775
<p>Suppose there were several projects mostly maintained by smart interns, who eventually leave after a period of time. Scripts are used here and there in key parts, for example, to back up a database, rename it, zip it, move it over ssh, unzip it, and then to restore it with different settings. You know, the scripting stuff.</p> <p>The programming languages for the application side is set, but those for scripts have been relaxed. Currently there are probably healthy mix of bash and .bat file, and maybe some Perl.</p> <p>1) To avoid language proliferation, and 2) because I don't want to force bash upon future Windows programmers, I'd like to set an "official" scripting language.</p> <p>Google picked Python for this, and it's famous for being readable, easy to learn, and having good library; however, I personally don't find it that readable compared to C-like grammar, Pascal, or Ruby.</p> <p>In any case, if you were to be forced to use only one scripting language on a Windows machine (with Cygwin if you want to) for all scripting, what would you like it to be, and why?</p> <p>Related religious wars:</p> <ul> <li><a href="https://stackoverflow.com/questions/213048/what-is-the-best-scripting-language-to-learn">What Is The Best Scripting Language To Learn?</a></li> <li><a href="https://stackoverflow.com/questions/70453/which-scripting-language-is-best">Which Scripting language is best?</a></li> </ul>
[ { "answer_id": 21688853, "author": "mbirth", "author_id": 3293109, "author_profile": "https://Stackoverflow.com/users/3293109", "pm_score": 1, "selected": false, "text": "Progress, b2 m, ACME App, Doing some magic...\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827/" ]
326,778
<p>OK,</p> <p>Here is my problem, I have a master page with a HEAD section that contains my JS includes. I have one JS include </p> <pre><code>&lt;script src="Includes/js/browser.js" language="javascript" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>In my page i consume it like this:</p> <pre><code>&lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; .... &lt;script type="text/javascript"&gt;registerBookmarkButton();&lt;/script&gt; .... &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p>And i get this error:</p> <pre><code>Line: 216 Error: Object expected </code></pre> <p>Please tell me i just missed something and it's a stupid mistake</p>
[ { "answer_id": 326866, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 1, "selected": false, "text": "alert()" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36269/" ]
326,794
<p>Is there a way in Python to handle XML files similar to the way PHP's SimpleXML extension does them?</p> <p>Ideally I just want to be able to access certain xml datas from a list object.</p>
[ { "answer_id": 9926389, "author": "LXj", "author_id": 292080, "author_profile": "https://Stackoverflow.com/users/292080", "pm_score": 0, "selected": false, "text": "In [1]: from lxml import objectify\n\nIn [2]: x = objectify.fromstring(\"\"\"<response><version>1.2</version><amount>1.01</amount><currency>USD</currency></response>\"\"\")\n\nIn [3]: x.version\nOut[3]: 1.2\n\nIn [4]: x.amount\nOut[4]: 1.01\n\nIn [5]: x.currency\nOut[5]: 'USD'\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32933/" ]
326,797
<p>I was wondering if there is a smart way to find out</p> <p>There is a 1/4 chance something happens.</p> <p>I know we can do this with rand() % 4 and checking if it is equal to 0, but is there a way without using rand()? In c++, thanks.</p>
[ { "answer_id": 326801, "author": "Vilx-", "author_id": 41360, "author_profile": "https://Stackoverflow.com/users/41360", "pm_score": 0, "selected": false, "text": "rand()" }, { "answer_id": 326814, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 4, "selected": false, "text": "rand() std::tr1" }, { "answer_id": 326850, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 2, "selected": false, "text": "rand() < RAND_MAX/n;\n" }, { "answer_id": 326894, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "static int r = 0;\n: : :\nif ((r = (r+1)%4) == 0) {\n // do something.\n}\n" }, { "answer_id": 326946, "author": "Juan Pablo Califano", "author_id": 24170, "author_profile": "https://Stackoverflow.com/users/24170", "pm_score": 2, "selected": false, "text": "rand() 0 RAND_MAX-1 double odds = .25;\n\nif(rand() <= RAND_MAX * odds) {\n // there should be .25 chance of entering this condition\n}\n" }, { "answer_id": 327402, "author": "Edouard A.", "author_id": 41363, "author_profile": "https://Stackoverflow.com/users/41363", "pm_score": 1, "selected": false, "text": "bool rand_afourth(void)\n{\n return !!((rand() & 1) & (rand() & 1));\n}\n boost::uniform_int<> aFourth(1,4)\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,802
<p>For those who like a good WPF binding challenge:</p> <p>I have a nearly functional example of two-way binding a <code>CheckBox</code> to an individual bit of a flags enumeration (thanks Ian Oakes, <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/c05b7e7e-25cd-4a41-8bf5-e35d2caff797/" rel="nofollow noreferrer">original MSDN post</a>). The problem though is that the binding behaves as if it is one way (UI to <code>DataContext</code>, not vice versa). So effectively the <code>CheckBox</code> does not initialize, but if it is toggled the data source is correctly updated. Attached is the class defining some attached dependency properties to enable the bit-based binding. What I've noticed is that ValueChanged is never called, even when I force the <code>DataContext</code> to change.</p> <p><strong>What I've tried:</strong> Changing the order of property definitions, Using a label and text box to confirm the <code>DataContext</code> is bubbling out updates, Any plausible <code>FrameworkMetadataPropertyOptions</code> (<code>AffectsRender</code>, <code>BindsTwoWayByDefault</code>), Explicitly setting <code>Binding Mode=TwoWay</code>, Beating head on wall, Changing <code>ValueProperty</code> to <code>EnumValueProperty</code> in case of conflict.</p> <p>Any suggestions or ideas would be extremely appreciated, thanks for anything you can offer!</p> <p>The enumeration:</p> <pre><code>[Flags] public enum Department : byte { None = 0x00, A = 0x01, B = 0x02, C = 0x04, D = 0x08 } // end enum Department </code></pre> <p>The XAML usage:</p> <pre><code>CheckBox Name="studentIsInDeptACheckBox" ctrl:CheckBoxFlagsBehaviour.Mask="{x:Static c:Department.A}" ctrl:CheckBoxFlagsBehaviour.IsChecked="{Binding Path=IsChecked, RelativeSource={RelativeSource Self}}" ctrl:CheckBoxFlagsBehaviour.Value="{Binding Department}" </code></pre> <p>The class:</p> <pre><code>/// &lt;summary&gt; /// A helper class for providing bit-wise binding. /// &lt;/summary&gt; public class CheckBoxFlagsBehaviour { private static bool isValueChanging; public static Enum GetMask(DependencyObject obj) { return (Enum)obj.GetValue(MaskProperty); } // end GetMask public static void SetMask(DependencyObject obj, Enum value) { obj.SetValue(MaskProperty, value); } // end SetMask public static readonly DependencyProperty MaskProperty = DependencyProperty.RegisterAttached("Mask", typeof(Enum), typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null)); public static Enum GetValue(DependencyObject obj) { return (Enum)obj.GetValue(ValueProperty); } // end GetValue public static void SetValue(DependencyObject obj, Enum value) { obj.SetValue(ValueProperty, value); } // end SetValue public static readonly DependencyProperty ValueProperty = DependencyProperty.RegisterAttached("Value", typeof(Enum), typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null, ValueChanged)); private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { isValueChanging = true; byte mask = Convert.ToByte(GetMask(d)); byte value = Convert.ToByte(e.NewValue); BindingExpression exp = BindingOperations.GetBindingExpression(d, IsCheckedProperty); object dataItem = GetUnderlyingDataItem(exp.DataItem); PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path); pi.SetValue(dataItem, (value &amp; mask) != 0, null); ((CheckBox)d).IsChecked = (value &amp; mask) != 0; isValueChanging = false; } // end ValueChanged public static bool? GetIsChecked(DependencyObject obj) { return (bool?)obj.GetValue(IsCheckedProperty); } // end GetIsChecked public static void SetIsChecked(DependencyObject obj, bool? value) { obj.SetValue(IsCheckedProperty, value); } // end SetIsChecked public static readonly DependencyProperty IsCheckedProperty = DependencyProperty.RegisterAttached("IsChecked", typeof(bool?), typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(false, IsCheckedChanged)); private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (isValueChanging) return; bool? isChecked = (bool?)e.NewValue; if (isChecked != null) { BindingExpression exp = BindingOperations.GetBindingExpression(d, ValueProperty); object dataItem = GetUnderlyingDataItem(exp.DataItem); PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path); byte mask = Convert.ToByte(GetMask(d)); byte value = Convert.ToByte(pi.GetValue(dataItem, null)); if (isChecked.Value) { if ((value &amp; mask) == 0) { value = (byte)(value + mask); } } else { if ((value &amp; mask) != 0) { value = (byte)(value - mask); } } pi.SetValue(dataItem, value, null); } } // end IsCheckedChanged /// &lt;summary&gt; /// Gets the underlying data item from an object. /// &lt;/summary&gt; /// &lt;param name="o"&gt;The object to examine.&lt;/param&gt; /// &lt;returns&gt;The underlying data item if appropriate, or the object passed in.&lt;/returns&gt; private static object GetUnderlyingDataItem(object o) { return o is DataRowView ? ((DataRowView)o).Row : o; } // end GetUnderlyingDataItem } // end class CheckBoxFlagsBehaviour </code></pre>
[ { "answer_id": 375288, "author": "PaulJ", "author_id": 11308, "author_profile": "https://Stackoverflow.com/users/11308", "pm_score": 7, "selected": true, "text": "Enum [Flags]\npublic enum Department\n{\n None = 0,\n A = 1,\n B = 2,\n C = 4,\n D = 8\n}\n\npublic partial class Window1 : Window\n{\n public Window1()\n {\n InitializeComponent();\n\n this.DepartmentsPanel.DataContext = new DataObject\n {\n Department = Department.A | Department.C\n };\n }\n}\n\npublic class DataObject\n{\n public DataObject()\n {\n }\n\n public Department Department { get; set; }\n}\n\npublic class DepartmentValueConverter : IValueConverter\n{\n private Department target;\n\n public DepartmentValueConverter()\n {\n }\n\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n Department mask = (Department)parameter;\n this.target = (Department)value;\n return ((mask & this.target) != 0);\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n this.target ^= (Department)parameter;\n return this.target;\n }\n}\n <Window.Resources>\n <l:DepartmentValueConverter x:Key=\"DeptConverter\" />\n</Window.Resources>\n\n <StackPanel x:Name=\"DepartmentsPanel\">\n <CheckBox Content=\"A\"\n IsChecked=\"{Binding \n Path=Department,\n Converter={StaticResource DeptConverter},\n ConverterParameter={x:Static l:Department.A}}\"/>\n <!-- more -->\n </StackPanel>\n" }, { "answer_id": 384756, "author": "Steve Cadwallader", "author_id": 41693, "author_profile": "https://Stackoverflow.com/users/41693", "pm_score": 2, "selected": false, "text": "public class CheckBoxFlagsBehaviour\n{\n private static bool isValueChanging;\n\n public static Enum GetMask(DependencyObject obj)\n {\n return (Enum)obj.GetValue(MaskProperty);\n } // end GetMask\n\n public static void SetMask(DependencyObject obj, Enum value)\n {\n obj.SetValue(MaskProperty, value);\n } // end SetMask\n\n public static readonly DependencyProperty MaskProperty =\n DependencyProperty.RegisterAttached(\"Mask\", typeof(Enum),\n typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(null));\n\n public static byte GetValue(DependencyObject obj)\n {\n return (byte)obj.GetValue(ValueProperty);\n } // end GetValue\n\n public static void SetValue(DependencyObject obj, byte value)\n {\n obj.SetValue(ValueProperty, value);\n } // end SetValue\n\n public static readonly DependencyProperty ValueProperty =\n DependencyProperty.RegisterAttached(\"Value\", typeof(byte),\n typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(default(byte), ValueChanged));\n\n private static void ValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n isValueChanging = true;\n byte mask = Convert.ToByte(GetMask(d));\n byte value = Convert.ToByte(e.NewValue);\n\n BindingExpression exp = BindingOperations.GetBindingExpression(d, IsCheckedProperty);\n object dataItem = GetUnderlyingDataItem(exp.DataItem);\n PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);\n pi.SetValue(dataItem, (value & mask) != 0, null);\n\n ((CheckBox)d).IsChecked = (value & mask) != 0;\n isValueChanging = false;\n } // end ValueChanged\n\n public static bool? GetIsChecked(DependencyObject obj)\n {\n return (bool?)obj.GetValue(IsCheckedProperty);\n } // end GetIsChecked\n\n public static void SetIsChecked(DependencyObject obj, bool? value)\n {\n obj.SetValue(IsCheckedProperty, value);\n } // end SetIsChecked\n\n public static readonly DependencyProperty IsCheckedProperty =\n DependencyProperty.RegisterAttached(\"IsChecked\", typeof(bool?),\n typeof(CheckBoxFlagsBehaviour), new UIPropertyMetadata(false, IsCheckedChanged));\n\n private static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n if (isValueChanging) return;\n\n bool? isChecked = (bool?)e.NewValue;\n if (isChecked != null)\n {\n BindingExpression exp = BindingOperations.GetBindingExpression(d, ValueProperty);\n object dataItem = GetUnderlyingDataItem(exp.DataItem);\n PropertyInfo pi = dataItem.GetType().GetProperty(exp.ParentBinding.Path.Path);\n\n byte mask = Convert.ToByte(GetMask(d));\n byte value = Convert.ToByte(pi.GetValue(dataItem, null));\n\n if (isChecked.Value)\n {\n if ((value & mask) == 0)\n {\n value = (byte)(value + mask);\n }\n }\n else\n {\n if ((value & mask) != 0)\n {\n value = (byte)(value - mask);\n }\n }\n\n pi.SetValue(dataItem, value, null);\n }\n } // end IsCheckedChanged\n\n private static object GetUnderlyingDataItem(object o)\n {\n return o is DataRowView ? ((DataRowView)o).Row : o;\n } // end GetUnderlyingDataItem\n} // end class CheckBoxFlagsBehaviour\n" }, { "answer_id": 49559152, "author": "Nick", "author_id": 862495, "author_profile": "https://Stackoverflow.com/users/862495", "pm_score": 2, "selected": false, "text": "<CheckBox Content=\"A\" IsChecked=\"{Binding Department[A]}\"/>\n<CheckBox Content=\"B\" IsChecked=\"{Binding Department[B]}\"/>\n<CheckBox Content=\"C\" IsChecked=\"{Binding Department[C]}\"/>\n<CheckBox Content=\"D\" IsChecked=\"{Binding Department[D]}\"/>\n public class ViewModel : ViewModelBase\n{\n private Department department;\n\n public ViewModel()\n {\n Department = new EnumFlags<Department>(department);\n }\n\n public Department Department { get; private set; }\n}\n public class EnumFlags<T> : INotifyPropertyChanged where T : struct, IComparable, IFormattable, IConvertible\n{\n private T value;\n\n public EnumFlags(T t)\n {\n if (!typeof(T).IsEnum) throw new ArgumentException($\"{nameof(T)} must be an enum type\"); // I really wish they would just let me add Enum to the generic type constraints\n value = t;\n }\n\n public T Value\n {\n get { return value; }\n set\n {\n if (this.value.Equals(value)) return;\n this.value = value;\n OnPropertyChanged(\"Item[]\");\n }\n }\n\n [IndexerName(\"Item\")]\n public bool this[T key]\n {\n get\n {\n // .net does not allow us to specify that T is an enum, so it thinks we can't cast T to int.\n // to get around this, cast it to object then cast that to int.\n return (((int)(object)value & (int)(object)key) == (int)(object)key);\n }\n set\n {\n if ((((int)(object)this.value & (int)(object)key) == (int)(object)key) == value) return;\n\n this.value = (T)(object)((int)(object)this.value ^ (int)(object)key);\n\n OnPropertyChanged(\"Item[]\");\n }\n }\n\n #region INotifyPropertyChanged\n public event PropertyChangedEventHandler PropertyChanged;\n\n private void OnPropertyChanged([CallerMemberName] string memberName = \"\")\n {\n PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(memberName));\n }\n #endregion\n}\n" }, { "answer_id": 53612263, "author": "Skelvir", "author_id": 8795573, "author_profile": "https://Stackoverflow.com/users/8795573", "pm_score": 0, "selected": false, "text": "public class FlagToBoolConverter : IMultiValueConverter\n\n{\n private YourFlagEnum selection;\n private YourFlagEnum mask;\n\n public static int InstanceCount = 0;\n\n public FlagToBoolConverter()\n {\n InstanceCount++;\n }\n\n public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n mask = (YourFlagEnum ) values[1];\n selection = (YourFlagEnum ) values[0];\n return (mask & selection) != 0;\n }\n\n public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)\n {\n if (value.Equals(true))\n {\n selection |= mask;\n }\n else\n {\n selection &= ~mask;\n }\n\n object[] o = new object[2];\n o[0] = selection;\n o[1] = mask;\n return o;\n }\n}\n <ItemsControl ItemsSource=\"{Binding CheckBoxTemplates}\">\n <ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Vertical\" Margin=\"40,0,0,0\"></StackPanel>\n </ItemsPanelTemplate>\n </ItemsControl.ItemsPanel>\n <ItemsControl.ItemTemplate>\n <DataTemplate>\n <CheckBox Content=\"{Binding Path=Content}\" >\n <CheckBox.Style>\n <Style TargetType=\"CheckBox\">\n <Setter Property=\"IsChecked\">\n <Setter.Value>\n <MultiBinding Converter=\"{StaticResource FlagToBoolConverter}\">\n <Binding Path=\"MyEnumProperty\" Mode=\"TwoWay\" UpdateSourceTrigger=\"PropertyChanged\"></Binding>\n <Binding Path=\"MyEnumPropertyMask\"></Binding>\n </MultiBinding>\n </Setter.Value>\n </Setter>\n </Style>\n </CheckBox.Style>\n </CheckBox>\n </DataTemplate>\n </ItemsControl.ItemTemplate>\n </ItemsControl>\n <UserControl.Resources>\n <ui:FlagToBoolConverter x:Key=\"FlagToBoolConverter\" x:Shared=\"False\"></ui:FlagToBoolConverter>\n</UserControl.Resources>\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41693/" ]
326,818
<p>I want to validate a set of credentials against the domain controller. e.g.:</p> <pre><code>Username: STACKOVERFLOW\joel Password: splotchy </code></pre> <h2>Method 1. Query Active Directory with Impersonation</h2> <p>A lot of people suggest querying the Active Directory for something. If an exception is thrown, then you know the credentials are not valid - as is suggested in <a href="https://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory">this stackoverflow question</a>.</p> <p>There are some serious <a href="http://bytes.com/groups/net-c/249893-fyi-easy-way-validate-ad-credentials-win2k-using-c" rel="noreferrer">drawbacks to this approach</a> however:</p> <ol> <li><p>You are not only authenticating a domain account, but you are also doing an implicit authorization check. That is, you are reading properties from the AD using an impersonation token. What if the otherwise valid account has no rights to read from the AD? By default all users have read access, but domain policies can be set to disable access permissions for restricted accounts (and or groups).</p></li> <li><p>Binding against the AD has a serious overhead, the AD schema cache has to be loaded at the client (ADSI cache in the ADSI provider used by DirectoryServices). This is both network, and AD server, resource consuming - and is too expensive for a simple operation like authenticating a user account.</p></li> <li><p>You're relying on an exception failure for a non-exceptional case, and assuming that means invalid username and password. Other problems (e.g. network failure, AD connectivity failure, memory allocation error, etc) are then mis-intrepreted as authentication failure.</p></li> </ol> <h2>Method 2. LogonUser Win32 API</h2> <p><a href="https://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory#290558">Others</a> have suggested using the <a href="http://msdn.microsoft.com/en-us/library/aa378184.aspx" rel="noreferrer"><code>LogonUser()</code></a> API function. This sounds nice, but unfortunately the calling user sometimes needs a permission usually only given to the operating system itself:</p> <blockquote> <p>The process calling LogonUser requires the SE_TCB_NAME privilege. If the calling process does not have this privilege, LogonUser fails and GetLastError returns ERROR_PRIVILEGE_NOT_HELD. </p> <p>In some cases, the process that calls LogonUser must also have the SE_CHANGE_NOTIFY_NAME privilege enabled; otherwise, LogonUser fails and GetLastError returns ERROR_ACCESS_DENIED. This privilege is not required for the local system account or accounts that are members of the administrators group. By default, SE_CHANGE_NOTIFY_NAME is enabled for all users, but some administrators may disable it for everyone.</p> </blockquote> <p>Handing out the "<em>Act as a part of the operating system</em>" privilege is not something you want to do willy-nilly - as Microsoft points out in a <a href="http://support.microsoft.com/kb/180548" rel="noreferrer">knowledge base article</a>:</p> <blockquote> <p>...the process that is calling LogonUser must have the SE_TCB_NAME privilege (in User Manager, this is the "<em>Act as part of the Operating System</em>" right). The SE_TCB_NAME privilege is very powerful and <strong>should not be granted to any arbitrary user just so that they can run an application</strong> that needs to validate credentials.</p> </blockquote> <p>Additionally, a call to <code>LogonUser()</code> will fail if a blank password is specified.</p> <hr> <p>What is the proper way to authenticate a set of domain credentials?</p> <hr> <p>I <em>happen</em> to be calling from managed code, but this is a a general Windows question. It can be assumed that the customers have the .NET Framework 2.0 installed.</p>
[ { "answer_id": 327073, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 8, "selected": true, "text": " bool valid = false;\n using (PrincipalContext context = new PrincipalContext(ContextType.Domain))\n {\n valid = context.ValidateCredentials( username, password );\n }\n" }, { "answer_id": 603818, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.DirectoryServices.AccountManagement;\n\nclass WindowsCred\n{\n private const string SPLIT_1 = \"\\\\\";\n\n public static bool ValidateW(string UserName, string Password)\n {\n bool valid = false;\n string Domain = \"\";\n\n if (UserName.IndexOf(\"\\\\\") != -1)\n {\n string[] arrT = UserName.Split(SPLIT_1[0]);\n Domain = arrT[0];\n UserName = arrT[1];\n }\n\n if (Domain.Length == 0)\n {\n Domain = System.Environment.MachineName;\n }\n\n using (PrincipalContext context = new PrincipalContext(ContextType.Domain, Domain)) \n {\n valid = context.ValidateCredentials(UserName, Password);\n }\n\n return valid;\n }\n}\n" }, { "answer_id": 6930296, "author": "kantanomo", "author_id": 877103, "author_profile": "https://Stackoverflow.com/users/877103", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Security;\nusing System.DirectoryServices.AccountManagement;\n\npublic struct Credentials\n{\n public string Username;\n public string Password;\n}\n\npublic class Domain_Authentication\n{\n public Credentials Credentials;\n public string Domain;\n\n public Domain_Authentication(string Username, string Password, string SDomain)\n {\n Credentials.Username = Username;\n Credentials.Password = Password;\n Domain = SDomain;\n }\n\n public bool IsValid()\n {\n using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))\n {\n // validate the credentials\n return pc.ValidateCredentials(Credentials.Username, Credentials.Password);\n }\n }\n}\n" }, { "answer_id": 26785753, "author": "Kevinrr3", "author_id": 4223946, "author_profile": "https://Stackoverflow.com/users/4223946", "pm_score": 3, "selected": false, "text": "using System;\nusing System.DirectoryServices;\nusing System.DirectoryServices.AccountManagement;\nusing System.Runtime.InteropServices;\n\nnamespace User\n{\n public static class UserValidation\n {\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool LogonUser(string principal, string authority, string password, LogonTypes logonType, LogonProviders logonProvider, out IntPtr token);\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool CloseHandle(IntPtr handle);\n enum LogonProviders : uint\n {\n Default = 0, // default for platform (use this!)\n WinNT35, // sends smoke signals to authority\n WinNT40, // uses NTLM\n WinNT50 // negotiates Kerb or NTLM\n }\n enum LogonTypes : uint\n {\n Interactive = 2,\n Network = 3,\n Batch = 4,\n Service = 5,\n Unlock = 7,\n NetworkCleartext = 8,\n NewCredentials = 9\n }\n public const int ERROR_PASSWORD_MUST_CHANGE = 1907;\n public const int ERROR_LOGON_FAILURE = 1326;\n public const int ERROR_ACCOUNT_RESTRICTION = 1327;\n public const int ERROR_ACCOUNT_DISABLED = 1331;\n public const int ERROR_INVALID_LOGON_HOURS = 1328;\n public const int ERROR_NO_LOGON_SERVERS = 1311;\n public const int ERROR_INVALID_WORKSTATION = 1329;\n public const int ERROR_ACCOUNT_LOCKED_OUT = 1909; //It gives this error if the account is locked, REGARDLESS OF WHETHER VALID CREDENTIALS WERE PROVIDED!!!\n public const int ERROR_ACCOUNT_EXPIRED = 1793;\n public const int ERROR_PASSWORD_EXPIRED = 1330;\n\n public static int CheckUserLogon(string username, string password, string domain_fqdn)\n {\n int errorCode = 0;\n using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain_fqdn, \"ADMIN_USER\", \"PASSWORD\"))\n {\n if (!pc.ValidateCredentials(username, password))\n {\n IntPtr token = new IntPtr();\n try\n {\n if (!LogonUser(username, domain_fqdn, password, LogonTypes.Network, LogonProviders.Default, out token))\n {\n errorCode = Marshal.GetLastWin32Error();\n }\n }\n catch (Exception)\n {\n throw;\n }\n finally\n {\n CloseHandle(token);\n }\n }\n }\n return errorCode;\n }\n }\n" }, { "answer_id": 28302759, "author": "Alan Nicholas", "author_id": 4524843, "author_profile": "https://Stackoverflow.com/users/4524843", "pm_score": 1, "selected": false, "text": " public bool IsLocalUser()\n {\n return windowsIdentity.AuthenticationType == \"NTLM\";\n }\n APIs(parameter) Used by Application Incorrect Value Correct Value \n===================================== =============== ========================\nAcquireCredentialsHandle (pszPackage) “NTLM” NEGOSSP_NAME “Negotiate”\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
326,820
<p>I know that you cannot return anonymous types from methods but I am wondering how the Select extension method returns an anonymous type. Is it just a compiler trick?</p> <p>Edit</p> <p>Suppose L is a List. How does this work?</p> <pre><code>L.Select(s =&gt; new { Name = s }) </code></pre> <p>The return type is IEnumerable&lt;'a> where 'a = new {String Name}</p>
[ { "answer_id": 326831, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "List<string> x = new List<string>();\n\n// The compiler converts this:\nx.Select(y => y.Length);\n\n// Into this, using type inference:\nEnumerable.Select<string, int>(x, y => y.Length);\n x" }, { "answer_id": 326844, "author": "Guvante", "author_id": 16800, "author_profile": "https://Stackoverflow.com/users/16800", "pm_score": 1, "selected": false, "text": "List<int> list = new List<int<();\n\nvar val = list.Select(x => new {value = x, mod = x % 10});\n" }, { "answer_id": 326888, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": false, "text": "public List<T> Foo<T>(T template) { // doesn't actually use \"template\"\n return new List<T>(); // just an example\n}\n var list = Foo(new {Bar=1});\n <T> public List<T> Foo<T>(Func<T> func) { // doesn't actually use \"func\"\n return new List<T>(); // just an example\n}\n\nvar list = Foo(() => new {Bar = 1});\n" }, { "answer_id": 326900, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "Select<Tsource, TResult>(IEnumerable<TSource>, Func<TSource, TResult> IEnumerable<TSource> Func<Tsource, TResult> Func<Tsource, TResult> Select TResult Select TResult ReturnAnonymousType<TResult>(Func<TResult> f) {\n return f();\n}\n\nConsole.WriteLine(ReturnAnonymousType(\n () => return new { Text = \"Hello World!\" } // type defined here, before calling \n);\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927/" ]
326,821
<p>Everyone in my office uses Macs and therefore most use Safari. </p> <p>We have a page that has 30 checkboxes on it, I didn't even do the HTML myself but no matter if I use the html input checkbox with a label or an asp:Checkbox usig the text property for the label my boss is irritated because the checkbox is a little below center on the label. </p> <p>I can only assume that this is due to Sarari and it's wonky rendering. I doubt there is a fix that wont be rediculously complicated (if there is please let me know). I didn't even do the html myself, I sent it out. </p> <p>I tried to explain to him that's how Safari "is" but that wasn't acceptable. I googled to see if anyone else had run into such an issue, (I didn't google to hard though, figured I'd just ask you guys). What do I do when hit with an issue like this where he insists something so minor is unacceptable? Am I approaching this wrong? I mean the HTML is perfectly reasonable here it is: </p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;asp:CheckBox CssClass="checkbox" runat="server" Text="Accessories" /&gt;&lt;/li&gt; &lt;li&gt;&lt;asp:CheckBox CssClass="checkbox" runat="server" Text="Art" /&gt;&lt;/li&gt; &lt;li&gt;&lt;asp:CheckBox CssClass="checkbox" runat="server" Text="Athletic Apparel" /&gt;&lt;/li&gt; &lt;!-- etc... --&gt; &lt;/ul&gt; </code></pre> <p>How can I explain this to him a way he will understand?</p>
[ { "answer_id": 326837, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 3, "selected": true, "text": "label {\n vertical-align: bottom;\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4140/" ]
326,822
<p>I want to serialize the following Xml structure:</p> <pre><code> &lt;XmlRootElement&gt; &lt;Company name="Acme Widgets LLC"&gt; &lt;DbApplication name="ApplicationA" vendor="oracle"&gt; &lt;ConnSpec environment="DEV" server="DBOraDev1201" database="AppA" userId="MyUser" password="5613456#6%^%$%$#" /&gt; &lt;ConnSpec environment="QA" server="DBOraQA1205" database="AppA" userId="MyUser" password="5613456#6%^%$%$#" /&gt; &lt;/DbApplication&gt; &lt;DbApplication name="AnotherApp" "vendor="SQLServer"&gt; &lt;ConnSpec environment="DEV" server="DBMsSqlDev1201" catalog="AnoptherApp" userId="MyUser" password="5613456#6%^%$%$#" /&gt; &lt;ConnSpec environment="QA" server="DBMsSqlQA1565" catalog="AnotherApp" userId="MyUser" password="5613456#6%^%$%$#" /&gt; &lt;/DbApplication&gt; &lt;/Company&gt; &lt;Company name = "ExpertSoftware Inc" .... ... &lt;/Company&gt; &lt;/XmlRootElement&gt; </code></pre> <p>but I have discovered in <a href="http://msdn.microsoft.com/en-us/library/ms950721.aspx" rel="nofollow noreferrer">link text</a></p> <p>Quote from above link: ...</p> <ul> <li>Q: Why aren't all properties of collection classes serialized?</li> <li>A: The XmlSerializer only serializes the elements in the collection when it detects either the IEnumerable or the ICollection interface. This behavior is by design. The only work around is to re-factor the custom collection into two classes, one of which exposes the properties including one of the pure collection types.</li> </ul> <p>...</p> <p>after discovering that you can't serialize or deserialize a collection that has other Xml attributes in it... The suggested workaround is to separate the element that has the collection from the the ones that have other attributes... i.e, You have to change the structure so that it looks like this instead:</p> <pre><code> &lt;XmlRootElement&gt; &lt;Companys&gt; &lt;Company name="Acme Widgets LLC"&gt; &lt;DbApplications&gt; &lt;DbApplication name="ApplicationA" vendor="oracle"&gt; &lt;ConnSpecs&gt; &lt;ConnSpec environment="DEV" server="DBOraDev1201" ... /&gt; &lt;ConnSpec environment="QA" server="DBOraQA1205" database="AppA" ... /&gt; &lt;/ConnSpecs&gt; &lt;/DbApplication&gt; &lt;DbApplication name="AnotherApp" "vendor="SQLServer"&gt; &lt;ConnSpecs&gt; &lt;ConnSpec environment="DEV" ... /&gt; &lt;ConnSpec environment="QA" ... /&gt; &lt;/ConnSpecs&gt; &lt;/DbApplication&gt; &lt;/DbApplications&gt; &lt;/Company&gt; &lt;Company name = "ExpertSoftware Inc" .... ... &lt;/Company&gt; &lt;/Companys&gt; &lt;/XmlRootElement&gt; </code></pre> <p>Does anyone know why this is so? or if there is some other way to do this?</p>
[ { "answer_id": 328778, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 3, "selected": true, "text": "public class XmlRootElement\n{\n [XmlElement(ElementName=\"Company\")]\n public Company[] Company { get; set; }\n\n // Other properties ....\n}\n\npublic class Company\n{\n [XmlAttribute(AttributeName=\"name\")]\n public string Name { get; set; }\n\n [XmlElement(ElementName = \"DbApplication\")]\n public DbApplication[] DbApplication { get; set; }\n\n // Other properties ....\n}\n\npublic class DbApplication\n{\n [XmlElement(ElementName = \"ConnSpec\")]\n public ConnSpec[] ConnSpec { get; set; }\n\n // Other properties ....\n}\n\npublic class ConnSpec\n{\n // Other properties ....\n}\n using (Stream stream = new FileStream(\"test.xml\", FileMode.Open, FileAccess.Read, FileShare.Read))\n{\n XmlSerializer serializer = new XmlSerializer(typeof(XmlRootElement));\n XmlRootElement root = (XmlRootElement)serializer.Deserialize(stream);\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32632/" ]
326,825
<p>How can I pass a variable number of args to a yield. I don't want to pass an array (as the following code does), I'd actually like to pass them as a programmatic number of args to the block.</p> <pre><code>def each_with_attributes(attributes, &amp;block) results[:matches].each_with_index do |match, index| yield self[index], attributes.collect { |attribute| (match[:attributes][attribute] || match[:attributes]["@#{attribute}"]) } end end </code></pre>
[ { "answer_id": 326836, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 2, "selected": false, "text": "def test(a, b)\n puts \"#{a} + #{b} = #{a + b}\"\nend\n\nargs = [1, 2]\n\ntest *args\n" }, { "answer_id": 326843, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 5, "selected": true, "text": "* block.call(*array)\n yield *array\n" }, { "answer_id": 326846, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "def print_num_args(*a)\n puts a.size\nend\n\narray = [1, 2, 3]\nprint_num_args(array);\nprint_num_args(*array);\n 1\n3\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6705/" ]
326,828
<p>In Flash when you set text in a TextField object with the htmlText property, changing the alpha value no longer works. Is there a way around that?</p>
[ { "answer_id": 329483, "author": "aaaidan", "author_id": 26331, "author_profile": "https://Stackoverflow.com/users/26331", "pm_score": 2, "selected": false, "text": "alpha htmlText <b> <i>" }, { "answer_id": 332158, "author": "Jesse Millikan", "author_id": 7526, "author_profile": "https://Stackoverflow.com/users/7526", "pm_score": 0, "selected": false, "text": "import flash.display.BlendMode;\nimport flash.text.TextField;\n// later...\nvar tf:TextField = new TextField();\ntf.blendMode = BlendMode.LAYER;\ntf.alpha = 0.5;\n" }, { "answer_id": 336032, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 3, "selected": true, "text": "alpha" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28672/" ]
326,857
<p>Problem:</p> <pre><code>edited files on windows, using git-bash, to fix IE7 problems committed, pushed to github repo booted back into linux pulled from repo merge conflict in dozens of files used 'git reset --hard' </code></pre> <p>What can I do to get back on track?</p> <p>UPDATE: please look at the following for a clearer picture (no irony intended)</p> <p>(I think the problem is one that I often encounter, that the sphinx files are platform-dependant, and I don't know how to skip them in the pull.)</p> <pre><code>jess@home:~$ cd Rails/nutrograph/ jess@home:~/Rails/nutrograph$ git rm nutrograph/ fatal: pathspec 'nutrograph/' did not match any files jess@home:~/Rails/nutrograph$ git pull remote: Counting objects: 29, done. remote: Compressing objects: 100% (13/13), done. remote: Total 15 (delta 11), reused 0 (delta 0) Unpacking objects: 100% (15/15), done. From git@github.com:shalunov/nutrograph 1925d73..1ed7f46 master -&gt; origin/master Updating 1925d73..1ed7f46 TODO: needs update app/models/data_link.rb: needs update app/models/footnote.rb: needs update app/models/static_chart.rb: needs update app/views/food_description/index.haml: needs update app/views/food_description/titles.haml: needs update app/views/site/about.html.erb: needs update app/views/static_page/_random_foods.haml: needs update app/views/static_page/index.haml: needs update app/views/static_page/show.haml: needs update app/views/static_page/sweet-potato-cooked-boiled-without-skin: needs update config/development.sphinx.conf: needs update config/environment.rb: needs update db/migrate/10_create_food_comparisons.rb: needs update db/sphinx/development/food_description_core.spa: needs update db/sphinx/development/food_description_core.sph: needs update db/sphinx/development/food_description_core.spl: needs update public/static_pages/beans-snap-green-cooked-boiled-drained-with-salt: needs update public/static_pages/butter-salted: needs update public/static_pages/cheese-muenster: needs update public/static_pages/sweet-potato-cooked-boiled-without-skin: needs update test/fixtures/data_links.yml: needs update test/fixtures/footnotes.yml: needs update test/fixtures/static_charts.yml: needs update test/unit/static_chart_test.rb: needs update vendor/plugins/haml/init.rb: needs update error: Entry 'app/views/static_page/index.haml' not uptodate. Cannot merge. jess@home:~/Rails/nutrograph$ l app/ CSV_files/ doc/ log/ public/ README.rdoc spec/ test/ TODO vendor/ config/ db/ lib/ Nutrograph.pdf Rakefile script/ stories/ tmp/ utf8_general_ci jess@home:~/Rails/nutrograph$ mkdir backup jess@home:~/Rails/nutrograph$ cd backup/ jess@home:~/Rails/nutrograph/backup$ git clone git@github.com:shalunov/nutrograph.git Initialized empty Git repository in /home/jess/Rails/nutrograph/backup/nutrograph/.git/ remote: Counting objects: 2346, done. remote: Compressing objects: 100% (2025/2025), done. remote: Total 2346 (delta 958), reused 996 (delta 146) Receiving objects: 100% (2346/2346), 19.74 MiB | 373 KiB/s, done. Resolving deltas: 100% (958/958), done. Checking out files: 100% (867/867), done. jess@home:~/Rails/nutrograph/backup$ script/server bash: script/server: No such file or directory jess@home:~/Rails/nutrograph/backup$ cd nutrograph/ jess@home:~/Rails/nutrograph/backup/nutrograph$ script/server =&gt; Booting Mongrel (use 'script/server webrick' to force WEBrick) =&gt; Rails 2.1.2 application starting on http://0.0.0.0:3000 =&gt; Call with -d to detach =&gt; Ctrl-C to shutdown server /usr/lib/ruby/gems/1.8/gems/rails-2.1.2/lib/commands/servers/mongrel.rb:57:in `initialize': No such file or directory - /home/jess/Rails/nutrograph/backup/nutrograph/log/development.log (Errno::ENOENT) from /usr/lib/ruby/gems/1.8/gems/rails-2.1.2/lib/commands/servers/mongrel.rb:57:in `open' from /usr/lib/ruby/gems/1.8/gems/rails-2.1.2/lib/commands/servers/mongrel.rb:57 from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require' from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:355:in `new_constants_in' from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.2/lib/active_support/dependencies.rb:510:in `require' from /usr/lib/ruby/gems/1.8/gems/rails-2.1.2/lib/commands/server.rb:39 from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require' from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:31:in `require' from script/server:3 jess@home:~/Rails/nutrograph/backup/nutrograph$ git merge usage: git-merge [options] &lt;remote&gt;... or: git-merge [options] &lt;msg&gt; HEAD &lt;remote&gt; --stat show a diffstat at the end of the merge -n don't show a diffstat at the end of the merge --summary (synonym to --stat) --log add list of one-line log to merge commit message --squash create a single commit instead of doing a merge --commit perform a commit if the merge succeeds (default) --ff allow fast forward (default) -s, --strategy ... merge strategy to use -m, --message ... message to be used for the merge commit (if any) jess@home:~/Rails/nutrograph/backup/nutrograph$ git merge origin/master Already up-to-date. jess@home:~/Rails/nutrograph/backup/nutrograph$ git pull Already up-to-date. jess@home:~/Rails/nutrograph/backup/nutrograph$ cd ../.. jess@home:~/.local/share/Trash/files$ cd jess@home:~$ cd Rails/nutrograph/ jess@home:~/Rails/nutrograph$ git merge usage: git-merge [options] &lt;remote&gt;... or: git-merge [options] &lt;msg&gt; HEAD &lt;remote&gt; --stat show a diffstat at the end of the merge -n don't show a diffstat at the end of the merge --summary (synonym to --stat) --log add list of one-line log to merge commit message --squash create a single commit instead of doing a merge --commit perform a commit if the merge succeeds (default) --ff allow fast forward (default) -s, --strategy ... merge strategy to use -m, --message ... message to be used for the merge commit (if any) jess@home:~/Rails/nutrograph$ git merge orgin orgin - not something we can merge jess@home:~/Rails/nutrograph$ git merge orgin/master orgin/master - not something we can merge jess@home:~/Rails/nutrograph$ git rebase orgin/master TODO: needs update app/views/static_page/index.haml: needs update config/development.sphinx.conf: needs update config/environment.rb: needs update db/sphinx/development/food_description_core.spa: needs update db/sphinx/development/food_description_core.sph: needs update vendor/plugins/haml/init.rb: needs update jess@home:~/Rails/nutrograph$ git reset --hard HEAD is now at 1925d73 got rid of "Nutrition Facts" in view jess@home:~/Rails/nutrograph$ git pull Updating 1925d73..1ed7f46 Fast forward app/views/layouts/application.haml | 25 +++++++++++-------------- app/views/static_page/index.haml | 6 +++--- nutrograph | 1 + public/javascripts/tabs.js | 4 +++- public/stylesheets/sass/site.sass | 16 +++++++++------- public/stylesheets/site.css | 14 ++++++++------ 6 files changed, 35 insertions(+), 31 deletions(-) create mode 160000 nutrograph jess@home:~/Rails/nutrograph$ script/server =&gt; Booting Mongrel (use 'script/server webrick' to force WEBrick) =&gt; Rails 2.1.2 application starting on http://0.0.0.0:3000 =&gt; Call with -d to detach =&gt; Ctrl-C to shutdown server ** Starting Mongrel listening at 0.0.0.0:3000 ** Starting Rails with development environment... ** Rails loaded. ** Loading any Rails specific GemPlugins ** Signals ready. TERM =&gt; stop. USR2 =&gt; restart. INT =&gt; stop (no restart). ** Rails signals registered. HUP =&gt; reload (without restart). It might not work well. ** Mongrel 1.1.5 available at 0.0.0.0:3000 ** Use CTRL-C to stop. Processing SiteController#index (for 127.0.0.1 at 2008-11-28 16:45:38) [GET] Session ID: aa0ab6213969dc2ce78472f9c5f57258 Parameters: {"action"=&gt;"index", "controller"=&gt;"site"} SQL (0.000153) SET NAMES 'utf8' SQL (0.000077) SET SQL_AUTO_IS_NULL=0 StaticPage Columns (0.000841) SHOW FIELDS FROM `static_pages` . . . . Rendering template within layouts/application Rendering static_page/index Completed in 0.69965 (1 reqs/sec) | Rendering: 0.34820 (49%) | DB: 0.26384 (37%) | 200 OK [http://localhost/4000-beef-round-top-round-separable-lean-only-trimmed-to-quarter-inch-fat-select-cooked-braised] ^C** INT signal received. Exiting jess@home:~/Rails/nutrograph$ git pull Already up-to-date. jess@home:~/Rails/nutrograph$ git rebase origin/master vendor/plugins/haml/init.rb: needs update jess@home:~/Rails/nutrograph$ git pull Already up-to-date. jess@home:~/Rails/nutrograph$ git pull origin/master fatal: 'origin/master': unable to chdir or not a git archive fatal: The remote end hung up unexpectedly jess@home:~/Rails/nutrograph$ git rebase origin/master vendor/plugins/haml/init.rb: needs update jess@home:~/Rails/nutrograph$ rm vendor/plugins/haml/init.rb jess@home:~/Rails/nutrograph$ rm vendor/plugins/haml/init.rb rm: cannot remove `vendor/plugins/haml/init.rb': No such file or directory jess@home:~/Rails/nutrograph$ haml --rails . Directory ./vendor/plugins/haml already exists, overwrite [y/N]? y Haml plugin added to . jess@home:~/Rails/nutrograph$ git rebase origin/master vendor/plugins/haml/init.rb: needs update jess@home:~/Rails/nutrograph$ git fetch origin jess@home:~/Rails/nutrograph$ git merge origin/master Already up-to-date. jess@home:~/Rails/nutrograph$ git rebase origin/master vendor/plugins/haml/init.rb: needs update jess@home:~/Rails/nutrograph$ git pull Already up-to-date. jess@home:~/Rails/nutrograph$ </code></pre> <hr> <p>It's actually not a line feed problem, as I set the e text editor to use unix style line endings. tho, at this point, i don't know what the problem is, just that I need a slolution.</p> <p>Are you ignoring that I ran `git reset --hard' ??</p>
[ { "answer_id": 326863, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": true, "text": "git config core.autocrlf true\n git add" }, { "answer_id": 327835, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 1, "selected": false, "text": "git pull $ git config branch.master.remote origin\n$ git config branch.master.merge refs/heads/master\n pull" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33287/" ]
326,862
<p>For example, if I wanted to do it from the command line I would use "a.exe > out.txt". Is it possible to do something similar in Visual Studio when I debug (F5)?</p>
[ { "answer_id": 326935, "author": "call me Steve", "author_id": 24334, "author_profile": "https://Stackoverflow.com/users/24334", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <fstream>\n\nusing namespace std;\n\nint main ()\n{\n#ifdef _DEBUG\n ofstream mout(\"stdout.txt\");\n cout.rdbuf(mout.rdbuf());\n#endif\n cout<< \"hello\" ;\n return 0;\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
326,885
<p>I want to create the 26 neighbors of a cubic-voxel-node in 3-d space. The inputs are the x,y,z position of the node and the size of the cube side . I am trying to do this using a for loop but haven't managed yet. I am quite newbie in programming please help me.</p>
[ { "answer_id": 326889, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 3, "selected": false, "text": "for (int dz = z - 1; dz <= z + 1; ++dz)\n{\n for (int dy = y - 1; dy <= y + 1; ++dy)\n {\n for (int dx = x - 1; dx <= x + 1; ++dx)\n {\n // all 27\n if ((dx != x) || (dy != y) || (dz != z))\n {\n // just the 26 neighbors\n }\n }\n }\n}\n" }, { "answer_id": 328036, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "// g++ 26neighbours.cpp -o 26neighbours && 26neighbours \n#include <algorithm>\n#include <iostream>\n#include <iterator>\n#include <vector>\n\nnamespace {\n struct Pos {\n double x, y, z;\n\n template<class Char, class Traits>\n friend std::basic_ostream<Char, Traits>& \n operator<< (std::basic_ostream<Char, Traits>& out, const Pos& p)\n {\n return out << p.x << \" \" << p.y << \" \" << p.z;\n }\n\n explicit Pos(double x_ = 0, double y_ = 0, double z_ = 0) \n : x(x_), y(y_), z(z_)\n {\n }\n };\n\n template <class OutputPosIterator, class InputPosIterator, class Number>\n void translate(OutputPosIterator first, OutputPosIterator last, \n InputPosIterator delta, Number factor)\n {\n for ( ; first != last; ++first, ++delta) {\n first->x += delta->x * factor;\n first->y += delta->y * factor;\n first->z += delta->z * factor;\n }\n }\n}\n\nint main(int argc, char *argv[])\n{\n const Pos delta[] = {\n // ruby -e\"(-1..1).each{|i| (-1..1).each{|j| (-1..1).each{|k| printf(\\\"Pos(%2d,%2d,%2d),\\n\\\", i, j, k) if (i!=0 || j!=0 || k!=0)}}}\"\n Pos(-1,-1,-1),\n Pos(-1,-1, 0),\n Pos(-1,-1, 1),\n Pos(-1, 0,-1),\n Pos(-1, 0, 0),\n Pos(-1, 0, 1),\n Pos(-1, 1,-1),\n Pos(-1, 1, 0),\n Pos(-1, 1, 1),\n Pos( 0,-1,-1),\n Pos( 0,-1, 0),\n Pos( 0,-1, 1),\n Pos( 0, 0,-1),\n Pos( 0, 0, 1),\n Pos( 0, 1,-1),\n Pos( 0, 1, 0),\n Pos( 0, 1, 1),\n Pos( 1,-1,-1),\n Pos( 1,-1, 0),\n Pos( 1,-1, 1),\n Pos( 1, 0,-1),\n Pos( 1, 0, 0),\n Pos( 1, 0, 1),\n Pos( 1, 1,-1),\n Pos( 1, 1, 0),\n Pos( 1, 1, 1),\n };\n const int N = sizeof(delta) / sizeof(*delta);\n\n // find neighbours of somePos\n double cube_size = 0.5; \n Pos somePos(0.5, 0.5, 0.5);\n\n std::vector<Pos> neighbours(N, somePos); \n translate(neighbours.begin(), neighbours.end(), delta, cube_size);\n\n // print neighbours\n std::copy(neighbours.begin(), neighbours.end(), \n std::ostream_iterator<Pos>(std::cout, \"\\n\"));\n std::cout << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 331382, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "for(int i = 0; i < 27, i++)\n{\n if(i == 13) continue;\n int dx = i%3 -1;\n int dy = (i/3)%3 -1;\n int dz = i/9 - 1;\n\n process(x+dx,y+dy,z+dz);\n}\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41706/" ]
326,891
<p>Is there an easy way to parse the user's HTTP_ACCEPT_LANGUAGE and set the locale in PHP?</p> <p>I know the Zend framework has a method to do this, but I'd rather not install the whole framework just to use that one bit of functionality.</p> <p>The PEAR I18Nv2 package is in beta and hasn't been changed for almost three years, so I'd rather not use that if possible.</p> <p>Also nice would be if it could figure out if the server was running on Windows or not, since Windows's locale strings are different from the rest of the world's... (German is "deu" or "german" instead of "de".)</p>
[ { "answer_id": 327042, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": true, "text": "en_US, en;q=0.8, fr_CA;q=0.2, *;q=0.1\n setlocale()" }, { "answer_id": 327419, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "$_SERVER['HTTP_ACCEPT_LANGUAGE'] q de_DE German_Germany q setlocale() false Zend_Locale setlocale() setlocale()" }, { "answer_id": 327472, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "http_negotiate_language" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29394/" ]
326,910
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
[ { "answer_id": 326912, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 4, "selected": false, "text": "def outer(a):\n b = compute_something_from(a)\n def inner():\n do_something_with(a, b)\n" }, { "answer_id": 37897092, "author": "Victor Barroso", "author_id": 2304601, "author_profile": "https://Stackoverflow.com/users/2304601", "pm_score": 2, "selected": false, "text": "def outer():\n def inner():\n pass\n\n if __debug__:\n test_inner(inner)\n # return\n\ndef test_inner(f):\n f() # this calls the inner function\n\nouter()\n python -O code.py\n" }, { "answer_id": 40512422, "author": "Alfe", "author_id": 1281485, "author_profile": "https://Stackoverflow.com/users/1281485", "pm_score": 3, "selected": false, "text": "def f(v1):\n v2 = 1\n def g(v3=2):\n return v1 + v2 + v3 + 4\n def h():\n return 16\n return g() + h() + 32\n\nclass C(object):\n def foo(self):\n def k(x):\n return [ self, x ]\n return k(3)\n\ndef m():\n vm = 1\n def n(an=2):\n vn = 4\n def o(ao=8):\n vo = 16\n return vm + an + vn + ao + vo\n return o()\n return n()\n import unittest\nfrom nested import nested\n\nclass TestNested(unittest.TestCase):\n def runTest(self):\n nestedG = nested(f, 'g', v1=8, v2=1)\n self.assertEqual(nestedG(2), 15)\n nestedH = nested(f, 'h')\n self.assertEqual(nestedH(), 16)\n nestedK = nested(C.foo, 'k', self='mock')\n self.assertEqual(nestedK(5), [ 'mock', 5 ])\n nestedN = nested(m, 'n', vm=1)\n nestedO = nested(nestedN, 'o', vm=1, an=2, vn=4)\n self.assertEqual(nestedO(8), 31)\n\ndef main(argv):\n unittest.main()\n\nif __name__ == '__main__':\n import sys\n sys.exit(main(sys.argv))\n nested import types\n\ndef freeVar(val):\n def nested():\n return val\n return nested.__closure__[0]\n\ndef nested(outer, innerName, **freeVars):\n if isinstance(outer, (types.FunctionType, types.MethodType)):\n outer = outer.func_code\n for const in outer.co_consts:\n if isinstance(const, types.CodeType) and const.co_name == innerName:\n return types.FunctionType(const, globals(), None, None, tuple(\n freeVar(freeVars[name]) for name in const.co_freevars))\n" }, { "answer_id": 67441739, "author": "LHM", "author_id": 5365001, "author_profile": "https://Stackoverflow.com/users/5365001", "pm_score": 0, "selected": false, "text": "# my_app.py\n\ndef util(func):\n # run some logic using func\n\ndef outer():\n def inner():\n pass\n\n util(inner)\n util inner def test_inner\n # Arrange\n mock_util = MagicMock()\n\n with patch.object(my_app, 'util', mock_util):\n outer() # run the outer function to capture the util call with MagicMock\n\n inner_function = mock_util.call_args[0][0]\n\n # Act\n inner_function() # run the inner function for testing\n\n # Assert\n # make whatever assertions you would like\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5624/" ]
326,919
<p>I have a row of buttons, which all create a pdf file which I want to open in a new tab. This way the button page stays on top, and the pdf's open to get printed. To prevent clicking a button twice I disable the button, like this (I use python):</p> <pre><code>&lt;input type='submit' value='Factureren' name='submitbutton' id='%s' onclick="javascript:document.getElementById('%s').disabled=true; document.getElementById('%s').className='button_disabled';"&gt; % ((but_id,) *3) </code></pre> <p>In FF3 this works fine, i.e. the form is submitted, the script executed and then the button disables. In IE the button just disables, but the form script isn't executed.</p> <p>Is there a solution to this IE problem?</p>
[ { "answer_id": 326923, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 3, "selected": false, "text": " <input type='submit' value='Factureren' name='submitbutton' id='%s' \nonclick=\"this.disabled=true; this.className='button_disabled';\"> % ((but_id,) *3)\n" }, { "answer_id": 326927, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 2, "selected": false, "text": "<input type=\"button\" value=\"Factureren\" name=\"submitbutton\" \nonclick=\"this.disabled=true; this.className='button_disabled'; this.form.submit();\">\n" }, { "answer_id": 326929, "author": "Stepan Mazurov", "author_id": 40786, "author_profile": "https://Stackoverflow.com/users/40786", "pm_score": 0, "selected": false, "text": "function toggleSubmit(){ \n frm=document.forms[0]\n if(frm.submit.disabled==true){\n frm.submit.disabled=false;\n }else{\n frm.submit.disabled=true;\n }\n }\n <input type='submit' value='Factureren' name='submitbutton'\nonclick=\"toggleSubmit();false;\"> % ((but_id,) *3)\n" }, { "answer_id": 326939, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 0, "selected": false, "text": "<input type=\"submit\" value=\"Factureren\" name=\"submitbutton' id=\"%s\"\nonclick=\"this.disabled = true; this.className = 'button_disabled'; true;\">\n% ((but_id,) *3)\n" }, { "answer_id": 327917, "author": "Ivan Vučica", "author_id": 39974, "author_profile": "https://Stackoverflow.com/users/39974", "pm_score": 0, "selected": false, "text": "onclick=\"javascript:document.getElementById('%s').disabled=true; \ndocument.getElementById('%s').className='button_disabled';\"\n onclick=\"document.getElementById('%s').disabled=true; \ndocument.getElementById('%s').className='button_disabled';\"\n onclick=\"document.getElementById('%s').disabled=true; \ndocument.getElementById('%s').className='button_disabled';\nthis.form.submit();\"\n" } ]
2008/11/28
[ "https://Stackoverflow.com/questions/326919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37986/" ]
326,937
<p>I have been using TortoiseSVN, svn, and subclipse and I think I understand the basics, but there's one thing that's been bugging me for a while: Merging introduces unwanted code. Here's the steps.</p> <p><code>trunk/test.txt@r2</code>. A test file was created with 'A' and a return:</p> <pre><code>A [EOF] </code></pre> <p><code>branches/TRY-XX-Foo/test.txt@r3</code>. Branched out the <code>trunk</code> to <code>TRY-XX-Foo</code>:</p> <pre><code>A [EOF] </code></pre> <p><code>branches/TRY-XX-Foo/test.txt@r4</code>. Made an unwanted change in <code>TRY-XX-Foo</code> and committed it:</p> <pre><code>A B (unwanted change) [EOF] </code></pre> <p><code>branches/TRY-XX-Foo/test.txt@r5</code>. Made an important bug fix in <code>TRY-XX-Foo</code> and committed it:</p> <pre><code>A B (unwanted change) C (important bug fix) [EOF] </code></pre> <p>Now, I would like to merge only the important bug fix back to trunk. So, I run merge for revision <code>4:5</code>. What I end up in my working directory is a conflict.</p> <p><code>trunk/test.txt</code>:</p> <pre><code>A &lt;&lt;&lt;&lt;&lt;&lt;&lt; .working ======= B (unwanted change) C (important bug fix) &gt;&gt;&gt;&gt;&gt;&gt;&gt; .merge-right.r5 [EOF] </code></pre> <p>Against my will, Subversion has now included "unwanted change" into the trunk code, and I need to weed them out manually. Is there a way to merge only specified revisions when multiple consecutive changes are made in the branch?</p> <p>The part of the problem is that B (unwated change) is included in .merge-right and I can't tell the difference between which revision it came from. I usually use TortoiseMerge and here's how it looks.</p> <p><img src="https://i.stack.imgur.com/NG2g7.png" alt="text.txt.working"></p>
[ { "answer_id": 326945, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 5, "selected": false, "text": "svnmerge.py merge -r4,7,11-15\n svn merge -c4,7 -r10:15 http://.../branches/TRY-XX-Foo\n" }, { "answer_id": 365976, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": true, "text": "A\n<<<<<<< .working\n=======\nB (unwanted change)\nC (important bug fix)\n>>>>>>> .merge-right.r341\n" }, { "answer_id": 486728, "author": "Dominik Grabiec", "author_id": 3719, "author_profile": "https://Stackoverflow.com/users/3719", "pm_score": 1, "selected": false, "text": "svn merge -r 4:3 test.txt\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3827/" ]
326,941
<p>I am planning on generating a Word document on the webserver dynamically. Is there good way of doing this in c#? I know I could script Word to do this but I would prefer another option.</p>
[ { "answer_id": 326952, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "Paragraph p = new Paragraph();\np.Runs.Add(new Run(\"Text can have multiple format styles, they can be \"));\np.Runs.Add(new Run(\"bold and italic\", \n TextFormats.Format.Bold | TextFormats.Format.Italic));\ndoc.Paragraphs.Add(p);\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
326,942
<p>My bash script doesn't work the way I want it to:</p> <pre><code>#!/bin/bash total="0" count="0" #FILE="$1" This is the easier way for FILE in $* do # Start processing all processable files while read line do if [[ "$line" =~ ^Total ]]; then tmp=$(echo $line | cut -d':' -f2) count=$(expr $count + 1) total=$(expr $total + $tmp) fi done &lt; $FILE done echo "The Total Is: $total" echo "$FILE" </code></pre> <p>Is there another way to modify this script so that it reads arguments into <code>$1</code> instead of <code>$FILE</code>? I've tried using a <code>while</code> loop:</p> <pre><code>while [ $1 != "" ] do .... done </code></pre> <p>Also when I implement that the code repeats itself. Is there a way to fix that as well?</p> <p>Another problem that I'm having is that when I have multiple files <code>hi*.txt</code> it gives me duplicates. Why? I have files like <code>hi1.txt</code> <code>hi1.txt~</code> but the tilde file is of 0 bytes, so my script shouldn't be finding anything.</p> <hr> <p>What i have is fine, but could be improved. I appreciate your awk suggestions but its currently beyond my level as a unix programmer. </p> <p>Strager: The files that my text editor generates automatically contain nothing..it is of 0 bytes..But yeah i went ahead and deleted them just to be sure. But no my script is in fact reading everything twice. I suppose its looping again when it really shouldnt. I've tried to silence that action with the exit commands..But wasnt successful.</p> <pre><code>while [ "$1" != "" ]; do # Code here # Next argument shift done </code></pre> <p>This code is pretty sweet, but I'm specifying all the possible commands at one time. Example: hi[145].txt If supplied would read all three files at once. Suppose the user enters hi*.txt; I then get all my hi files read twice and then added again.</p> <p>How can I code it so that it reads my files (just once) upon specification of hi*.txt? I really think that this is because of not having $1.</p>
[ { "answer_id": 326964, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 1, "selected": false, "text": "#!/bin/sh\n\nprocess() {\n echo \"doing something with $1\"\n}\n\nfor i in \"$@\" # Note use of \"$@\" to not break on filenames with whitespace\ndo\n process \"$i\"\ndone\n" }, { "answer_id": 326978, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 1, "selected": false, "text": "while [ \"$1\" != \"\" ]; do\n # Code here\n\n # Next argument\n shift\ndone\n" }, { "answer_id": 327081, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "grep '^Total:' \"$@\" |\ncut -d: -f2 |\nawk '{sum += $1}\n END { print sum }'\n awk cut awk grep \"^Total:\" \"$@\" |\nawk -F: '{sum += $2}\n END { print sum }'\n awk awk -F: '$1 ~ /^Total/ { sum += $2 }\n END { print sum }' \"$@\"\n perl -na -F: -e '$sum += $F[1] if m/^Total:/; END { print $sum; }' \"$@\"\n \"$@\" $* $1 $1 while [ $# -gt 0 ]\ndo\n ...process $1...\n shift\ndone\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40120/" ]
326,960
<p>Here's my problem.I have 2 xmlfiles with identical structure, with the second xml containing only few node compared to first.</p> <p>File1</p> <pre><code> &lt;root&gt; &lt;alpha&gt;111&lt;/alpha&gt; &lt;beta&gt;22&lt;/beta&gt; &lt;gamma&gt;&lt;/gamma&gt; &lt;delta&gt;&lt;/delta&gt; &lt;/root&gt; </code></pre> <p><strong>File2</strong></p> <pre><code> &lt;root&gt; &lt;beta&gt;XX&lt;/beta&gt; &lt;delta&gt;XX&lt;/delta&gt; &lt;/root&gt; </code></pre> <p>This's what the result should look like </p> <pre><code> &lt;root&gt; &lt;alpha&gt;111&lt;/alpha&gt; &lt;beta&gt;22&lt;/beta&gt; &lt;gamma&gt;&lt;/gamma&gt; &lt;delta&gt;XX&lt;/delta&gt; &lt;/root&gt; </code></pre> <p>Basically if the node contents of any node in File1 is blank then it should read the values from File2(if it exists, that is).</p> <p>I did try my luck with Microsoft XmlDiff API but it didn't work out for me(the patch process didn't apply changes to the source doc). Also I'm a bit worried about the DOM approach that it uses, because of the size of the xml that I'll be dealing with. Can you please suggest a good way of doing this. I'm using C# 2 </p>
[ { "answer_id": 326985, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "document() <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n\n <xsl:template match=\"root/*[.='']\">\n <xsl:variable name=\"file2node\">\n <xsl:copy-of select=\"document('File2.xml')/root/*[name()=name(current())]\"/>\n </xsl:variable>\n <xsl:choose>\n <xsl:when test=\"$file2node != ''\">\n <xsl:copy-of select=\"$file2node\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:copy/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n\n <xsl:template match=\"*\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\"/>\n <xsl:apply-templates/>\n </xsl:copy>\n </xsl:template>\n\n</xsl:stylesheet>\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28773/" ]
326,987
<p>I am trying to find out how to use usercontrols in asp.net mvc. I know how to add a usercontrol to a view and how to pass data to it. What I haven't been able to figure out is how do you do this without having to retrieve and pass the data in every single controller?</p> <p>For example, if I have a user control that displays the most recent posts on several but not all the pages in the site, how do I write the Controllers so that I get data for that usercontrol and pass it to the user control from only one place in the web site instead of getting and passing data in each of the different controllers that the user control is used in?</p> <p>I'm not sure if this makes sense or not. Is there a better or recommended way to handle an "island" of data that you want to display on several pages?</p> <p>I'm coming from web forms where I could just write a user control that got its own data and displayed data independently from the rest of whatever page it is used on.</p>
[ { "answer_id": 327057, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": " ViewData[\"RecentPosts\"] = RecentPosts.GetRecentPosts( this.GetType() );\n" }, { "answer_id": 327088, "author": "rajesh pillai", "author_id": 34644, "author_profile": "https://Stackoverflow.com/users/34644", "pm_score": 5, "selected": true, "text": " [HandleError]\n public class BaseController : Controller\n {\n CourseService cs = new CourseService();\n protected override void OnActionExecuting(ActionExecutingContext filterContext)\n {\n List<Tag> tags = cs.GetTags();\n ViewData[\"Tags\"] = tags;\n }\n\n }\n <div id=\"sidebar_b\">\n <asp:ContentPlaceHolder ID=\"ContentReferenceB\" runat=\"server\" >\n <% Html.RenderPartial(\"Tags\"); %>\n </asp:ContentPlaceHolder>\n </div>\n" }, { "answer_id": 327811, "author": "Matthew", "author_id": 20162, "author_profile": "https://Stackoverflow.com/users/20162", "pm_score": 2, "selected": false, "text": "<% Html.RenderAction(\"Index\", \"UserControlController\") %>\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32892/" ]
326,991
<p>What's the best way to get a function like the following to work:</p> <pre><code>def getNearest(zipCode, miles): </code></pre> <p>That is, given a zipcode (07024) and a radius, return all zipcodes which are within that radius?</p>
[ { "answer_id": 37577689, "author": "Glenn Van Schil", "author_id": 4614788, "author_profile": "https://Stackoverflow.com/users/4614788", "pm_score": 0, "selected": false, "text": "public List<City> findCityInRange(GeoPoint geoPoint, double distance) {\n List<City> cities = new ArrayList<City>();\n QueryBuilder queryBuilder = geoDistanceQuery(\"geoPoint\")\n .point(geoPoint.getLat(), geoPoint.getLon())\n //.distance(distance, DistanceUnit.KILOMETERS) original\n .distance(distance, DistanceUnit.MILES)\n .optimizeBbox(\"memory\")\n .geoDistance(GeoDistance.ARC);\n\n SearchRequestBuilder builder = esClient.getClient()\n .prepareSearch(INDEX)\n .setTypes(\"city\")\n .setSearchType(SearchType.QUERY_THEN_FETCH)\n .setScroll(new TimeValue(60000))\n .setSize(100).setExplain(true)\n .setPostFilter(queryBuilder)\n .addSort(SortBuilders.geoDistanceSort(\"geoPoint\")\n .order(SortOrder.ASC)\n .point(geoPoint.getLat(), geoPoint.getLon())\n //.unit(DistanceUnit.KILOMETERS)); Original\n .unit(DistanceUnit.MILES));\n\n SearchResponse response = builder\n .execute()\n .actionGet();\n\n\n SearchHit[] hits = response.getHits().getHits();\n\n scroll:\n while (true) {\n\n for (SearchHit hit : hits) {\n Map<String, Object> result = hit.getSource();\n cities.add(mapper.convertValue(result, City.class));\n }\n\n response = esClient.getClient().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();\n if (response.getHits().getHits().length == 0) {\n break scroll;\n }\n }\n\n return cities;\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
326,992
<p>Given that I only have one monitor, what's the best way to debug a program which uses the entire screen (such as a DirectX application)? Tools such as the step-by-step debugger seem useless in this context. Also, printing to the console isn't as effective, since you can only look at the console once the application has terminated.</p>
[ { "answer_id": 327018, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "fprint(logfile,\"%s:%d\\n\",__FILE__,__LINE__);\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/326992", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
327,002
<p>I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?</p> <p><b>UPDATE</b></p> <p>This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?</p> <p>I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.</p> <h3>My email:</h3> <blockquote> <p>There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better?</p> </blockquote> <h3>His response:</h3> <blockquote> <p>pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...</p> </blockquote>
[ { "answer_id": 327011, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 8, "selected": true, "text": "math.sqrt(x) x**0.5 import math\nN = 1000000\n %%timeit\nfor i in range(N):\n z=i**.5\n %%timeit\nfor i in range(N):\n z=math.sqrt(i)\n" }, { "answer_id": 327024, "author": "JimB", "author_id": 32880, "author_profile": "https://Stackoverflow.com/users/32880", "pm_score": 4, "selected": false, "text": "math.sqrt sqrt from math import sqrt\n x**.5 import math\n sqrt = math.sqrt\n" }, { "answer_id": 327048, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "$ python -mtimeit -s\"from math import sqrt; x = 123\" \"x**.5\"\n1000000 loops, best of 3: 0.445 usec per loop\n\n$ python -mtimeit -s\"from math import sqrt; x = 123\" \"sqrt(x)\"\n1000000 loops, best of 3: 0.574 usec per loop\n\n$ python -mtimeit -s\"import math; x = 123\" \"math.sqrt(x)\"\n1000000 loops, best of 3: 0.727 usec per loop\n x**.5 sqrt(x) $ \\Python30\\python -mtimeit -s\"from math import sqrt; x = 123\" \"x**.5\"\n1000000 loops, best of 3: 0.803 usec per loop\n\n$ \\Python30\\python -mtimeit -s\"from math import sqrt; x = 123\" \"sqrt(x)\"\n1000000 loops, best of 3: 0.695 usec per loop\n\n$ \\Python30\\python -mtimeit -s\"import math; x = 123\" \"math.sqrt(x)\"\n1000000 loops, best of 3: 0.761 usec per loop\n math.sqrt(x) x**.5 $ python -mtimeit -s\"from math import sqrt; x = 123\" \"x**.5\"\n10000000 loops, best of 3: 0.173 usec per loop\n$ python -mtimeit -s\"from math import sqrt; x = 123\" \"sqrt(x)\"\n10000000 loops, best of 3: 0.115 usec per loop\n$ python -mtimeit -s\"import math; x = 123\" \"math.sqrt(x)\"\n10000000 loops, best of 3: 0.158 usec per loop\n$ python3.1 -mtimeit -s\"from math import sqrt; x = 123\" \"x**.5\"\n10000000 loops, best of 3: 0.194 usec per loop\n$ python3.1 -mtimeit -s\"from math import sqrt; x = 123\" \"sqrt(x)\"\n10000000 loops, best of 3: 0.123 usec per loop\n$ python3.1 -mtimeit -s\"import math; x = 123\" \"math.sqrt(x)\"\n10000000 loops, best of 3: 0.157 usec per loop\n" }, { "answer_id": 327049, "author": "zdan", "author_id": 4304, "author_profile": "https://Stackoverflow.com/users/4304", "pm_score": 2, "selected": false, "text": "PS C:\\> python -m timeit -n 100000 10000**.5\n100000 loops, best of 3: 0.0543 usec per loop\nPS C:\\> python -m timeit -n 100000 -s \"import math\" math.sqrt(10000)\n100000 loops, best of 3: 0.162 usec per loop\nPS C:\\> python -m timeit -n 100000 -s \"from math import sqrt\" sqrt(10000)\n100000 loops, best of 3: 0.0541 usec per loop\n" }, { "answer_id": 2695986, "author": "bobpaul", "author_id": 308709, "author_profile": "https://Stackoverflow.com/users/308709", "pm_score": 1, "selected": false, "text": ">>> timeit1()\nTook 0.564911 seconds\n>>> timeit2()\nTook 0.403087 seconds\n>>> timeit1()\nTook 0.604713 seconds\n>>> timeit2()\nTook 0.387749 seconds\n>>> timeit1()\nTook 0.587829 seconds\n>>> timeit2()\nTook 0.379381 seconds\n" }, { "answer_id": 2696173, "author": "zoli2k", "author_id": 259275, "author_profile": "https://Stackoverflow.com/users/259275", "pm_score": 3, "selected": false, "text": "(float).__pow__() pow() math.sqrt() sqrt() pow(x,y) pow(x,0.5) sqrt() .** math.sqrt zoltan@host:~$ python2.4 p.py \nTook 0.173994 seconds\nTook 0.158991 seconds\nzoltan@host:~$ python2.5 p.py \nTook 0.182321 seconds\nTook 0.155394 seconds\nzoltan@host:~$ python2.6 p.py \nTook 0.166766 seconds\nTook 0.097018 seconds\n" }, { "answer_id": 2696402, "author": "lunixbochs", "author_id": 293352, "author_profile": "https://Stackoverflow.com/users/293352", "pm_score": 2, "selected": false, "text": "from ctypes import c_float, c_long, byref, POINTER, cast\n\ndef sqrt(num):\n xhalf = 0.5*num\n x = c_float(num)\n i = cast(byref(x), POINTER(c_long)).contents.value\n i = c_long(0x5f375a86 - (i>>1))\n x = cast(byref(i), POINTER(c_float)).contents.value\n\n x = x*(1.5-xhalf*x*x)\n x = x*(1.5-xhalf*x*x)\n return x * num\n from struct import pack, unpack\n\ndef sqrt_struct(num):\n xhalf = 0.5*num\n i = unpack('L', pack('f', 28.0))[0]\n i = 0x5f375a86 - (i>>1)\n x = unpack('f', pack('L', i))[0]\n\n x = x*(1.5-xhalf*x*x)\n x = x*(1.5-xhalf*x*x)\n return x * num\n" }, { "answer_id": 52870351, "author": "hkBst", "author_id": 5600363, "author_profile": "https://Stackoverflow.com/users/5600363", "pm_score": 2, "selected": false, "text": "sqrt from sys import version\nfrom time import time\nfrom math import sqrt, pi, e\n\nprint(version)\n\nN = 1_000_000\n\ndef timeit1():\n z = N * e\n s = time()\n for n in range(N):\n z += (n * pi) ** .5 - z ** .5\n print (f\"Took {(time() - s):.4f} seconds to calculate {z}\")\n\ndef timeit2():\n z = N * e\n s = time()\n for n in range(N):\n z += sqrt(n * pi) - sqrt(z)\n print (f\"Took {(time() - s):.4f} seconds to calculate {z}\")\n\ndef timeit3(arg=sqrt):\n z = N * e\n s = time()\n for n in range(N):\n z += arg(n * pi) - arg(z)\n print (f\"Took {(time() - s):.4f} seconds to calculate {z}\")\n\ntimeit1()\ntimeit2()\ntimeit3()\n 3.6.6 (default, Jul 19 2018, 14:25:17) \n[GCC 8.1.1 20180712 (Red Hat 8.1.1-5)]\nTook 0.3747 seconds to calculate 3130485.5713865166\nTook 0.2899 seconds to calculate 3130485.5713865166\nTook 0.2635 seconds to calculate 3130485.5713865166\n 3.7.4 (default, Jul 9 2019, 16:48:28) \n[GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]\nTook 0.2583 seconds to calculate 3130485.5713865166\nTook 0.1612 seconds to calculate 3130485.5713865166\nTook 0.1563 seconds to calculate 3130485.5713865166\n" }, { "answer_id": 61428735, "author": "jsbueno", "author_id": 108205, "author_profile": "https://Stackoverflow.com/users/108205", "pm_score": 1, "selected": false, "text": "In [77]: dis.dis(a) \n 2 0 LOAD_CONST 1 (1.4142135623730951)\n 2 RETURN_VALUE\n\nIn [78]: def a(): \n ...: return 2 ** 0.5 \n ...: \n\nIn [79]: import dis \n\nIn [80]: dis.dis(a) \n 2 0 LOAD_CONST 1 (1.4142135623730951)\n 2 RETURN_VALUE\n\n" }, { "answer_id": 71234817, "author": "EmperorArthurIX", "author_id": 18287280, "author_profile": "https://Stackoverflow.com/users/18287280", "pm_score": 2, "selected": false, "text": "sqrt(x) x**0.5 pow(x, 0.5) math.sqrt() ** pow() ** pow() math.sqrt() import time\nimport math\nprint(\"x**0.5 : \")\nfor _ in range(5):\n start = time.time()\n for i in range(int(1e8)):\n i**0.5\n end = time.time()\n print(end-start)\nprint(\"math.sqrt(x) : \")\nfor _ in range(5):\n start = time.time()\n for i in range(int(1e8)):\n math.sqrt(i)\n end = time.time()\n print(end-start)\nprint(\"pow(x,0.5) : \")\nfor _ in range(5):\n start = time.time()\n for i in range(int(1e8)):\n pow(i,0.5)\n end = time.time()\n print(end-start)\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41718/" ]
327,010
<p>A problem that we need to solve regularly at my workplace is how to build sql statements based on user supplied table/column names. The issue I am trying to address is the commas between column names. </p> <p>One technique looks something like this.</p> <pre><code>selectSql = "SELECT "; for (z = 0; z &lt; columns.size(); z++) { selectSql += columns[z]._name; selectSql += ", "; } selectSql = selectSql(0, selectSql.len() - 2); selectSql += "FROM some-table"; </code></pre> <p>Another technique looks something like this</p> <pre><code>selectSql = "SELECT "; for (z = 0; z &lt; columns.size(); z++) { selectSql += columns[z]._name; if (z &lt; columns.size() - 1) selectSql += ", "; } selectSql += "FROM some-table"; </code></pre> <p>I am not particularly enthralled by either of these implementations.</p> <p>I am interesting in hearing ideas for other ways to address this issue, with an eye toward making the code easier to read/understand/maintain.</p> <p>What alternate techniques are available?</p>
[ { "answer_id": 327022, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "pad = \"\"\nstmt = \"SELECT \"\n\nfor (i = 0; i < number; i++)\n{\n stmt += pad + item[i]\n pad = \", \"\n}\n" }, { "answer_id": 327023, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 0, "selected": false, "text": "// Untested\n#include <numeric>\n\ntemplate<std::string separator>\nstruct JoinColumns {\n std::string operator()(Column a, Column b) {\n return a._name + separator + b._name;\n }\n\n // Too lazy to come up with a better name\n std::string inArray(T array) {\n stl::accumulate(array.begin(), array.end(), std::string(), *this);\n }\n};\n\nselectSql += stl::accumulate(columns.begin(), columns.end(), std::string(), JoinColumns<\", \">());\n// or\nselectSql += JoinColumns<\", \">().inArray(columns);\n" }, { "answer_id": 327056, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 0, "selected": false, "text": "for (z = 0; z < columns.size(); z++)\n{\n if( z != 0 )\n selectSql += \", \"; \n selectSql += columns[z]._name;\n}\n" }, { "answer_id": 327070, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "selectSql = \"SELECT \";\nselectSql += columns[0]._name;\n\nfor (z = 1; z < columns.size(); z++) {\n selectSql += \", \";\n selectSql += columns[z]._name;\n}\n\nselectSql += \" FROM some-table\";\n" }, { "answer_id": 327098, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 2, "selected": false, "text": "SELECT A FROM T\n\n-- Is the same as \n\nSELECT A,1 FROM T\n\n-- Apart from there is an extra column named 1 where each value is 1\n #include <sstream>\n#include <iterator>\n#include <algorithm>\n\n std::stringstream select;\n\n // Build select statement.\n select << \"SELECT \";\n std::copy(col.begin(),col.end(),std::ostream_iterator<std::string>(select,\" , \"));\n select << \" 1 FROM TABLE PLOP\";\n" }, { "answer_id": 327862, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "struct join {\n std::string sep;\n join(std::string const& sep): sep(sep) { }\n\n template<typename Column>\n std::string operator()(Column const& a, Column const& b) const {\n return a._name + sep + b._name;\n }\n};\n std::string query = std::accumulate(cols.begin(), cols.end(), \n std::string(\"SELECT \"), join(\", \")) + \" FROM some-table;\";\n" }, { "answer_id": 327932, "author": "cadabra", "author_id": 39132, "author_profile": "https://Stackoverflow.com/users/39132", "pm_score": 1, "selected": false, "text": "string sql = \"SELECT \" + join(cols.begin(), cols.end(), \", \") + \" FROM some_table\";\n template <typename I>\nstring join(I begin, I end, const string& sep){\n ostringstream out;\n for(; begin != end; ++begin){\n out << *begin;\n if(begin+1 != end) out << sep;\n }\n return out.str();\n}\n" }, { "answer_id": 328026, "author": "D.Shawley", "author_id": 41747, "author_profile": "https://Stackoverflow.com/users/41747", "pm_score": 1, "selected": false, "text": "std::string\nbuild_sql(std::vector<std::string> const& colNames,\n std::string const& tableName)\n{\n std::ostringstream sql;\n sql << \"SELECT \"\n << boost::algorithm::join(colNames, std::string(\",\"))\n << \" FROM \" << tableName;\n return sql.str();\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7734/" ]
327,026
<p>I use something like this: screen.addstr(text, color_pair(1) | A_BOLD), but it doesn't seem to work.. However, A_REVERSE and all others attribute does work! </p> <p>In fact, I'm trying to print something in white, but the COLOR_WHITE prints it gray.. and after a while of searching, it seems that printing it gray + BOLD makes it! </p> <p>Any helps would be greatly appreciated.</p>
[ { "answer_id": 327072, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "#!/usr/bin/env python\nfrom itertools import cycle\nimport curses, contextlib, time\n\n@contextlib.contextmanager\ndef curses_screen():\n \"\"\"Contextmanager's version of curses.wrapper().\"\"\"\n try:\n stdscr=curses.initscr()\n curses.noecho()\n curses.cbreak()\n stdscr.keypad(1)\n try: curses.start_color()\n except: pass\n\n yield stdscr\n finally:\n stdscr.keypad(0)\n curses.echo()\n curses.nocbreak()\n curses.endwin()\n\nif __name__==\"__main__\":\n with curses_screen() as stdscr:\n c = curses.A_BOLD\n if curses.has_colors():\n curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)\n c |= curses.color_pair(1)\n\n curses.curs_set(0) # make cursor invisible\n\n y, x = stdscr.getmaxyx()\n for col in cycle((c, curses.A_BOLD)):\n stdscr.erase()\n stdscr.addstr(y//2, x//2, 'abc', col)\n stdscr.refresh()\n time.sleep(1)\n" }, { "answer_id": 53016371, "author": "David", "author_id": 10565176, "author_profile": "https://Stackoverflow.com/users/10565176", "pm_score": 3, "selected": false, "text": "screen.addstr(text, curses.color_pair(1) | curses.A_BOLD) curses. import curses" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41722/" ]
327,035
<p>I have a particular PHP page that, for various reasons, needs to save ~200 fields to a database. These are 200 separate insert and/or update statements. Now the obvious thing to do is reduce this number but, like I said, for reasons I won't bother going into I can't do this.</p> <p>I wasn't expecting this problem. Selects seem reasonably performant in MySQL but inserts/updates aren't (it takes about 15-20 seconds to do this update, which is naturally unacceptable). I've written Java/Oracle systems that can happily do thousands of inserts/updates in the same time (in both cases running local databases; MySQL 5 vs OracleXE).</p> <p>Now in something like Java or .Net I could quite easily do one of the following:</p> <ol> <li>Write the data to an in-memory write-behind cache (ie it would know how to persist to the database and could do so asynchronously);</li> <li>Write the data to an in-memory cache and use the PaaS (Persistence as a Service) model ie a listener to the cache would persist the fields; or</li> <li>Simply start a background process that could persist the data.</li> </ol> <p>The minimal solution is to have a cache that I can simply update, which will separately go and upate the database in its own time (ie it'll return immediately after update the in-memory cache). This can either be a global cache or a session cache (although a global shared cache does appeal in other ways).</p> <p>Any other solutions to this kind of problem?</p>
[ { "answer_id": 327159, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "mysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\n mysql_query('INSERT INTO tableName VALUES(...),(...),(...),(...)');\n" }, { "answer_id": 327972, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "UPDATE INSERT MYISAM INNODB INNODB SELECT INSERT UPDATE" }, { "answer_id": 1912406, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "LOAD DATA INFILE 'data.txt' INTO TABLE table2\n FIELDS TERMINATED BY '\\t';\n" }, { "answer_id": 8957362, "author": "Zerkonet", "author_id": 1162891, "author_profile": "https://Stackoverflow.com/users/1162891", "pm_score": 1, "selected": false, "text": "mysql_query('start transaction');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)');\nmysql_query('INSERT INTO tableName VALUES(...)'); \nmysql_query('commit;')\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
327,043
<p>I can find tutorials about mapping textures to polygons specifying vertices etc. but nothing regarding how to apply a texture to a cube (or other stuff) drawn with glut (glutSolidCube).</p> <p>I am doing something like:</p> <pre><code>glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, decal); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, nearest); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, nearest); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 4, myImageWidth, myImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid *)myImage); //... glEnable(GL_TEXTURE_2D); //now draw the cube glutSolidCube(N); </code></pre> <p>Doing this I get the texture to apply to the cube but the whole cube gets the color of the first byte in the texture!</p> <p>Is there any way of mapping a texture to a solid cube (and other solids) when using glutSolidCube?</p>
[ { "answer_id": 327135, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "glutSolidCube() glutSolidCube() glutSolidCube() /* Copyright (c) Mark J. Kilgard, 1994, 1997. */\n\n/** \n(c) Copyright 1993, Silicon Graphics, Inc. \n\nALL RIGHTS RESERVED \n\nPermission to use, copy, modify, and distribute this software \nfor any purpose and without fee is hereby granted, provided \nthat the above copyright notice appear in all copies and that \nboth the copyright notice and this permission notice appear in \nsupporting documentation, and that the name of Silicon \nGraphics, Inc. not be used in advertising or publicity \npertaining to distribution of the software without specific, \nwritten prior permission.\n\nTHE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU\n\"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR\nOTHERWISE, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF\nMERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO\nEVENT SHALL SILICON GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE\nELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT OR\nCONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER,\nINCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE,\nSAVINGS OR REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR\nNOT SILICON GRAPHICS, INC. HAS BEEN ADVISED OF THE POSSIBILITY\nOF SUCH LOSS, HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\nARISING OUT OF OR IN CONNECTION WITH THE POSSESSION, USE OR\nPERFORMANCE OF THIS SOFTWARE.\n\nUS Government Users Restricted Rights\n\nUse, duplication, or disclosure by the Government is subject to\nrestrictions set forth in FAR 52.227.19(c)(2) or subparagraph\n(c)(1)(ii) of the Rights in Technical Data and Computer\nSoftware clause at DFARS 252.227-7013 and/or in similar or\nsuccessor clauses in the FAR or the DOD or NASA FAR\nSupplement. Unpublished-- rights reserved under the copyright\nlaws of the United States. Contractor/manufacturer is Silicon\nGraphics, Inc., 2011 N. Shoreline Blvd., Mountain View, CA\n94039-7311.\n\nOpenGL(TM) is a trademark of Silicon Graphics, Inc.\n*/\n\nstatic void\ndrawBox(GLfloat size, GLenum type)\n{\n static GLfloat n[6][3] =\n {\n {-1.0, 0.0, 0.0},\n {0.0, 1.0, 0.0},\n {1.0, 0.0, 0.0},\n {0.0, -1.0, 0.0},\n {0.0, 0.0, 1.0},\n {0.0, 0.0, -1.0}\n };\n static GLint faces[6][4] =\n {\n {0, 1, 2, 3},\n {3, 2, 6, 7},\n {7, 6, 5, 4},\n {4, 5, 1, 0},\n {5, 6, 2, 1},\n {7, 4, 0, 3}\n };\n GLfloat v[8][3];\n GLint i;\n\n v[0][0] = v[1][0] = v[2][0] = v[3][0] = -size / 2;\n v[4][0] = v[5][0] = v[6][0] = v[7][0] = size / 2;\n v[0][1] = v[1][1] = v[4][1] = v[5][1] = -size / 2;\n v[2][1] = v[3][1] = v[6][1] = v[7][1] = size / 2;\n v[0][2] = v[3][2] = v[4][2] = v[7][2] = -size / 2;\n v[1][2] = v[2][2] = v[5][2] = v[6][2] = size / 2;\n\n for (i = 5; i >= 0; i--) {\n glBegin(type);\n glNormal3fv(&n[i][0]);\n glVertex3fv(&v[faces[i][0]][0]);\n glVertex3fv(&v[faces[i][1]][0]);\n glVertex3fv(&v[faces[i][2]][0]);\n glVertex3fv(&v[faces[i][3]][0]);\n glEnd();\n }\n}\n\nvoid APIENTRY\nglutSolidCube(GLdouble size)\n{\n drawBox(size, GL_QUADS);\n}\n" }, { "answer_id": 5011345, "author": "Humayun", "author_id": 618847, "author_profile": "https://Stackoverflow.com/users/618847", "pm_score": 4, "selected": false, "text": " glEnable(GL_TEXTURE_GEN_S); //enable texture coordinate generation\n glEnable(GL_TEXTURE_GEN_T);\n glBindTexture(GL_TEXTURE_2D, theTexture[2]);\n glutSolidCube(2);\n glDisable(GL_TEXTURE_GEN_S); //enable texture coordinate generation\n glDisable(GL_TEXTURE_GEN_T);\n" }, { "answer_id": 62602579, "author": "Anton Duzenko", "author_id": 505984, "author_profile": "https://Stackoverflow.com/users/505984", "pm_score": 0, "selected": false, "text": "glBegin\\End GL_TEXTURE_GEN_S\\T void drawBox() {\n static glm::vec3 n[6] =\n {\n {-1.0, 0.0, 0.0},\n {0.0, 1.0, 0.0},\n {1.0, 0.0, 0.0},\n {0.0, -1.0, 0.0},\n {0.0, 0.0, 1.0},\n {0.0, 0.0, -1.0}\n };\n static int faces[6][4] =\n {\n {0, 1, 2, 3},\n {3, 2, 6, 7},\n {7, 6, 5, 4},\n {4, 5, 1, 0},\n {5, 6, 2, 1},\n {7, 4, 0, 3}\n };\n glm::vec3 v[8];\n int i;\n\n v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1;\n v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1;\n v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1;\n v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1;\n v[0][2] = v[3][2] = v[4][2] = v[7][2] = -1;\n v[1][2] = v[2][2] = v[5][2] = v[6][2] = 1;\n\n auto& surface = surfaces[0];\n\n for ( i = 0; i < 6; i++ ) {\n for ( int j = 0; j < 4; j++ ) \n surface.normals.push_back( n[i] );\n auto i1 = i * 4;\n surface.indices.push_back( i1 + 0 );\n surface.indices.push_back( i1 + 1 );\n surface.indices.push_back( i1 + 3 );\n surface.indices.push_back( i1 + 1 );\n surface.indices.push_back( i1 + 2 );\n surface.indices.push_back( i1 + 3 );\n surface.vertices.push_back( v[faces[i][0]] );\n surface.vertices.push_back( v[faces[i][1]] );\n surface.vertices.push_back( v[faces[i][2]] );\n surface.vertices.push_back( v[faces[i][3]] );\n surface.texCoords.push_back( { 0, 0 } );\n surface.texCoords.push_back( { 0, 1 } );\n surface.texCoords.push_back( { 1, 0 } );\n surface.texCoords.push_back( { 1, 1 } );\n }\n }\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311500/" ]
327,047
<p>Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of: </p> <pre><code>$("&lt;div&gt;&lt;/div&gt;"); </code></pre> <p>However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?</p> <p><a href="https://stackoverflow.com/a/268520/32943">This answer</a> has the benchmarks to the suggestions below.</p>
[ { "answer_id": 327061, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": " $(\"<div/>\");\n" }, { "answer_id": 327065, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 7, "selected": false, "text": "$('<div>');\n var it = 50000;\n\nvar start = new Date().getTime();\nfor (i = 0; i < it; ++i) {\n // test creation of an element \n // see below statements\n}\nvar end = new Date().getTime();\nalert( end - start ); \n\nvar e = $( document.createElement('div') ); // ~300ms\nvar e = $('<div>'); // ~3100ms\nvar e = $('<div></div>'); // ~3200ms\nvar e = $('<div/>'); // ~3500ms \n" }, { "answer_id": 327068, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 9, "selected": true, "text": "$(document.createElement('div'));" }, { "answer_id": 2207532, "author": "Irshad", "author_id": 267109, "author_profile": "https://Stackoverflow.com/users/267109", "pm_score": 4, "selected": false, "text": "document.createElement('div')" }, { "answer_id": 2709653, "author": "edwin", "author_id": 211422, "author_profile": "https://Stackoverflow.com/users/211422", "pm_score": 5, "selected": false, "text": "$('<div>') document.createElement()" }, { "answer_id": 3782205, "author": "Tobiah", "author_id": 456616, "author_profile": "https://Stackoverflow.com/users/456616", "pm_score": 3, "selected": false, "text": "$(\"<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>\")\n" }, { "answer_id": 8961098, "author": "Erel Segal-Halevi", "author_id": 827927, "author_profile": "https://Stackoverflow.com/users/827927", "pm_score": 3, "selected": false, "text": "$(document.createElement('div'))" }, { "answer_id": 17613885, "author": "Jani Hyytiäinen", "author_id": 611056, "author_profile": "https://Stackoverflow.com/users/611056", "pm_score": 3, "selected": false, "text": "$(document.createElement('div')) $('<div>') $(document.createElement('div')) var e = $(document.createElement('div')).appendTo('#target');\nvar e = $('<div>').appendTo('#target');\nvar e = $('<div></div>').appendTo('#target');\nvar e = $('<div/>').appendTo('#target');\n" }, { "answer_id": 19364869, "author": "The Alpha", "author_id": 741747, "author_profile": "https://Stackoverflow.com/users/741747", "pm_score": 7, "selected": false, "text": "jQuery $('<div/>', {\n 'id':'myDiv',\n 'class':'myClass',\n 'text':'Text Only',\n}).on('click', function(){\n alert(this.id); // myDiv\n}).appendTo('body');\n $('<div/>', {\n 'id':'myDiv',\n 'class':'myClass',\n 'style':'cursor:pointer;font-weight:bold;',\n 'html':'<span>For HTML</span>',\n 'click':function(){ alert(this.id) },\n 'mouseenter':function(){ $(this).css('color', 'red'); },\n 'mouseleave':function(){ $(this).css('color', 'black'); }\n}).appendTo('body');\n handlers $(document).on('click', '.myClass', function(){\n alert(this.innerHTML);\n});\n\nvar i=1;\nfor(;i<=200;i++){\n $('<div/>', {\n 'class':'myClass',\n 'html':'<span>Element'+i+'</span>'\n }).appendTo('body');\n}\n myClass $('<input/>', {\n 'type': 'Text',\n 'value':'Some Text',\n 'size': '30'\n}).appendTo(\"body\");\n size jQuery-1.8.0 jQuery-1.7.2 size 30 size jQuery-1.8.3 size $('<input/>', {\n 'type': 'Text',\n 'value':'Some Text',\n attr: { size: \"30\" }\n}).appendTo(\"body\");\n $('<input/>', {\n 'type': 'Text',\n 'value':'Some Text',\n prop: { size: \"30\" }\n}).appendTo(\"body\");\n attr/prop jQuery-1.8.0 and later jQuery-1.7.2 or earlier jQuery 1.6.4 $('<input/>')\n.attr( { type:'text', size:50, autofocus:1 } )\n.val(\"Some text\").appendTo(\"body\");\n 'Size'(capital S) 'size' version-2.0.2 $('<input>', {\n 'type' : 'text',\n 'Size' : '50', // size won't work\n 'autofocus' : 'true'\n}).appendTo('body');\n Attributes vs. Properties" }, { "answer_id": 25848600, "author": "Marcel GJS", "author_id": 2849950, "author_profile": "https://Stackoverflow.com/users/2849950", "pm_score": 2, "selected": false, "text": "var select = jQuery(\"#selecter\");\njQuery(\"`<option/>`\",{value: someValue, text: someText}).appendTo(select);\n var select = jQuery(\"#selecter\");\njQuery(document.createElement('option')).prop({value: someValue, text: someText}).appendTo(select);\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32943/" ]
327,052
<p>I'm working on a CakePHP 1.2 application. I have a model "User" defined with a few HABTM relationships with other tables through a join table.</p> <p>I'm now tasked with finding User information based on the data stored in one of these HABTM tables. Unfortunately, when the query executes, my condition is rejected with an error about a missing table. Upon inspection it seems that CakePHP is not including any of the HABTM tables in the select statement.</p> <p>My User HABTM relationship is as follows:</p> <pre><code> var $hasAndBelongsToMany = array( 'Course' =&gt; array( 'className' =&gt; 'Course', 'joinTable' =&gt; 'course_members', 'foreignKey' =&gt; 'user_id', 'associationForeignKey' =&gt; 'course_id', 'conditions' =&gt; '', 'order' =&gt; '', 'limit' =&gt; '', 'uniq' =&gt; false, 'finderQuery' =&gt; '', 'deleteQuery' =&gt; '', 'insertQuery' =&gt; '' ), 'School' =&gt; array( 'className' =&gt; 'School', 'joinTable' =&gt; 'school_members', 'foreignKey' =&gt; 'user_id', 'associationForeignKey' =&gt; 'school_id', 'conditions' =&gt; '', 'order' =&gt; '', 'limit' =&gt; '', 'uniq' =&gt; false, 'finderQuery' =&gt; '', 'deleteQuery' =&gt; '', 'insertQuery' =&gt; '' ), 'Team' =&gt; array( 'className' =&gt; 'Team', 'joinTable' =&gt; 'team_members', 'foreignKey' =&gt; 'user_id', 'associationForeignKey' =&gt; 'team_id', 'conditions' =&gt; '', 'order' =&gt; '', 'limit' =&gt; '', 'uniq' =&gt; false, 'finderQuery' =&gt; '', 'deleteQuery' =&gt; '', 'insertQuery' =&gt; '' ) ); </code></pre> <p>The error is:</p> <blockquote> <p>SQL Error: 1054: Unknown column 'School.name' in 'where clause'</p> </blockquote> <p>And finally, the query it is trying to execute</p> <pre><code> SELECT `User`.`id`, `User`.`username`, `User`.`password`, `User`.`firstName`, `User`.`lastName`, `User`.`email `, `User`.`phone`, `User`.`streetAddress`, `User`.`city`, `User`.`province`, `User`.`country`, `User `.`postal`, `User`.`userlevel`, `User`.`modified`, `User`.`created`, `User`.`deleted`, `User`.`deleted_date ` FROM `users` AS `User` WHERE `User`.`id` = 6 AND `School`.`name` LIKE '%Test%' LIMIT 1 </code></pre>
[ { "answer_id": 3431591, "author": "Asif Zardari", "author_id": 413985, "author_profile": "https://Stackoverflow.com/users/413985", "pm_score": 3, "selected": false, "text": "$this->Recipe->Tag->find('all', array(\n 'conditions' => array('Tag.name' => 'Dessert')));\n $this->Recipe->bindModel(array('hasOne' => array('RecipesTag')));\n$this->Recipe->find('all', array(\n 'fields' => array('Recipe.*'),\n 'conditions' => array('RecipesTag.tag_id' => 124) // id of Dessert\n));\n $this->Recipe->bindModel(array('hasOne' => array('RecipesTag',\n 'FilterTag' => array(\n 'className' => 'Tag',\n 'foreignKey' => false,\n 'conditions' => array('FilterTag.id = RecipesTag.tag_id')\n))));\n$this->Recipe->find('all', array(\n 'fields' => array('Recipe.*'),\n 'conditions' => array('FilterTag.name' => 'Dessert')\n));\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
327,060
<p>I have a need to evaluate user-defined logical expressions of arbitrary complexity on some PHP pages. Assuming that form fields are the primary variables, it would need to:</p> <ul> <li>substitute"varibles" for form fields values;</li> <li>handle comparison operators, minimally ==, &lt;, &lt;=, >= and > by symbol, name (eg eq, lt, le, ge, gt respectively);</li> <li>handle boolean operators not, and, or and possibly xor by name, symbol (eg !, &amp;&amp;, || and ^^ respectively);</li> <li>handle literal values for strings and numbers;</li> <li>be plaintext not XML (eg "firstname == '' or lastname == ''); and</li> <li>be reasonably performant.</li> </ul> <p>Now in years gone by I've written recursive descent parsers that could build an expression tree and do this kind of thing but thats not a task I'm relishing in PHP so I'm hoping there are things out there that will at least get me some of the way there.</p> <p>Suggestions?</p>
[ { "answer_id": 31758193, "author": "Cam", "author_id": 1386788, "author_profile": "https://Stackoverflow.com/users/1386788", "pm_score": 4, "selected": false, "text": "composer require symfony/expression-language" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
327,066
<p>I have a custom XML schema defined for page display that puts elements on the page by evaluating XML elements on the page. This is currently implemented using the preg regex functions, primarily the excellent preg_replace_callback function, eg:</p> <pre><code>... $s = preg_replace_callback("!&lt;field&gt;(.*?)&lt;/field&gt;!", replace_field, $s); ... function replace_field($groups) { return isset($fields[$group[1]) ? $fields[$groups[1]] : ""; } </code></pre> <p>Just as an example.</p> <p>Now this works pretty well... so long as the XML elements aren't nested. At this point it gets a whole lot more complicated, like if you have:</p> <pre><code>&lt;field name="outer"&gt; &lt;field name="inner"&gt; ... &lt;/field&gt; &lt;/field&gt; </code></pre> <p>You want to make sure you replace the innermost field first. Judicious use of greedy/non-greedy regex patterns can go some of the way to handling these more complicated scenarios but the clear message is that I'm reaching the limits of what regex can reasonably do and really I need to be doing XML parsing.</p> <p>What I'd like is an XML transformation package that:</p> <p>allows me to conditionally evaluate/include the contained document tree or not based on a callback function ideally (analagous to preg_replace_callback); can handle nested elements of the same or different types; and handles attributes in a nice way (eg as an associative array).</p> <p>What can help me along the way?</p>
[ { "answer_id": 327407, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": true, "text": "XSLTProcessor --with-xsl[=DIR] XSLTProcessor::registerPHPFunctions() $xml = '<allusers>\n <user>\n <uid>bob</uid>\n </user>\n <user>\n <uid>joe</uid>\n </user>\n</allusers>';\n$xsl = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet version=\"1.0\" \n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:php=\"http://php.net/xsl\">\n<xsl:output method=\"html\" encoding=\"utf-8\" indent=\"yes\"/>\n <xsl:template match=\"allusers\">\n <html><body>\n <h2>Users</h2>\n <table>\n <xsl:for-each select=\"user\">\n <tr><td>\n <xsl:value-of\n select=\"php:function(\\'ucfirst\\',string(uid))\"/>\n </td></tr>\n </xsl:for-each>\n </table>\n </body></html>\n </xsl:template>\n</xsl:stylesheet>';\n$xmldoc = DOMDocument::loadXML($xml);\n$xsldoc = DOMDocument::loadXML($xsl);\n\n$proc = new XSLTProcessor();\n$proc->registerPHPFunctions();\n$proc->importStyleSheet($xsldoc);\necho $proc->transformToXML($xmldoc);\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
327,082
<p>When deploying the application to the device, the program will quit after a few cycles with the following error:</p> <pre><code>Program received signal: "EXC_BAD_ACCESS". </code></pre> <p>The program runs without any issue on the iPhone simulator, it will also debug and run as long as I step through the instructions one at a time. As soon as I let it run again, I will hit the <code>EXC_BAD_ACCESS</code> signal.</p> <p>In this particular case, it happened to be an error in the accelerometer code. It would not execute within the simulator, which is why it did not throw any errors. However, it would execute once deployed to the device.</p> <p>Most of the answers to this question deal with the general <code>EXC_BAD_ACCESS</code> error, so I will leave this open as a catch-all for the dreaded Bad Access error.</p> <p><code>EXC_BAD_ACCESS</code> is typically thrown as the result of an illegal memory access. You can find more information in the answers below.</p> <p>Have you encountered the <code>EXC_BAD_ACCESS</code> signal before, and how did you deal with it?</p>
[ { "answer_id": 327147, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 4, "selected": false, "text": "pthread_join() -Wall -Wextra" }, { "answer_id": 328164, "author": "philsquared", "author_id": 32136, "author_profile": "https://Stackoverflow.com/users/32136", "pm_score": 9, "selected": true, "text": "[NSString stringWithFormat]" }, { "answer_id": 330095, "author": "Rob", "author_id": 386102, "author_profile": "https://Stackoverflow.com/users/386102", "pm_score": 3, "selected": false, "text": "netObjectDefinedInMyHeader = [[[MyNetObject alloc] init] autorelease];\n [[MyNetObject alloc] init] myObjectDefinedInHeader = aParameterObjectPassedIn;\n myObjectDefinedInHeader = [aParameterObjectPassedIn retain];\n" }, { "answer_id": 930887, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "startPoint = [[DataPoint alloc] init] ;\nstartPoint= [DataPointList objectAtIndex: 0];\nx = startPoint.x - 10; // EXC_BAD_ACCESS\n startPoint = [[DataPoint alloc] init] ;\nstartPoint = [[DataPointList objectAtIndex: 0] retain];\n EXC_BAD_ACCESS" }, { "answer_id": 1171037, "author": "gnuchu", "author_id": 143613, "author_profile": "https://Stackoverflow.com/users/143613", "pm_score": 3, "selected": false, "text": "NSMutableString *string;\n[string appendWithFormat:@\"foo\"];\n NSMutableString *string = [[NSMutableString alloc] init];\n[string appendWithFormat:@\"foo\"];\n" }, { "answer_id": 1623000, "author": "Scott Heaberlin", "author_id": 195956, "author_profile": "https://Stackoverflow.com/users/195956", "pm_score": 3, "selected": false, "text": "NSLog(@\"Some silly log message %@-%@\");\n NSLog(@\"Some silly log message %@-%@\", someObj1, someObj2);\n" }, { "answer_id": 2377132, "author": "Josh", "author_id": 285997, "author_profile": "https://Stackoverflow.com/users/285997", "pm_score": 2, "selected": false, "text": "dealloc" }, { "answer_id": 2755656, "author": "fool4jesus", "author_id": 269361, "author_profile": "https://Stackoverflow.com/users/269361", "pm_score": 2, "selected": false, "text": "@property (nonatomic, assign) IBOutlet UISegmentedControl *choicesControl;\n@property (nonatomic, assign) IBOutlet UISwitch *africaSwitch;\n@property (nonatomic, assign) IBOutlet UISwitch *asiaSwitch;\n @property (nonatomic, retain) IBOutlet UISegmentedControl *choicesControl;\n@property (nonatomic, retain) IBOutlet UISwitch *africaSwitch;\n@property (nonatomic, retain) IBOutlet UISwitch *asiaSwitch;\n" }, { "answer_id": 12963793, "author": "Artur", "author_id": 406355, "author_profile": "https://Stackoverflow.com/users/406355", "pm_score": 1, "selected": false, "text": "@ C-strings NSStrings EXC_BAD_ACCESS @\"Some String\"\n \"Some String\"\n array" }, { "answer_id": 14449286, "author": "DHShah01", "author_id": 1640754, "author_profile": "https://Stackoverflow.com/users/1640754", "pm_score": 1, "selected": false, "text": "[self performSegueWithIdentifier:sender:] -(void) prepareForSegue:(UIstoryboardSegue *)" }, { "answer_id": 66480113, "author": "Mehrdad", "author_id": 7861886, "author_profile": "https://Stackoverflow.com/users/7861886", "pm_score": 0, "selected": false, "text": " class A: UIView {\n \n let b = B()\n .\n .\n }\n\n\n\n class B: A {\n .\n .\n }\n" }, { "answer_id": 67471254, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 0, "selected": false, "text": "EXC_BAD_ACCESS IPHONEOS_DEPLOYMENT_TARGET Test explicit dependency 14.0" }, { "answer_id": 69756405, "author": "pableiros", "author_id": 3701102, "author_profile": "https://Stackoverflow.com/users/3701102", "pm_score": 0, "selected": false, "text": "* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x1d8)\n frame #0: 0x0000000180f969cc CoreText`CTFontGetClientObject + 12\n...\n * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)\n frame #0: 0x000000012341c10e CoreFoundation`CFRelease.cold.1 + 14\n frame #1: 0x00000001232ed7bd CoreFoundation`CFRelease + 77\n frame #2: 0x0000000128136990 libGSFont.dylib`GSFontGetExtraData + 112\n frame #3: 0x0000000135bc8958 UIFoundation`-[UIFont lineHeight] + 9\n frame #4: 0x00000001340149f3 UIKitCore`-[UILabel intrinsicContentSize] + 331\n...\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19617/" ]
327,093
<p>I'm racking my brain trying to come up with an elegant solution to a DLL load problem. I have an application that statically links to other lib files which load DLLs. I'm not loading the DLLs directly. I'd like to have some DLLs in another folder other than the folder that the executable is in. Something like %working_folder%\dlls - I'd rather not have dozens (yes ... dozens) of DLLs in my %working_folder%. </p> <p>I'm trying to develop something that is part of the main app that will adjust the search path @ startup. The problem I'm running into is that this new custom DLL path isn't in the system search path. When I start the app it crashes (STATUS_DLL_NOT_FOUND) because the necessary DLLs are not in the appropriate places. What I'd like to do is to check @ startup if this new custom DLL folder is in the process environment variable search path and if not add it. Problem is, the application attempts to load all these DLLs before the app executes one line of code. </p> <p>How do I fix this? I've considered writing a help app that starts first, adjusts the environment variables appropriately and the launches the main app via CreateProcess. This will work I'm sure of it but it makes things difficult on the developers. When they debug the main app they're not going to launch a helper app first - not that they could even do that.</p> <p>I've tried the registry app path feature with no success. Same chicken and egg problem as before. </p> <p>What can I do here?</p>
[ { "answer_id": 327118, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "main SetDllDirectory() GetEnvironmentVariable() SetEnvironmentVariable() SetCurrentDirectory()" }, { "answer_id": 22712256, "author": "David Woo", "author_id": 1773790, "author_profile": "https://Stackoverflow.com/users/1773790", "pm_score": 2, "selected": false, "text": "class RunBeforeMain\n{\npublic:\n RunBeforeMain()\n {\n const TCHAR* dllPathEnvName= name of env variable to directory containing dlls\n const TCHAR* pathEnvName= TEXT(\"Path\");\n\n\n TCHAR newSearchPath[4096];\n ::GetEnvironmentVariable(dllPathEnvName, newSearchPath, MAX_PATH);\n\n //append bin\n _tcscat_s(newSearchPath, MAX_PATH, TEXT(\"bin;\"));\n size_t length = _tcslen(newSearchPath);\n\n //append existing Path\n ::GetEnvironmentVariable(pathEnvName, newSearchPath + length, 4096-length);\n ::SetEnvironmentVariable(pathEnvName, newSearchPath);\n\n }\n};\nstatic RunBeforeMain runBeforeMain; //constructor code will run before main.\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
327,097
<p>I'm building a with-source system which I am giving out on the 'net for providing adoptable virtual pets. The system will be owned mainly by kids. Since I want it to be usable for absolute beginner programmers, there are several complexity constraints on my system: It can't use libraries that don't commonly ship with PHP, and it can't touch a database or write to other permanent storage.</p> <p>When each pet is adopted, the visitor will randomly get given one of a series of slightly different variations of that pet. The variations initially look the same, but grow up over time to become different pets. The visitor will be given a short code in HTML which links to the image of their pet. Since there is no permanent storage available server-side, the user's image link must contain all of the information to determine which pet variation they ended up getting.</p> <p>At the moment, the URL just contains the ID of the pet and the ID of the variation that the user got. The problem with this is that, by comparing codes with each other, the users can figure out who amongst them ended up with the same variation. Since some variations are rarer than others, users can spot the rare variations easily before the difference is even visually apparent.</p> <p>What I would like is an encryption system for the details in the URL. Something that obscures the variation ID so that each user gets a different URL with high probability. I thought of using the variation ID (3 or 4 bits) as the low bits or high bits of a large random number, but the users will spot the pattern in this. Ideally the encryption system would be parametrized so that each installation of my system would use a slightly different encryption.</p> <p>PHP's mcrypt library would probably have something useful in it, but it doesn't seem to be very common amongst hosters.</p> <p>Is there a simple, parametrized, obfuscation/encryption I can use here?</p>
[ { "answer_id": 327103, "author": "SoapBox", "author_id": 36384, "author_profile": "https://Stackoverflow.com/users/36384", "pm_score": 5, "selected": true, "text": "petvar = (petvar^rnd)<<16 | rnd;" }, { "answer_id": 327206, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "function ecrypt($str){\n $key = \"abc123 as long as you want bla bla bla\";\n for($i=0; $i<strlen($str); $i++) {\n $char = substr($str, $i, 1);\n $keychar = substr($key, ($i % strlen($key))-1, 1);\n $char = chr(ord($char)+ord($keychar));\n $result.=$char;\n }\n return urlencode(base64_encode($result));\n}\n\n\nfunction decrypt($str){\n $str = base64_decode(urldecode($str));\n $result = '';\n $key = \"must be same key as in encrypt\";\n for($i=0; $i<strlen($str); $i++) {\n $char = substr($str, $i, 1);\n $keychar = substr($key, ($i % strlen($key))-1, 1);\n $char = chr(ord($char)-ord($keychar));\n $result.=$char;\n }\nreturn $result;\n}\n $arr = array(\n 'pet_name'=>\"fido\",\n 'favorite_food'=>\"cat poop\",\n 'unique_id'=>3848908043\n);\n$param_string = encrypt(serialize($arr));\n\n$link = \"/load_pet.php?params=$param_string\";\n $param_string = $_GET[\"params\"];\n$params = unserialize(decrypt($param_string));\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14431/" ]
327,100
<p>I have been attempting to create a new directory for my apache server. As I tried to access the new directory, I type:</p> <p>sudo /etc/init.d/apache2 restart</p> <p>But I obtain this error in the Ubuntu Terminal:</p> <p>Syntax Error on line 1 of /etc/apache2/conf.d/fqdn.save: ServerName takes one argument, the Hostname and port of the server.</p> <p>As I investigate, the fqdn.save file could not be accessed and is considered unknown. I want to delete this file, but I'm unable to as I believe I need root access. </p> <p>Does anyone know how to delete this unwanted file in Ubuntu? Or does anyone know how to redirect the apache2 restart to /etc/apache2/conf.d/fqdn (instead of fqdn.save) when I type "sudo /etc/init.d/apache restart" on the terminal</p> <p>please and thank you</p>
[ { "answer_id": 327126, "author": "genehack", "author_id": 39933, "author_profile": "https://Stackoverflow.com/users/39933", "pm_score": 2, "selected": false, "text": "sudo cat /etc/apache2/conf.d/fqdn.save\n sudo cp /etc/apache2/conf.d/fqdn.save /tmp\n sudo rm /etc/apache/conf.d/fqdn.save\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
327,122
<p>Using Morph Labs' Appspace to deploy a site means no automated way to redirect 'myapp.com' to 'www.myapp.com' (and no access to .htacess).</p> <p>Is there an in-rails way to do this? Would I need a plugin like <a href="http://github.com/mbleigh/subdomain-fu/tree/master" rel="nofollow noreferrer">subdomain-fu</a>?</p> <p>More specifically, I'm trying to do something like:</p> <ul> <li>'myapp.com' => 'www.myapp.com'</li> <li>'myapp.com/session/new' => 'www.myapp.com/session/new'</li> </ul> <p>Basically, I always want the 'www' subdomain prepended on every request (because the SSL cert specifically has a common name of 'www.myapp.com').</p>
[ { "answer_id": 327127, "author": "Stepan Mazurov", "author_id": 40786, "author_profile": "https://Stackoverflow.com/users/40786", "pm_score": 0, "selected": false, "text": " head :moved_permanently, :location => ‘http://www.newdomain.com’\n def rails_301\nheaders[\"Status\"] = \"301 Moved Permanently\"\nredirect_to \"http://www.newdomain.com\"\nend \n" }, { "answer_id": 327154, "author": "carson", "author_id": 25343, "author_profile": "https://Stackoverflow.com/users/25343", "pm_score": 6, "selected": true, "text": "class ApplicationController < ActionController::Base\n before_filter :check_uri\n\n def check_uri\n redirect_to request.protocol + \"www.\" + request.host_with_port + request.request_uri if !/^www/.match(request.host)\n end\nend\n" }, { "answer_id": 1729714, "author": "Mike H", "author_id": 98610, "author_profile": "https://Stackoverflow.com/users/98610", "pm_score": 3, "selected": false, "text": "before_filter :check_uri\n\ndef check_uri\n if /^www/.match(request.host)\n redirect_to request.protocol + request.host_with_port[4..-1] + request.request_uri \n end\nend\n" }, { "answer_id": 3129435, "author": "Levi Rosol", "author_id": 23458, "author_profile": "https://Stackoverflow.com/users/23458", "pm_score": 2, "selected": false, "text": "def check_uri\n redirect_to request.protocol + \"www.\" + request.host_with_port + request.request_uri if !/^www/.match(request.host) if Rails.env == 'production'\nend\n" }, { "answer_id": 9522315, "author": "Lee McAlilly", "author_id": 168286, "author_profile": "https://Stackoverflow.com/users/168286", "pm_score": 3, "selected": false, "text": "class ApplicationController < ActionController::Base\n protect_from_forgery\n\n Rails.env.production? do\n before_filter :check_url\n end\n\n def check_url\n redirect_to request.protocol + \"www.\" + request.host_with_port + request.fullpath if !/^www/.match(request.host)\n end\nend\n" }, { "answer_id": 19395978, "author": "Rodrigo Garcia Najera", "author_id": 2856304, "author_profile": "https://Stackoverflow.com/users/2856304", "pm_score": 0, "selected": false, "text": "URL foo.com 3600 http://www.foo.com\n CNAME www.foo.com 3600 providedssslendpoint.herokussl.com\n ALIAS foo.com 3600 providedsslendpoint.herokussl.com\n ENV['SITE_HOST'] before_filter :check_domain\n\n def check_domain\n if Rails.env.production? || Rails.env.testing? and request.host.downcase != ENV['SITE_HOST']\n redirect_to request.protocol + ENV['SITE_HOST'] + request.fullpath, :status => 301\n end\n end\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19527/" ]
327,151
<p>I have an ASP.NET page that uses a repeater nested within another repeater to generate a listing of data. It's to the effect of the following:</p> <pre><code>&lt;asp:Repeater&gt; &lt;ItemTemplate&gt; &lt;span&gt;&lt;%#Eval("Data1") %&gt;&lt;/span&gt; &lt;!-- and many more --&gt; &lt;asp:Repeater DataSource='&lt;%#Eval("Data2")%&gt;'&gt; &lt;HeaderTemplate&gt; &lt;ul&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;li&gt;&lt;%#Container.DataItem%&gt;&lt;/li&gt; &lt;/ItemTemplate&gt; &lt;FooterTemplate&gt; &lt;/ul&gt; &lt;/FooterTemplate&gt; &lt;/asp:Repeater&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <p>In the (C#) code-behind I'm basically using LINQ to pull a listing of information from an XML document and bind that information to the first repeater.</p> <p>Searching for the answer to this, it seems the method is to determine whether the data for the nested repeater is empty. If it is, then you set the visibility of the repeater to false.</p> <p>Unfortunately, I haven't been able to determine how to do that inline, and not in the code-behind (since it won't necessarily work for what I'm doing).</p> <p>Since my pages aren't validating now, because the ul ends up being empty for any items without Data2, and because I'd like to keep using an unordered list, I seek your help.</p> <p>Any ideas?</p> <p>Thanks!</p> <p>UPDATE:</p> <p>If it helps, since it could very well be possible to do in the code-behind, the LINQ is something to this effect:</p> <pre><code>var x = from y in z select new { Data1 = d, // etcetera Data2 = (from j in k where j.Value != String.Empty select j.Value).ToList() }; blah.DataSource = x; blah.DataBind(); </code></pre>
[ { "answer_id": 327362, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 2, "selected": false, "text": "<asp:Repeater runat=\"server\" DataSource='<%#Eval(\"Data2\")%>' \n Visible='<%# ((IEnumerable)Eval(\"Data2\")).GetEnumerator().MoveNext() %>'>\n" }, { "answer_id": 328520, "author": "JoshBerke", "author_id": 26160, "author_profile": "https://Stackoverflow.com/users/26160", "pm_score": 0, "selected": false, "text": "void rep1_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n\n Repeater rep2 = (Repeater)e.Item.FindControl(\"rep2\");\n rep2.DataSource = ((dto)e.Item.DataItem).y;\n rep2.DataBind();\n}\n" }, { "answer_id": 329895, "author": "Matt Peterson", "author_id": 19036, "author_profile": "https://Stackoverflow.com/users/19036", "pm_score": 4, "selected": true, "text": "using System;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\n\npublic class EmptyCapableRepeater : Repeater\n{\n public ITemplate EmptyDataTemplate { get; set; }\n\n protected override void OnDataBinding ( EventArgs e )\n {\n base.OnDataBinding( e );\n\n if ( this.Items.Count == 0 )\n {\n EmptyDataTemplate.InstantiateIn( this );\n }\n }\n}\n <custom:EmptyCapableRepeater runat=\"server\" ID=\"rptSearchResults\">\n <ItemTemplate>\n <%# Eval( \"Result\" )%>\n </ItemTemplate>\n <SeparatorTemplate>\n <br />\n </SeparatorTemplate>\n <EmptyDataTemplate>\n <em>No results were found.</em>\n </EmptyDataTemplate>\n</custom:EmptyCapableRepeater>\n" }, { "answer_id": 2029755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<FooterTemplate> \n <li style=\"display:none;\">This will not show.</li></ul> \n</FooterTemplate> \n <FooterTemplate> \n <tr> style=\"display:none;\"><td>But something must be in here.</td></tr></table> \n</FooterTemplate> \n" }, { "answer_id": 2875583, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 0, "selected": false, "text": "OnItemDataBound ItemType Header ItemType Item" }, { "answer_id": 16524013, "author": "Moslem Hadi", "author_id": 709340, "author_profile": "https://Stackoverflow.com/users/709340", "pm_score": 1, "selected": false, "text": "protected void Repeater1_PreRender(object sender, EventArgs e)\n{\n if (Repeater1.Items.Count < 1)\n {\n container.Visible = false;\n }\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11912/" ]
327,162
<p>I have been trying to encrypt soap message and send to the server, so that the server can decrypt, process the message, encrypt the response again and send back to the client...</p> <p>I short i want to implement security in ASMX web services....</p> <p>Please help me</p> <p>Thanks Sandeep</p>
[ { "answer_id": 327167, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": true, "text": "[WebMethod]\npublic string SecureMethodX(string secureInput)\n{\n string plainText = decrypt(secureInput);\n //do something...\n string encryptedResult = encrypt(someResult);\n return encryptedResult;\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41740/" ]
327,191
<p>The list <code>sort()</code> method is a modifier function that returns <code>None</code>.</p> <p>So if I want to iterate through all of the keys in a dictionary I cannot do:</p> <pre><code>for k in somedictionary.keys().sort(): dosomething() </code></pre> <p>Instead, I must:</p> <pre><code>keys = somedictionary.keys() keys.sort() for k in keys: dosomething() </code></pre> <p>Is there a pretty way to iterate through these keys in sorted order without having to break it up in to multiple steps?</p>
[ { "answer_id": 327210, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 5, "selected": true, "text": "for k in sorted(somedictionary.keys()):\n doSomething(k)\n for k, v in sorted(somedictionary.iteritems()):\n doSomething(k, v)\n" }, { "answer_id": 856272, "author": "odwl", "author_id": 2453648, "author_profile": "https://Stackoverflow.com/users/2453648", "pm_score": 3, "selected": false, "text": "for k in sorted(somedictionary):\n doSomething(k)\n [doSomethinc(k) for k in sorted(somedict)]\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31060/" ]
327,216
<p><a href="http://thedailywtf.com/Articles/nice_num,-mean_programmer.aspx" rel="nofollow noreferrer">The Daily WTF</a> for 2008-11-28 pillories the following code:</p> <pre><code>static char *nice_num(long n) { int neg = 0, d = 3; char *buffer = prtbuf; int bufsize = 20; if (n &lt; 0) { neg = 1; n = -n; } buffer += bufsize; *--buffer = '\0'; do { *--buffer = '0' + (n % 10); n /= 10; if (--d == 0) { d = 3; *--buffer = ','; } } while (n); if (*buffer == ',') ++buffer; if (neg) *--buffer = '-'; return buffer; } </code></pre> <p>How would you write it?</p>
[ { "answer_id": 327240, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "static int nice_num(char *buffer, size_t len, int32_t n)\n{\n int neg = 0, d = 3;\n char buf[16];\n size_t bufsize = sizeof(buf);\n char *pbuf = buf + bufsize;\n\n if(n < 0)\n {\n if(n == INT32_MIN)\n {\n strncpy(buffer, \"-2,147,483,648\", len);\n return len <= 14;\n }\n\n neg = 1;\n n = -n;\n }\n\n *--pbuf = '\\0';\n\n do\n {\n *--pbuf = '0' + (n % 10);\n n /= 10;\n if(--d == 0)\n {\n d = 3;\n *--pbuf = ',';\n }\n }\n while(n > 0);\n\n if(*pbuf == ',') ++pbuf;\n if(neg) *--pbuf = '-';\n\n strncpy(buffer, pbuf, len);\n return len <= strlen(pbuf);\n}\n" }, { "answer_id": 327241, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n#include <limits.h>\n\nstatic char *prettyNumber(long num, int base, char separator)\n{\n#define bufferSize (sizeof(long) * CHAR_BIT)\n static char buffer[bufferSize + 1];\n unsigned int pos = 0;\n\n /* We're walking backwards because numbers are right to left. */\n char *p = buffer + bufferSize;\n *p = '\\0';\n\n int negative = num < 0;\n\n do\n {\n char digit = num % base;\n digit += '0';\n\n *(--p) = digit;\n ++pos;\n\n num /= base;\n\n /* This the last of a digit group? */\n if(pos % 3 == 0)\n {\n/* TODO Make this a user setting. */\n#ifndef IM_AMERICAN\n# define IM_AMERICAN_BOOL 0\n#else\n# define IM_AMERICAN_BOOL 1\n#endif\n /* Handle special thousands case. */\n if(!IM_AMERICAN_BOOL && pos == 3 && num < base)\n {\n /* DO NOTHING */\n }\n else\n {\n *(--p) = separator;\n }\n }\n } while(num);\n\n if(negative)\n *(--p) = '-';\n\n return p;\n#undef bufferSize\n}\n\nint main(int argc, char **argv)\n{\n while(argc > 1)\n {\n long num = 0;\n\n if(sscanf(argv[1], \"%ld\", &num) != 1)\n continue;\n\n printf(\"%ld = %s\\n\", num, prettyNumber(num, 10, ' '));\n\n --argc;\n ++argv;\n };\n\n return 0;\n}\n" }, { "answer_id": 327243, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 1, "selected": false, "text": "localeconv" }, { "answer_id": 327244, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "snprintf() printf() printf()" }, { "answer_id": 327245, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 1, "selected": false, "text": "(defun pretty-number (x) (format t \"~:D\" x))\n" }, { "answer_id": 327392, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "\nsub pretify {\n my $num = $_[0];\n my $numstring = sprintf( \"%f\", $num );\n\n # Split into whole/decimal\n my ( $whole, $decimal ) = ( $numstring =~ /(^\\d*)(.\\d+)?/ );\n my @chunks;\n my $output = '';\n\n # Pad whole into multiples of 3\n $whole = q{ } x ( 3 - ( length $whole ) % 3 ) . $whole;\n\n # Create an array of all 3 parts.\n @chunks = $whole =~ /(.{3})/g;\n\n # Reassemble with commas\n $output = join ',', @chunks;\n if ($decimal) {\n $output .= $decimal;\n }\n\n # Strip Padding ( and spurious commas )\n $output =~ s/^[ ,]+//;\n\n # Strip excess tailing zeros\n $output =~ s/0+$//;\n\n # Ending with . is ugly\n $output =~ s/\\.$//;\n return $output;\n}\n\nprint \"\\n\", pretify 100000000000000000000000000.0000;\nprint \"\\n\", pretify 10_202_030.45;\nprint \"\\n\", pretify 10_101;\nprint \"\\n\", pretify 0;\nprint \"\\n\", pretify 0.1;\nprint \"\\n\", pretify 0.0001;\nprint \"\\n\";\n" }, { "answer_id": 1352659, "author": "Adrian Panasiuk", "author_id": 111160, "author_profile": "https://Stackoverflow.com/users/111160", "pm_score": 1, "selected": false, "text": "size_t\nsigned_as_text_grouped_on_powers_of_1000(char *s, ssize_t max, int n)\n{\n if (max <= 0)\n return 0;\n\n size_t r=0;\n bool more_groups = n/1000 != 0;\n if (more_groups)\n {\n r = signed_as_text_grouped_on_powers_of_1000(s, max, n/1000);\n r += snprintf(s+r, max-r, \",\");\n n = abs(n%1000);\n r += snprintf(s+r, max-r, \"%03d\",n);\n } else\n r += snprintf(s+r, max-r, \"% 3d\", n);\n\n return r;\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15168/" ]
327,223
<p>In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, <code>topDict[word1][word2][word3]</code> returns the number of times these words appear in the text, <code>topDict[word1][word2]</code> returns a dictionary with all the words that appeared following words 1 and 2, etc.</p> <p>This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead.</p> <p>My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries.</p> <p>From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best.</p> <p>So, does anyone have any suggestions for me?</p> <p>Edited to add:</p> <p>Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (i.e. I want something like the result of <code>topDict[word1, word2].keys()</code>). </p> <p>The current dataset I am playing around with is the most recent version of <a href="http://www.soschildrensvillages.org.uk/charity-news/wikipedia-for-schools.htm" rel="noreferrer">Wikipedia For Schools</a>. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive.</p>
[ { "answer_id": 327254, "author": "user39307", "author_id": 39307, "author_profile": "https://Stackoverflow.com/users/39307", "pm_score": 1, "selected": false, "text": "topDictionary[word1+delimiter+word2+delimiter+word3]\n" }, { "answer_id": 327285, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 2, "selected": false, "text": "from __future__ import with_statement\n\nimport time\nfrom collections import deque, defaultdict\n\n# Just used to generate some triples of words\ndef triplegen(words=\"/usr/share/dict/words\"):\n d=deque()\n with open(words) as f:\n for i in range(3):\n d.append(f.readline().strip())\n\n while d[-1] != '':\n yield tuple(d)\n d.popleft()\n d.append(f.readline().strip())\n\nif __name__ == '__main__':\n class D(dict):\n def __missing__(self, key):\n self[key] = D()\n return self[key]\n h=D()\n for a, b, c in triplegen():\n h[a][b][c] = 1\n time.sleep(60)\n h[a, b, c] = 1\n" }, { "answer_id": 327295, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 6, "selected": true, "text": "295760 S. Lott's answer\n237984 S. Lott's with keys interned before passing in\n203172 [*] d[(a,b,c)] = int(freq)\n203156 d[a][b][c] = int(freq)\n189132 keys.append((a,b,c)); freqs.append(int(freq))\n146132 d[intern(a),intern(b)][intern(c)] = int(freq)\n145408 d[intern(a)][intern(b)][intern(c)] = int(freq)\n 83888 [*] d[a+' '+b+' '+c] = int(freq)\n 82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq)\n 68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq))\n 60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq))\n 50556 pair array\n 48320 squeezed pair array\n 33024 squeezed single array\n import collections\n\ndef build(file):\n pairs = collections.defaultdict(list)\n for line in file: # N.B. file assumed to be already sorted\n a, b, c, freq = line.split()\n key = ' '.join((a, b))\n pairs[key].append(c + ':' + freq if freq != '1' else c)\n out = open('squeezedsinglearrayfile', 'w')\n for key in sorted(pairs.keys()):\n out.write('%s|%s\\n' % (key, ' '.join(pairs[key])))\n\ndef load():\n return open('squeezedsinglearrayfile').readlines()\n\nif __name__ == '__main__':\n build(open('freqs'))\n" }, { "answer_id": 327299, "author": "user39307", "author_id": 39307, "author_profile": "https://Stackoverflow.com/users/39307", "pm_score": -1, "selected": false, "text": "Word1=indexDict[word1]\nWord2=indexDict[word2]\nWord3=indexDict[word3]\n\ntopDictionary[Word1][Word2][Word3]\n if word not in indexDict:\n indexDict[word]=len(indexDict)\n" }, { "answer_id": 327313, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 3, "selected": false, "text": "d = {}\nd[ word1, word2, word3 ] = 1\n d[w1,w2,w3] += 1 from collections import defaultdict\nd = defaultdict(int)\nd[\"first\",\"word\",\"tuple\"] += 1\n >>> a = (1,2,3)\n>>> a[:2]\n(1, 2)\n >>> b = [(1,2,3),(1,2,5),(3,4,6)]\n>>> search = (1,2)\n>>> [a[2] for a in b if a[:2] == search]\n[3, 5]\n" }, { "answer_id": 327464, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "from BTrees.OOBTree import OOBTree as BTree\n .keys .items .iterkeys .iteritems min, max >>> t=BTree()\n>>> t['a', 'b', 'c']= 10\n>>> t['a', 'b', 'z']= 11\n>>> t['a', 'a', 'z']= 12\n>>> t['a', 'd', 'z']= 13\n>>> print list(t.keys(('a', 'b'), ('a', 'c')))\n[('a', 'b', 'c'), ('a', 'b', 'z')]\n" }, { "answer_id": 327479, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 2, "selected": false, "text": "random.choice import random\n\n# can change these functions to use a dict-based histogram\n# instead of a list with repeats\ndef default_histogram(): return []\ndef add_to_histogram(item, hist): hist.append(item)\ndef choose_from_histogram(hist): return random.choice(hist)\n\nK=2 # look 2 words back\nwords = ...\nd = {}\n\n# build histograms\nfor i in xrange(len(words)-K-1):\n key = words[i:i+K]\n word = words[i+K]\n\n d.setdefault(key, default_histogram())\n add_to_histogram(word, d[key])\n\n# generate text\nstart = random.randrange(len(words)-K-1)\nkey = words[start:start+K]\nfor i in NUM_WORDS_TO_GENERATE:\n word = choose_from_histogram(d[key])\n print word,\n key = key[1:] + (word,)\n" }, { "answer_id": 327697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "import numpy\nw = {'word1':1, 'word2':2, 'word3':3, 'word4':4}\na = numpy.zeros( (4,4,4) )\n a[w[word1], w[word2], w[word3]] += 1\n" }, { "answer_id": 327924, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "import bisect\n\nclass WordList( object ):\n \"\"\"Leaf-level is list of words and counts.\"\"\"\n def __init__( self ):\n self.words= [ ('\\xff-None-',0) ]\n def count( self, wordTuple ):\n assert len(wordTuple)==1\n word= wordTuple[0]\n loc= bisect.bisect_left( self.words, word )\n if self.words[loc][0] != word:\n self.words.insert( loc, (word,0) ) \n self.words[loc]= ( word, self.words[loc][1]+1 )\n def getWords( self ):\n return self.words[:-1]\n\nclass WordTree( object ):\n \"\"\"Above non-leaf nodes are words and either trees or lists.\"\"\"\n def __init__( self ):\n self.words= [ ('\\xff-None-',None) ]\n def count( self, wordTuple ):\n head, tail = wordTuple[0], wordTuple[1:]\n loc= bisect.bisect_left( self.words, head )\n if self.words[loc][0] != head:\n if len(tail) == 1:\n newList= WordList()\n else:\n newList= WordTree()\n self.words.insert( loc, (head,newList) )\n self.words[loc][1].count( tail )\n def getWords( self ):\n return self.words[:-1]\n\nt = WordTree()\nfor a in ( ('the','quick','brown'), ('the','quick','fox') ):\n t.count(a)\n\nfor w1,wt1 in t.getWords():\n print w1\n for w2,wt2 in wt1.getWords():\n print \" \", w2\n for w3 in wt2.getWords():\n print \" \", w3\n" }, { "answer_id": 331384, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import numpy as N\nfrom scipy import sparse\n\nword_index = {}\ncount = sparse.lil_matrix((word_count*word_count, word_count), dtype=N.int)\n\nfor word1, word2, word3 in triple_list:\n w1 = word_index.setdefault(word1, len(word_index))\n w2 = word_index.setdefault(word2, len(word_index))\n w3 = word_index.setdefault(word3, len(word_index))\n w1_w2 = w1 * word_count + w2\n count[w1_w2,w3] += 1\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ]
327,231
<p>i am trying to find the best way to display results on my page via an Ajax call using jQuery, do you think the best way is to pass it as JSON or plain text? I have worked with ajax calls before, but not sure which is preferred over the other and for the JSON version what is the best way to read from a JSON file generated by a PHP page to display my results.</p> <p>i know I would include a <code>.each</code> to run through it to display them all.</p>
[ { "answer_id": 327282, "author": "strager", "author_id": 39992, "author_profile": "https://Stackoverflow.com/users/39992", "pm_score": 2, "selected": false, "text": "$.getJSON(url, data, function(json) {\n $(json).each(function() {\n /* YOUR CODE HERE */\n });\n});\n" }, { "answer_id": 327640, "author": "Jay", "author_id": 41690, "author_profile": "https://Stackoverflow.com/users/41690", "pm_score": 6, "selected": true, "text": "$.getJSON(\"http://mywebsite.com/json/get.php?cid=15\",\n function(data){\n $.each(data.products, function(i,product){\n content = '<p>' + product.product_title + '</p>';\n content += '<p>' + product.product_short_description + '</p>';\n content += '<img src=\"' + product.product_thumbnail_src + '\"/>';\n content += '<br/>';\n $(content).appendTo(\"#product_list\");\n });\n });\n Array('products' => Array(0 => Array('product_title' => 'Product 1',\n 'product_short_description' => 'Product 1 is a useful product',\n 'product_thumbnail_src' => '/images/15/1.jpg'\n )\n 1 => Array('product_title' => 'Product 2',\n 'product_short_description' => 'Product 2 is a not so useful product',\n 'product_thumbnail_src' => '/images/15/2.jpg'\n )\n )\n )\n $(\"#product_list\").empty();\n" }, { "answer_id": 327659, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>\n<link rel=\"stylesheet\" href=\"../css/screen.css\" type=\"text/css\" media=\"screen, projection\" />\n<link rel=\"stylesheet\" href=\"../css/print.css\" type=\"text/css\" media=\"print\" />\n<!--[if IE]><link rel=\"stylesheet\" href=\"../css/ie.css\" type=\"text/css\" media=\"screen, projection\"><![endif]-->\n<link href=\"../css/highlight.css\" rel=\"stylesheet\" type=\"text/css\" media=\"screen\" />\n<script src=\"js/jquery.js\" type=\"text/javascript\" charset=\"utf-8\"></script>\n<script type=\"text/javascript\">\n/* <![CDATA[ */\n$(document).ready(function(){\n $.getJSON(\"readJSON.php\",function(data){\n $.each(data.post, function(i,post){\n content += '<p>' + post.post_author + '</p>';\n content += '<p>' + post.post_content + '</p>';\n content += '<p' + post.date + '</p>';\n content += '<br/>';\n $(content).appendTo(\"#posts\");\n });\n }); \n});\n/* ]]> */\n</script>\n</head>\n<body>\n <div class=\"container\">\n <div class=\"span-24\">\n <h2>Check out the following posts:</h2>\n <div id=\"posts\">\n </di>\n </div>\n </div>\n</body>\n</html>\n { posts: [{\"id\":\"1\",\"date_added\":\"0001-02-22 00:00:00\",\"post_content\":\"This is a post\",\"author\":\"Ryan Coughlin\"}]}\n object is undefined\nhttp://localhost:8888/rks/post/js/jquery.js\nLine 19\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
327,249
<p>I'm thinking of asking my students to use git for pair programming. Because student work has to be secret, a public repo is out of the question. Instead, each student will have a private repo they maintain themselves, and they will need to exchange patches using git-format-patch. I've read the man page but I'm a little unclear <em>which</em> patches will be sent. The obvious thing for the students would be <strong>send all patches since the last send</strong> or (if git doesn't mind receiving the same patches redundantly) <strong>send all patches since the dawn of time</strong>. (Remember these are student projects, they last for a couple of weeks and are small, and <strong>performance is not a criterion</strong>.) Our best friend is <strong>simplicity</strong> and we are fond of brute force as well.</p> <p>Can anyone give me a short series of examples that show two people, each with a private git repo, exchanging patches using git-format-patch and git-am? Or alternatively point me to existing git documentation and/or tutorial?</p>
[ { "answer_id": 327258, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 5, "selected": true, "text": "tar cvf - mytree | gzip -9vc > /tmp/mytree.tgz\n# mail /tmp/mytree.tgz\ngit tag last-send\n# hack, commit, hack, commit\ngit format-patch -M -C last-send..\n# mail 00* && rm 00*\ngit tag -f last-send\n git tag # get patches from mail and place in /tmp\ngit am /tmp/00*\nrm /tmp/00*\n" }, { "answer_id": 35025845, "author": "Sukima", "author_id": 227176, "author_profile": "https://Stackoverflow.com/users/227176", "pm_score": 0, "selected": false, "text": "git bundle git format-patch" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41661/" ]
327,251
<p>The documentation of the Python <a href="http://www.python.org/doc/2.5.2/lib/module-readline.html" rel="noreferrer"><code>readline</code></a> module says "Availability: Unix". However, it doesn't appear to be available on OS X, although other modules marked as Unix are available. Here is what I'm using:</p> <pre> $ uname -a Darwin greg.local 8.11.1 Darwin Kernel Version 8.11.1: Wed Oct 10 18:23:28 PDT 2007; root:xnu-792.25.20~1/RELEASE_I386 i386 i386 $ which python /usr/bin/python $ python Python 2.3.5 (#1, Nov 26 2007, 09:16:55) [GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import readline Traceback (most recent call last): File "", line 1, in ? ImportError: No module named readline >>> </pre> <p>I have also installed Python 2.5 through MacPorts but <code>readline</code> is not available there either.</p> <p>What can I do to provide <code>readline</code> functionality for Python's <code>raw_input()</code> function on OS X?</p>
[ { "answer_id": 327292, "author": "tegbains", "author_id": 19419, "author_profile": "https://Stackoverflow.com/users/19419", "pm_score": 4, "selected": true, "text": "py-readline py25-readline /opt/local" }, { "answer_id": 1114882, "author": "Telemachus", "author_id": 26702, "author_profile": "https://Stackoverflow.com/users/26702", "pm_score": 2, "selected": false, "text": "man python luga ~ $ python \nPython 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) \n[GCC 4.0.1 (Apple Inc. build 5465)] on darwin\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import rlcompleter\n>>> import readline\n>>>\n" }, { "answer_id": 38943793, "author": "Sairam", "author_id": 208928, "author_profile": "https://Stackoverflow.com/users/208928", "pm_score": 3, "selected": false, "text": "rlwrap brew install rlwrap rlwrap python" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
327,274
<p>How would you write a prepared MySQL statement in PHP that takes a differing number of arguments each time? An example such query is:</p> <pre class="lang-sql prettyprint-override"><code>SELECT `age`, `name` FROM `people` WHERE id IN (12, 45, 65, 33) </code></pre> <p>The <code>IN</code> clause will have a different number of <code>id</code>s each time it is run.</p> <p>I have two possible solutions in my mind but want to see if there is a better way.</p> <p><strong>Possible Solution 1</strong> Make the statement accept 100 variables and fill the rest with dummy values guaranteed not to be in the table; make multiple calls for more than 100 values.</p> <p><strong>Possible Solution 2</strong> Don't use a prepared statement; build and run the query checking stringently for possible injection attacks.</p>
[ { "answer_id": 327384, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 6, "selected": true, "text": "$dbh=new PDO($dbConnect, $dbUser, $dbPass);\n$parms=array(12, 45, 65, 33);\n$parmcount=count($parms); // = 4\n$inclause=implode(',',array_fill(0,$parmcount,'?')); // = ?,?,?,?\n$sql='SELECT age, name FROM people WHERE id IN (%s)';\n$preparesql=sprintf($sql,$inclause); // = example statement used in the question\n$st=$dbh->prepare($preparesql);\n$st->execute($parms);\n $dbh=new PDO($dbConnect, $dbUser, $dbPass);\n$parms=array(12, 45, 65, 33);\n$st=$dbh->prepare(sprintf('SELECT age, name FROM people WHERE id IN (%s)',\n implode(',',array_fill(0,count($parms),'?'))));\n$st->execute($parms);\n" }, { "answer_id": 327390, "author": "Eimantas", "author_id": 41761, "author_profile": "https://Stackoverflow.com/users/41761", "pm_score": 2, "selected": false, "text": "$sql = \"... WHERE id IN (?)\";\n$values = array(1, 2, 3, 4);\n$result = $dbw -> prepare ($sql, $values) -> execute ();\n" }, { "answer_id": 327395, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 1, "selected": false, "text": "IN function convertToInt(&$value, $key)\n{\n $value = intval($value);\n}\n\n$ids = array('12', '45', '65', '33');\narray_walk($ids, 'convertToInt');\n$sql = 'SELECT age, name FROM people WHERE id IN (' . implode(', ', $ids) . ')';\n// $sql will contain SELECT age, name FROM people WHERE id IN (12, 45, 65, 33)\n" }, { "answer_id": 455751, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<?php $NumofIds = 2; //this is the number of ids I got from the last query\n $parameters=implode(',',array_fill(0,$NumofIds,'?')); \n // = ?,? the same number of ?'s as ids we are looking for<br />\n $paramtype=implode('',array_fill(0,$NumofIds,'i')); // = ii<br/>\n //make the array to build the bind_param function<br/>\n $idAr[] = $paramtype; //'ii' or how ever many ?'s we have<br/>\n while($statement->fetch()){ //this is my last query i am getting the id out of<br/>\n $idAr[] = $id; \n }\n\n //now this array looks like this array:<br/>\n //$idAr = array('ii', 128, 237);\n\n $query = \"SELECT id,studentid,book_title,date FROM contracts WHERE studentid IN ($parameters)\";\n $statement = $db->prepare($query);\n //build the bind_param function\n call_user_func_array (array($statement, \"bind_param\"), $idAr);\n //here is what we used to do before making it dynamic\n //statement->bind_param($paramtype,$v1,$v2);\n $statement->execute();\n?>\n" }, { "answer_id": 10967684, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 3, "selected": false, "text": "FIND_IN_SET SELECT age, name FROM people WHERE FIND_IN_SET(id, '12,45,65,33')\n" }, { "answer_id": 21183709, "author": "user3065191", "author_id": 3065191, "author_profile": "https://Stackoverflow.com/users/3065191", "pm_score": 0, "selected": false, "text": "$params = array()\n$all_ids = $this->get_all_ids();\n\nfor($i = 0; $i <= sizeof($all_ids) - 1; $i++){\n array_push($params, $all_ids[$i]['id']);\n}\n\n$clause = implode(',', array_fill(0, count($params), '?')); // output ?, ?, ?\n$total_i = implode('', array_fill(0, count($params), 'i')); // output iiii\n\n$types = \"ss\" . $total_i; // will reproduce : ssiiii ..etc\n\n// %% it's necessary because of sprintf function\n$query = $db->prepare(sprintf(\"SELECT * \n FROM clients \n WHERE name LIKE CONCAT('%%', ?, '%%') \n AND IFNULL(description, '') LIKE CONCAT('%%', ?, '%%')\n AND id IN (%s)\", $clause));\n\n$thearray = array($name, $description);\n$merge = array_merge($thearray, $params); // output: \"John\", \"Cool guy!\", 1, 2, 3, 4\n\n// We need to pass variables instead of values by reference\n// So we need a function to that\ncall_user_func_array('mysqli_stmt_bind_param', array_merge (array($query, $types), $this->makeValuesReferenced($merge))); \n public function makeValuesReferenced($arr){\n $refs = array();\n foreach($arr as $key => $value)\n $refs[$key] = &$arr[$key];\n return $refs;\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41757/" ]
327,286
<p>I have a huge dictionary of blank values in a variable called current like so:</p> <pre><code>struct movieuser {blah blah blah} Dictionary&lt;movieuser, float&gt; questions = new Dictionary&lt;movieuser, float&gt;(); </code></pre> <p>So I am looping through this dictionary and need to fill in the "answers", like so:</p> <pre><code>for(var k = questions.Keys.GetEnumerator();k.MoveNext(); ) { questions[k.Current] = retrieveGuess(k.Current.userID, k.Current.movieID); } </code></pre> <p>Now, this doesn't work, because I get an InvalidOperationException from trying to modify the dictionary I am looping through. However, you can see that the code should work fine - since I am not adding or deleting any values, just modifying the value. I understand, however, why it is afraid of my attempting this.</p> <p>What is the preferred way of doing this? I can't figure out a way to loop through a dictionary WITHOUT using iterators.</p> <p>I don't really want to create a copy of the whole array, since it is a lot of data and will eat up my ram like its still Thanksgiving.</p> <p>Thanks, Dave</p>
[ { "answer_id": 327291, "author": "Matt Campbell", "author_id": 41110, "author_profile": "https://Stackoverflow.com/users/41110", "pm_score": 2, "selected": false, "text": "foreach(var key in someListOfKeys)\n{\n questions.Add(key, retrieveGuess(key.userID, key.movieID);\n}\n" }, { "answer_id": 327312, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "MovieUser IEnumerable<MovieUser> users = RetrieveUsers();\n\nIDictionary<MovieUser, float> questions = new Dictionary<MovieUser, float>();\nforeach (MovieUser user in users)\n{\n questions[user] = RetrieveGuess(user);\n}\n IDictionary<MovieUser, float> questions = \n RetrieveUsers.ToDictionary(user => user, user => RetrieveGuess(user));\n RetrieveUsers() Dispose IEnumerator<T> GetEnumerator foreach MovieUser" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2504/" ]
327,310
<p>In Visual c# Express Edition, is it possible to make some (but not all) items in a ListBox bold? I can't find any sort of option for this in the API.</p>
[ { "answer_id": 327320, "author": "Mindaugas Mozūras", "author_id": 26408, "author_profile": "https://Stackoverflow.com/users/26408", "pm_score": 6, "selected": true, "text": " public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n\n ListBox1.Items.AddRange(new Object[] { \"First Item\", \"Second Item\"});\n ListBox1.DrawMode = DrawMode.OwnerDrawFixed;\n }\n\n private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)\n {\n e.DrawBackground();\n e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font(\"Arial\", 10, FontStyle.Bold), Brushes.Black, e.Bounds);\n e.DrawFocusRectangle();\n }\n }\n" }, { "answer_id": 20469298, "author": "roman", "author_id": 3082558, "author_profile": "https://Stackoverflow.com/users/3082558", "pm_score": 0, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_Load(object sender, EventArgs e)\n {\n foreach (FontFamily fam in FontFamily.Families)\n {\n listBox1.Items.Add(fam.Name);\n }\n listBox1.DrawMode = DrawMode.OwnerDrawFixed; // 属性里设置\n\n }\n\n private void listBox1_DrawItem(object sender, DrawItemEventArgs e)\n {\n e.DrawBackground();\n e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), new Font(listBox1.Items[e.Index].ToString(), listBox1.Font.Size), Brushes.Black, e.Bounds);\n //e.DrawFocusRectangle();\n }\n }\n}\n" }, { "answer_id": 22669669, "author": "jsirr13", "author_id": 1491812, "author_profile": "https://Stackoverflow.com/users/1491812", "pm_score": 2, "selected": false, "text": "e.Bounds OnMeasureItem DrawMode.OwnerDrawVariable listBox.DrawMode = DrawMode.OwnerDrawVariable;\n void listBox_MeasureItem(object sender, MeasureItemEventArgs e)\n{\n e.ItemHeight = 18;\n}\n" }, { "answer_id": 32877943, "author": "Skydev", "author_id": 1493367, "author_profile": "https://Stackoverflow.com/users/1493367", "pm_score": 1, "selected": false, "text": " private void listBoxDrawItem (object sender, DrawItemEventArgs e)\n {\n Font f = e.Font;\n if (e.Index == 1) //TODO: Your condition to make text bold\n f = new Font(e.Font, FontStyle.Bold);\n e.DrawBackground();\n e.Graphics.DrawString(((ListBox)(sender)).Items[e.Index].ToString(), f, new SolidBrush(e.ForeColor), e.Bounds);\n e.DrawFocusRectangle();\n }\n" }, { "answer_id": 44167403, "author": "Jim Roton", "author_id": 3624300, "author_profile": "https://Stackoverflow.com/users/3624300", "pm_score": 0, "selected": false, "text": "public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n\n ListBox1.Items.AddRange(new Object[] { \"me\", \"myself\", \"bob\"});\n\n // set the draw mode to fixed\n ListBox1.DrawMode = DrawMode.OwnerDrawFixed;\n }\n\n private void ListBox1_DrawItem(object sender, DrawItemEventArgs e)\n {\n // draw the background\n e.DrawBackground();\n\n // get the font\n Font font = new Font(e.Font, (e.State & DrawItemState.Selected) == DrawItemState.Selected ? FontStyle.Bold : FontStyle.Regular);\n\n // draw the text\n e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), font, new SolidBrush(ListBox1.ForeColor), e.Bounds);\n\n e.DrawFocusRectangle();\n }\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13877/" ]
327,311
<p>Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.</p>
[ { "answer_id": 9022835, "author": "Praveen Gollakota", "author_id": 553995, "author_profile": "https://Stackoverflow.com/users/553995", "pm_score": 9, "selected": false, "text": "dict O(1) 0, 1, ..., i, ... # Logical model of Python Hash table\n -+-----------------+\n 0| <hash|key|value>|\n -+-----------------+\n 1| ... |\n -+-----------------+\n .| ... |\n -+-----------------+\n i| ... |\n -+-----------------+\n .| ... |\n -+-----------------+\n n| ... |\n -+-----------------+\n i i = hash(key) & mask mask = PyDictMINSIZE - 1 i <hash|key|value> == is i+1, i+2, ... dict" }, { "answer_id": 44509302, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": " <hash> <key> <value>\n null null null\n...010001 ffeb678c 633241c4 # addresses of the keys and values\n null null null\n ... ... ...\n [null, 0, null, null, null, null, null, null]\n <hash> <key> <value>\n...010001 ffeb678c 633241c4 \n ... ... ...\n hash key dict_0 dict_1 dict_2...\n...010001 ffeb678c 633241c4 fffad420 ...\n ... ... ... ... ...\n __dict__ __dict__ __init__ __new__ __init__ __slots__ __dict__ __dict__ __slots__ **kwargs" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ]
327,321
<p>I am working on some sort of CRM application which has huge sales data with all the customer leads etc (ASP.NET 2.0/Ajax)</p> <p>I want to create a dashboard which will have four separate data containers each container will have different sort of data and each container has to update it self after some configured time interval. so I want to update only that part of page not whole page</p> <p>What should I used in the above scenario asp.net updatePanel or jQuery implementation (which technique and why)</p> <p>Because performance is also important here.</p>
[ { "answer_id": 327418, "author": "rodbv", "author_id": 79101, "author_profile": "https://Stackoverflow.com/users/79101", "pm_score": 3, "selected": true, "text": "window.setTimeout(\"Button1.click()\",5000)" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41524/" ]
327,324
<p>I'm using Junit 4.4 and Ant 1.7. If a test case fails with an error (for example because a method threw an unexpected exception) I don't get any details about what the error was.</p> <p>My build.xml looks like this:</p> <pre><code>&lt;target name="test" depends="compile"&gt; &lt;junit printsummary="withOutAndErr" filtertrace="no" fork="yes" haltonfailure="yes" showoutput="yes"&gt; &lt;classpath refid="project.run.path"/&gt; &lt;test name="a.b.c.test.TestThingee1"/&gt; &lt;test name="a.b.c.test.NoSuchTest"/&gt; &lt;/junit&gt; &lt;/target&gt; </code></pre> <p>When I run "ant test" it says (for example) 2 Test runs, 0 failures, 1 error. It doesn't say "There is no such test as NoSuchTest" even though this is completely reasonable and would let me figure out the cause of the error.</p> <p>Thanks!</p> <p>-Dan</p>
[ { "answer_id": 327334, "author": "user41762", "author_id": 41762, "author_profile": "https://Stackoverflow.com/users/41762", "pm_score": 5, "selected": false, "text": "<formatter type=\"plain\" usefile=\"false\" />\n" }, { "answer_id": 327619, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 3, "selected": false, "text": "<target name=\"test\">\n <mkdir dir=\"target/test-results\"/>\n <junit fork=\"true\" forkmode=\"perBatch\" haltonfailure=\"false\"\n printsummary=\"true\" dir=\"target\" failureproperty=\"test.failed\">\n <classpath>\n <path refid=\"class.path\"/>\n <pathelement location=\"target/classes\"/>\n <pathelement location=\"target/test-classes\"/>\n </classpath>\n <formatter type=\"brief\" usefile=\"false\" />\n <formatter type=\"xml\" />\n <batchtest todir=\"target/test-results\">\n <fileset dir=\"target/test-classes\" includes=\"**/*Test.class\"/>\n </batchtest>\n </junit>\n\n <mkdir dir=\"target/test-report\"/>\n <junitreport todir=\"target/test-report\">\n <fileset dir=\"target/test-results\">\n <include name=\"TEST-*.xml\"/>\n </fileset>\n <report format=\"frames\" todir=\"target/test-report\"/>\n </junitreport>\n\n <fail if=\"test.failed\"/>\n</target>\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41762/" ]
327,326
<p>I have a problem redrawing a custom view in simple cocoa application. Drawing is based on one parameter that is being changed by a simple NSSlider. However, although i implement -setParameter: and -parameter methods and bind slider's value to that parameter in interface builder i cannot seem to make a custom view to redraw itself.</p> <p>The code that does redrawing is like this:</p> <pre><code>- (void)setParameter:(int)newParameter { parameter = newParamter; NSLog(@"Updated parameter: %d", parameter); [self setNeedsDisplay:YES]; } </code></pre> <p>I DO get the message about setting the new parameter although the view doesn't redraw itself. Any ideas are welcome!</p>
[ { "answer_id": 327338, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 4, "selected": true, "text": "[self setNeedsDisplay:YES] - (void)drawRect:(NSRect)rect drawRect:" }, { "answer_id": 1865196, "author": "Eric", "author_id": 174691, "author_profile": "https://Stackoverflow.com/users/174691", "pm_score": 2, "selected": false, "text": "NSOpenGLView [[self openGLContext] flushBuffer] drawRect:" }, { "answer_id": 15027467, "author": "dreamzor", "author_id": 1280800, "author_profile": "https://Stackoverflow.com/users/1280800", "pm_score": 0, "selected": false, "text": "setNeedsDisplay:YES" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41761/" ]
327,337
<pre><code>mysql&gt; desc categories; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(80) | YES | | NULL | | +-------+-------------+------+-----+---------+----------------+ mysql&gt; desc expenses; +-------------+---------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+---------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | created_at | datetime | NO | | NULL | | | description | varchar(100) | NO | | NULL | | | amount | decimal(10,2) | NO | | NULL | | | category_id | int(11) | NO | MUL | 1 | | +-------------+---------------+------+-----+---------+----------------+ </code></pre> <p>Now I need the top N categories like this...</p> <pre><code>Expense.find_by_sql("SELECT categories.name, sum(amount) as total_amount from expenses join categories on category_id = categories.id group by category_id order by total_amount desc") </code></pre> <p>But this is nagging at my Rails conscience.. it seems that it may be possible to achieve the same thing via Expense.find and supplying options like :group, :joins..</p> <ul> <li>Can someone translate this query into ActiveRecord Model speak ? </li> <li>Is it worth it... Personally i find the SQL more readable and gets my job done faster.. maybe coz I'm still learning Rails. Any advantages with not embedding SQL in source code (apart from not being able to change DB vendors..sql flavor, etc.)?</li> <li>Seems like <code>find_by_sql</code> doesn't have the bind variable provision like <code>find</code>. What is the workaround? e.g. if i want to limit the number of records to a user-specified limit.</li> </ul>
[ { "answer_id": 327574, "author": "François Beausoleil", "author_id": 7355, "author_profile": "https://Stackoverflow.com/users/7355", "pm_score": 2, "selected": false, "text": "Expense.find(:all,\n :select => \"categories.name name, sum(amount) total_amount\",\n :joins => \"categories on category_id = categories.id\",\n :group => \"category_id\",\n :order => \"total_amount desc\")\n" }, { "answer_id": 327691, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 2, "selected": false, "text": "# You can use the same string replacement techniques as you can with ActiveRecord#find\n Post.find_by_sql [\"SELECT title FROM posts WHERE author = ? AND created > ?\", author_id, start_date]\n" }, { "answer_id": 328787, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "def Expense.get_top_n_categories options={}\n #sQuery = \"SELECT categories.name, sum(amount) as total_amount \n # from expenses \n # join categories on category_id = categories.id \n # group by category_id \n # order by total_amount desc\";\n #sQuery += \" limit #{options[:limit].to_i}\" if !options[:limit].nil?\n #Expense.find_by_sql(sQuery)\n query_options = {:select => \"categories.name name, sum(amount) total_amount\",\n :joins => \"inner join categories on category_id = categories.id\",\n :group => \"category_id\",\n :order => \"total_amount desc\"}\n query_options[:limit] = options[:limit].to_i if !options[:limit].nil?\n Expense.find(:all, query_options)\n end\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
327,358
<p>I am new to .net and would like to know whether .net has the java equivalent of AtomicInteger, ConcurrentLinkedQueue, etc?</p> <p>I did a bit of search and couldnt come up with anything.</p> <p>The lock free algorithms need some sort of a CAS instruction, which is provided through the undocumented Unsafe class in Java, does .net have anything equivalent?</p>
[ { "answer_id": 327391, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "Interlocked" }, { "answer_id": 327400, "author": "pdeva", "author_id": 14316, "author_profile": "https://Stackoverflow.com/users/14316", "pm_score": 0, "selected": false, "text": "int counter;\nvoid code(){\n myThreadVal = Interlocked.increment(counter);\n}\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14316/" ]
327,361
<p>How can I add an input form in an Excel sheet. I want to insert values into an Excel cell using the form.</p>
[ { "answer_id": 327396, "author": "Oddthinking", "author_id": 8014, "author_profile": "https://Stackoverflow.com/users/8014", "pm_score": 2, "selected": false, "text": " A B C\n1 Name Age Favourite Animal\n2 Jane 11 Horse\n" } ]
2008/11/29
[ "https://Stackoverflow.com/questions/327361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38931/" ]