qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
252,260 |
<p>I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter.
The function looks like this: </p>
<pre><code>Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function
</code></pre>
<p>and I'm Invoking it like this:</p>
<pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)
</code></pre>
<p>This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.</p>
<pre><code>Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)
</code></pre>
<p>Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?</p>
|
[
{
"answer_id": 319190,
"author": "codeConcussion",
"author_id": 1321,
"author_profile": "https://Stackoverflow.com/users/1321",
"pm_score": 0,
"selected": false,
"text": "<p>I would overload the <strong>DoSomeStuff</strong> method rather than use an optional parameter...</p>\n\n<pre><code>Private Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String) As Boolean\n Return DoSomeStuff(blah1, blah2, \"45\")\nEnd Function\n\nPrivate Overloads Function DoSomeStuff(ByVal blah1 As String, ByVal blah2 As String, ByVal blah3 As String) As Boolean\n 'stuff\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 319209,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 2,
"selected": false,
"text": "<p>The Visual Basic compiler actually substitutes the optional parameter values into the calling code. So if your actual code was:</p>\n\n<pre><code>DoSomeStuff(blah1, blah2)</code></pre>\n\n<p>Visual Basic would have emitted IL code equivalent to:</p>\n\n<pre><code>DoSomeStuff(blah1, blah2, \"45\")</code></pre>\n\n<p>To know what that last parameter is, you'll need to get a reference to the parameter's object (I'm not sure what that is in Reflector - in .NET you'd get access to the MethodInfo and then to the ParameterInfo), then get its custom attributes, looking for an attribute marked with OptionalAttribute and DefaultParameterValueAttribute. Then, you'll need to call it with the third parameter, supplying the value from DefaultParameterValueAttribute. </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am trying to use reflector.InvokeMethod to invoke a function with an optional parameter.
The function looks like this:
```
Private Function DoSomeStuff(ByVal blah1 as string, ByVal blah2 as string, Optional ByVal blah3 as string = "45") as boolean
'stuff
end function
```
and I'm Invoking it like this:
```
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2, Param3)
```
This works fine, other than when I don't pass the third (optional) parameter, it dosn't hit the function.
```
Dim result As Boolean = Reflector.InvokeMethod(AccessModifier.private,obj_of_Class, "DoSomeStuff", Param1, Param2)
```
Is there a way I can use Reflector.invokeMethod to call this function without passing the optional parameter? or another way to achieve this?
|
The Visual Basic compiler actually substitutes the optional parameter values into the calling code. So if your actual code was:
```
DoSomeStuff(blah1, blah2)
```
Visual Basic would have emitted IL code equivalent to:
```
DoSomeStuff(blah1, blah2, "45")
```
To know what that last parameter is, you'll need to get a reference to the parameter's object (I'm not sure what that is in Reflector - in .NET you'd get access to the MethodInfo and then to the ParameterInfo), then get its custom attributes, looking for an attribute marked with OptionalAttribute and DefaultParameterValueAttribute. Then, you'll need to call it with the third parameter, supplying the value from DefaultParameterValueAttribute.
|
252,267 |
<p>The code at the end produces a compile error:</p>
<pre><code>NotApplicable.java:7: run() in cannot be applied to (int)
run(42);
^
1 error
</code></pre>
<p>The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?</p>
<pre><code>public class NotApplicable {
public NotApplicable() {
new Runnable() {
public void run() {
foo(42);
run(42);
// uncomment below to fix
//NotApplicable.this.run(42);
}
};
}
private void run(int bar) {
}
public void foo(int bar) {
}
}
</code></pre>
|
[
{
"answer_id": 252276,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "<p>This is because <code>run</code> is being re-declared when you enter the <code>new Runnable() {}</code> scope. All previous bindings to run become inaccessible. It's as if you were doing this:</p>\n\n<pre><code>import java.util.*;\n\npublic class tmp\n{\n private int x = 20;\n public static class Inner\n {\n private List x = new ArrayList();\n public void func()\n {\n System.out.println(x + 10);\n }\n }\n\n public static void main(String[] args)\n {\n (new Inner()).func();\n }\n}\n</code></pre>\n\n<p>The compiler won't look for something that matches the type of <code>x</code> all the way up the scope stack, it'll just halt when it finds the first references and sees that the types are incompatible.</p>\n\n<p><strong>NOTE:</strong> It's not as if it <em>couldn't</em> do this... it's just that, to preserve your own sanity, it's been decided that it shouldn't.</p>\n"
},
{
"answer_id": 252401,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 5,
"selected": true,
"text": "<p>The explanation for the behavior of your code sample is that <code>this</code> is defined to be the class that you are currently \"most\" inside of. In this case, you are \"most\" inside the anonymous inner class that subclasses runnable and there is no method which matches <code>run(int)</code>. To broaden your search you specify which <code>this</code> you want to use by stating <code>NotApplicable.this.run(42)</code>.</p>\n\n<p>The jvm will evaluate as follows:</p>\n\n<p><code>this</code> -> currently executing instance of <code>Runnable</code> with method <code>run()</code></p>\n\n<p><code>NotApplicable.this</code> -> currently executing instance of <code>NotApplicable</code> with method <code>run(int)</code></p>\n\n<p>The compiler will look up the nesting tree for the first method that matches the NAME of the method. <em>–Thanks to DJClayworth for this clarification</em></p>\n\n<p>The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run.</p>\n\n<pre><code>public class Outer{\n\n public Outer() {\n new Runnable() {\n public void printit() {\n System.out.println( \"Anonymous Inner\" );\n }\n public void run() {\n printit(); // prints \"Anonymous Inner\"\n this.printit(); //prints \"Anonymous Inner\"\n\n // would not be possible to execute next line without this behavior\n Outer.this.printit(); //prints \"Outer\" \n }\n };\n }\n\n public void printit() {\n System.out.println( \"Outer\" );\n }\n}\n</code></pre>\n"
},
{
"answer_id": 253908,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I recall the rules for selecting a method to run between nested classes are approximately the same as the rules for selecting a method in an inheritance tree. That means that what we are getting here is not overloading, it's hiding. The difference between these is crucial to understanding methods in inheritance.</p>\n\n<p>If your Runnable was declared as a subclass, then the run() method would hide the run(int) method in the parent. Any call to run(...) would try to execute the one on Runnable, but would fail if it couldn't match signatures. Since foo is not declared in the child then the one on the parent is called.</p>\n\n<p>The same principle is happening here. Look up references to \"method hiding\" and it should be clear.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21838/"
] |
The code at the end produces a compile error:
```
NotApplicable.java:7: run() in cannot be applied to (int)
run(42);
^
1 error
```
The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?
```
public class NotApplicable {
public NotApplicable() {
new Runnable() {
public void run() {
foo(42);
run(42);
// uncomment below to fix
//NotApplicable.this.run(42);
}
};
}
private void run(int bar) {
}
public void foo(int bar) {
}
}
```
|
The explanation for the behavior of your code sample is that `this` is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches `run(int)`. To broaden your search you specify which `this` you want to use by stating `NotApplicable.this.run(42)`.
The jvm will evaluate as follows:
`this` -> currently executing instance of `Runnable` with method `run()`
`NotApplicable.this` -> currently executing instance of `NotApplicable` with method `run(int)`
The compiler will look up the nesting tree for the first method that matches the NAME of the method. *–Thanks to DJClayworth for this clarification*
The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run.
```
public class Outer{
public Outer() {
new Runnable() {
public void printit() {
System.out.println( "Anonymous Inner" );
}
public void run() {
printit(); // prints "Anonymous Inner"
this.printit(); //prints "Anonymous Inner"
// would not be possible to execute next line without this behavior
Outer.this.printit(); //prints "Outer"
}
};
}
public void printit() {
System.out.println( "Outer" );
}
}
```
|
252,274 |
<p>I open gmail, click on an inbox item, and look at source of the page. It doesn't look like there isn't any proper html to relate to what is shown on the actual page.</p>
<p>How is the source getting processed into the actual page? Is there some javascript processing this information?</p>
|
[
{
"answer_id": 252306,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": -1,
"selected": false,
"text": "<p>In IE you get a blank page if you right-click and \"View Source\". If you use the Page menu > View Source, you see the actual page source. As Steve mentioned, in Firefox you see the actual source both from right-click \"View Page Source\" and from View menu > Page Source.</p>\n\n<p>I suspect they're taking advantage of some IE-specific obfuscation to hide their secret sauce from 85% of the users.</p>\n"
},
{
"answer_id": 252307,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 2,
"selected": false,
"text": "<p>GMail uses a large amount of java script to make its pages work. This javascript is manipulating the HTML DOM.</p>\n\n<p>If you look at the page source you aren't seeing the current contents of the DOM. You need to use a tool that will show you the HTML DOM. I use Opera Dragonfly, but there are plenty of others for other browsers. Dragonfly will show the the scripts for the page, as well as the event handlers for each element of the DOM.</p>\n\n<p>Edited 3 Nov 08:</p>\n\n<p>In response to the request for access to the scripts, when I view the page the scripts all come up as inline. As others have said, they're obfuscated, so less than easy to read. Here is just a sample:</p>\n\n<pre><code>try{function aa(a,b){return a.appendChild=b}function ba(a,b){return a.textContent=b}function da(a,b){return a.stop=b}function ea(a,b){return a.toString=b}function fa(a,b){return a.length=b}function ga(a,b){return a.title=b}function ha(a,b){return a.position=b}function ia(a,b){return a.create=b}function ja(a,b){return a.className=b}function ka(a,b){return a.width=b}function la(a,b){return a.expand=b}function ma(a,b){return a.abort=b}function na(a,b){return a.data=b}function oa(a,b){return a.next=b}\nfunction pa(a,b){return a.load=b}function d(a,b){return a.innerHTML=b}function qa(a,b){return a.onerror=b}function sa(a,b){return a.getDate=b}function ta(a,b){return a.value=b}function ua(a,b){return a.disabled=b}function va(a,b){return a.dispatchEvent=b}function wa(a,b){return a.currentTarget=b}function xa(a,b){return a.left=b}function ya(a,b){return a.hideFocus=b}function za(a,b){return a.removeChild=b}function Aa(a,b){return a.target=b}function Ba(a,b){return a.screenX=b}\nfunction Ca(a,b){return a.screenY=b}function Da(a,b){return a.send=b}function Ea(a,b){return a.remove=b}function Fa(a,b){return a.start=b}function Ga(a,b){return a.cssText=b}function Ha(a,b){return a.keyCode=b}function Ia(a,b){return a.enabled=b}function Ja(a,b){return a.href=b}function Ka(a,b){return a.handleEvent=b}function La(a,b){return a.removeNode=b}function Ma(a,b){return a.detach=b}function Na(a,b){return a.type=b}function Oa(a,b){return a.contains=b}function Pa(a,b){return a.tabIndex=b}\nfunction Qa(a,b){return a.cellSpacing=b}function Ra(a,b){return a.clear=b}function Sa(a,b){return a.setPosition=b}function Ta(a,b){return a.cellPadding=b}function Ua(a,b){return a.display=b}function Va(a,b){return a.execute=b}function Wa(a,b){return a.height=b}function Xa(a,b){return a.nodeValue=b}function Ya(a,b){return a.clientX=b}function Za(a,b){return a.clientY=b}function ab(a,b){return a.right=b}function bb(a,b){return a.visibility=b}\nfunction aaa(a){var b=cb[i](db);(new Image).src=baa+eb(b)+\"&jsmsg=\"+eb(a)+caa+fb+daa+(new Date)[gb]()}function _B_record(){cb[k]((new Date)[gb]())}function _B_prog(a){top.pr=a;if(hb===undefined){var b=top[ib][jb](eaa);hb=b?b[m]:null}if(hb){ka(hb,n[kb](a*0.99)+lb);if(a==100)hb=null}}function _B_err(a){aaa(a);throw a;}function mb(a,b){var c=a[nb](ob),e=b||pb;for(var f;f=c[rb]();)if(e[f])e=e[f];else return null;return e}function sb(){}function tb(a){a.lg=function $(){return a.bmc||(a.bmc=new a)}}\nfunction ub(a){var b=typeof a;if(b==vb)if(a){if(typeof a[o]==wb&&typeof a[xb]!=\"undefined\"&&!faa(a,gaa))return yb;if(typeof a[q]!=\"undefined\")return zb}else return Ab;else if(b==zb&&typeof a[q]==\"undefined\")return vb;return b}function haa(a,b){if(b in a)for(var c in a)if(c==b&&Bb[r][Cb][q](a,b))return true;return false}function Db(a){return typeof a!=\"undefined\"}function Eb(a){return ub(a)==yb}function Fb(a){var b=ub(a);return b==yb||b==vb&&typeof a[o]==wb}function Gb(a){return typeof a==Hb}\nfunction Ib(a){return typeof a==wb}function Jb(a){return ub(a)==zb}function Kb(a){var b=ub(a);return b==vb||b==yb||b==zb}function Lb(a){if(a[Cb]&&a[Cb](iaa)){var b=a.closure_hashCode_;if(b)return b}a.closure_hashCode_||(a.closure_hashCode_=++jaa);return a.closure_hashCode_}\nfunction s(a,b){var c=a.SSb;if(arguments[o]>2){var e=Array[r][Mb][q](arguments,2);c&&e[Nb][Ob](e,c);c=e}b=a.WSb||b;a=a.TSb||a;var f,g=b||pb;f=c?function(){var h=Array[r][Mb][q](arguments);h[Nb][Ob](h,c);return a[Ob](g,h)}:function(){return a[Ob](g,arguments)};f.SSb=c;f.WSb=b;f.TSb=a;return f}function Pb(a){var b=Array[r][Mb][q](arguments,1);b[Nb](a,null);return s[Ob](null,b)}function Qb(a,b){for(var c in b)a[c]=b[c]}\nfunction t(a,b){function c(){}c.prototype=b[r];a.F=b[r];a.prototype=new c;a[r].constructor=a}function Rb(a,b,c){if(a[Sb])return a[Sb](b,c);if(Array[Sb])return Array[Sb](a,b,c);var e=c==null?0:c<0?n.max(0,a[o]+c):c;for(var f=e;f<a[o];f++)if(f in a&&a[f]===b)return f;return-1}function Tb(a,b,c){if(a[Ub])a[Ub](b,c);else if(Array[Ub])Array[Ub](a,b,c);else{var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)g in f&&b[q](c,f[g],g,a)}}\nfunction Vb(a,b,c){if(a.map)return a.map(b,c);if(Array.map)return Array.map(a,b,c);var e=a[o],f=[],g=0,h=Gb(a)?a[nb](v):a;for(var j=0;j<e;j++)if(j in h)f[g++]=b[q](c,h[j],j,a);return f}function Wb(a,b,c){if(a[Xb])return a[Xb](b,c);if(Array[Xb])return Array[Xb](a,b,c);var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)if(g in f&&b[q](c,f[g],g,a))return true;return false}\n</code></pre>\n"
},
{
"answer_id": 252482,
"author": "Jarett Millard",
"author_id": 15882,
"author_profile": "https://Stackoverflow.com/users/15882",
"pm_score": 1,
"selected": false,
"text": "<p>When you do plain \"View Source,\" you're looking at the source of the loading page. All the HTML there is dynamically replaced with the GMail app when it's all loaded.</p>\n\n<p>EDIT: GMail also makes extensive use of iframes for God-only-knows what. If I remember correctly, there're about 5 or 6 (i)frame objects in GMail. Additionally, much of the Javascript is loaded dynamically, without even using tags. The URL for these scripts goes something like:</p>\n\n<p><a href=\"https://mail.google.com/mail/?ui=2&view=jsm&name=gm&ver=A7pcfYmUnLY&am=X_E5t8T3EkGpRf3deGMWZA\" rel=\"nofollow noreferrer\">https://mail.google.com/mail/?ui=2&view=jsm&name=gm&ver=A7pcfYmUnLY&am=X_E5t8T3EkGpRf3deGMWZA</a></p>\n\n<p>That exact URL won't work, though; the two variables at the end depend on your individual login information/session/phase of the moon.</p>\n"
},
{
"answer_id": 252582,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 0,
"selected": false,
"text": "<p>To view the Javascript used to generate the email, use <b>Firebug</b> for firefox, click \"script\", then in the bar above that button there will be the name of one of the scripts, click on it to list all the scripts, choose whichever one you like.\ngmail probably compresses it though, making it pretty much unreadable.</p>\n"
},
{
"answer_id": 252602,
"author": "Carl89",
"author_id": 32984,
"author_profile": "https://Stackoverflow.com/users/32984",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, they are using javascript to transform that data into the complete page that you see.</p>\n"
},
{
"answer_id": 253046,
"author": "Dean Rather",
"author_id": 14966,
"author_profile": "https://Stackoverflow.com/users/14966",
"pm_score": 2,
"selected": false,
"text": "<p>As <a href=\"https://stackoverflow.com/users/20840/jay\">Jay</a> mentioned, my method of using FireFox's Web Developer Plugin doesn't actually work, it just shows the preview (first few lines).</p>\n\n<p>However, using Firefox's <b>FireBug</b> plugin, you can click <b>Inspect</b>, then move the mouse and <b>highlight what your interested in.</b> When it has the outline around it <b>click</b>. Once the selection is shown in the HTML of FireBug, <b>right-click on the HTML element</b> (in my case a div class=\"YrSjGe\"), and choose <b>Copy HTML</b>. Then go to your favorite text editor, and <b>paste</b>.</p>\n\n<p>Finally, the HTML :)</p>\n"
},
{
"answer_id": 253104,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 1,
"selected": false,
"text": "<p>As others have already mentioned, Gmail uses large portions of obfuscated Javascript to manipulate the DOM. Although it is a lot of work to discover how all of this works (since it's a lot of obfuscated code to go through), the best way to finding out how it works is to use <a href=\"http://getfirebug.com/\" rel=\"nofollow noreferrer\">Firebug</a> to look at the various AJAX-requests, included scripts and the rendered DOM.</p>\n\n<p>Also, you could read the <a href=\"http://www.sajithmr.com/gmail-architecture/\" rel=\"nofollow noreferrer\">following article</a>, which explains a short portion of the architecture used by Gmail.</p>\n"
},
{
"answer_id": 1663758,
"author": "Adam Nelson",
"author_id": 26235,
"author_profile": "https://Stackoverflow.com/users/26235",
"pm_score": 0,
"selected": false,
"text": "<p>You can also select 'Show original' on the drop down where it says 'reply' or 'reply to all' to see the exact email text including headers.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I open gmail, click on an inbox item, and look at source of the page. It doesn't look like there isn't any proper html to relate to what is shown on the actual page.
How is the source getting processed into the actual page? Is there some javascript processing this information?
|
GMail uses a large amount of java script to make its pages work. This javascript is manipulating the HTML DOM.
If you look at the page source you aren't seeing the current contents of the DOM. You need to use a tool that will show you the HTML DOM. I use Opera Dragonfly, but there are plenty of others for other browsers. Dragonfly will show the the scripts for the page, as well as the event handlers for each element of the DOM.
Edited 3 Nov 08:
In response to the request for access to the scripts, when I view the page the scripts all come up as inline. As others have said, they're obfuscated, so less than easy to read. Here is just a sample:
```
try{function aa(a,b){return a.appendChild=b}function ba(a,b){return a.textContent=b}function da(a,b){return a.stop=b}function ea(a,b){return a.toString=b}function fa(a,b){return a.length=b}function ga(a,b){return a.title=b}function ha(a,b){return a.position=b}function ia(a,b){return a.create=b}function ja(a,b){return a.className=b}function ka(a,b){return a.width=b}function la(a,b){return a.expand=b}function ma(a,b){return a.abort=b}function na(a,b){return a.data=b}function oa(a,b){return a.next=b}
function pa(a,b){return a.load=b}function d(a,b){return a.innerHTML=b}function qa(a,b){return a.onerror=b}function sa(a,b){return a.getDate=b}function ta(a,b){return a.value=b}function ua(a,b){return a.disabled=b}function va(a,b){return a.dispatchEvent=b}function wa(a,b){return a.currentTarget=b}function xa(a,b){return a.left=b}function ya(a,b){return a.hideFocus=b}function za(a,b){return a.removeChild=b}function Aa(a,b){return a.target=b}function Ba(a,b){return a.screenX=b}
function Ca(a,b){return a.screenY=b}function Da(a,b){return a.send=b}function Ea(a,b){return a.remove=b}function Fa(a,b){return a.start=b}function Ga(a,b){return a.cssText=b}function Ha(a,b){return a.keyCode=b}function Ia(a,b){return a.enabled=b}function Ja(a,b){return a.href=b}function Ka(a,b){return a.handleEvent=b}function La(a,b){return a.removeNode=b}function Ma(a,b){return a.detach=b}function Na(a,b){return a.type=b}function Oa(a,b){return a.contains=b}function Pa(a,b){return a.tabIndex=b}
function Qa(a,b){return a.cellSpacing=b}function Ra(a,b){return a.clear=b}function Sa(a,b){return a.setPosition=b}function Ta(a,b){return a.cellPadding=b}function Ua(a,b){return a.display=b}function Va(a,b){return a.execute=b}function Wa(a,b){return a.height=b}function Xa(a,b){return a.nodeValue=b}function Ya(a,b){return a.clientX=b}function Za(a,b){return a.clientY=b}function ab(a,b){return a.right=b}function bb(a,b){return a.visibility=b}
function aaa(a){var b=cb[i](db);(new Image).src=baa+eb(b)+"&jsmsg="+eb(a)+caa+fb+daa+(new Date)[gb]()}function _B_record(){cb[k]((new Date)[gb]())}function _B_prog(a){top.pr=a;if(hb===undefined){var b=top[ib][jb](eaa);hb=b?b[m]:null}if(hb){ka(hb,n[kb](a*0.99)+lb);if(a==100)hb=null}}function _B_err(a){aaa(a);throw a;}function mb(a,b){var c=a[nb](ob),e=b||pb;for(var f;f=c[rb]();)if(e[f])e=e[f];else return null;return e}function sb(){}function tb(a){a.lg=function $(){return a.bmc||(a.bmc=new a)}}
function ub(a){var b=typeof a;if(b==vb)if(a){if(typeof a[o]==wb&&typeof a[xb]!="undefined"&&!faa(a,gaa))return yb;if(typeof a[q]!="undefined")return zb}else return Ab;else if(b==zb&&typeof a[q]=="undefined")return vb;return b}function haa(a,b){if(b in a)for(var c in a)if(c==b&&Bb[r][Cb][q](a,b))return true;return false}function Db(a){return typeof a!="undefined"}function Eb(a){return ub(a)==yb}function Fb(a){var b=ub(a);return b==yb||b==vb&&typeof a[o]==wb}function Gb(a){return typeof a==Hb}
function Ib(a){return typeof a==wb}function Jb(a){return ub(a)==zb}function Kb(a){var b=ub(a);return b==vb||b==yb||b==zb}function Lb(a){if(a[Cb]&&a[Cb](iaa)){var b=a.closure_hashCode_;if(b)return b}a.closure_hashCode_||(a.closure_hashCode_=++jaa);return a.closure_hashCode_}
function s(a,b){var c=a.SSb;if(arguments[o]>2){var e=Array[r][Mb][q](arguments,2);c&&e[Nb][Ob](e,c);c=e}b=a.WSb||b;a=a.TSb||a;var f,g=b||pb;f=c?function(){var h=Array[r][Mb][q](arguments);h[Nb][Ob](h,c);return a[Ob](g,h)}:function(){return a[Ob](g,arguments)};f.SSb=c;f.WSb=b;f.TSb=a;return f}function Pb(a){var b=Array[r][Mb][q](arguments,1);b[Nb](a,null);return s[Ob](null,b)}function Qb(a,b){for(var c in b)a[c]=b[c]}
function t(a,b){function c(){}c.prototype=b[r];a.F=b[r];a.prototype=new c;a[r].constructor=a}function Rb(a,b,c){if(a[Sb])return a[Sb](b,c);if(Array[Sb])return Array[Sb](a,b,c);var e=c==null?0:c<0?n.max(0,a[o]+c):c;for(var f=e;f<a[o];f++)if(f in a&&a[f]===b)return f;return-1}function Tb(a,b,c){if(a[Ub])a[Ub](b,c);else if(Array[Ub])Array[Ub](a,b,c);else{var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)g in f&&b[q](c,f[g],g,a)}}
function Vb(a,b,c){if(a.map)return a.map(b,c);if(Array.map)return Array.map(a,b,c);var e=a[o],f=[],g=0,h=Gb(a)?a[nb](v):a;for(var j=0;j<e;j++)if(j in h)f[g++]=b[q](c,h[j],j,a);return f}function Wb(a,b,c){if(a[Xb])return a[Xb](b,c);if(Array[Xb])return Array[Xb](a,b,c);var e=a[o],f=Gb(a)?a[nb](v):a;for(var g=0;g<e;g++)if(g in f&&b[q](c,f[g],g,a))return true;return false}
```
|
252,282 |
<p>I'm working on an import (from Excel) dialog to select ranges of cells.</p>
<p>When the range is selected, I use the event sink to catch the event and highlight the first row and first column.</p>
<p>I need to unhighlight the previous selection's first row and column. I don't think it's safe to just get the selected range at the time the selection changes and remember it, such as (pseudocode for brevity and clarity):</p>
<pre><code>OnSelectionChange()
{
if (m_PrevSelection)
UnHilite(m_PrevSelection);
HiliteCurrentSelection();
GetSelectedRange(m_PrevSelection);
}
</code></pre>
<p>I'm guessing that just holding onto that range (obtained from _Application::Selection) without releasing it is going to cause all sorts of problems. I haven't found a way to copy the range (IRange Copy just copies cell contents from one range to another).</p>
<p>I guess I could take the range's cell addresses and store those, then recreate a range from them when I need to do the unhighlighting. This would seem to me to come up often. Is there a more elegant solution?</p>
|
[
{
"answer_id": 252439,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 3,
"selected": true,
"text": "<p>If you were working in Excel VBA, you could </p>\n\n<pre><code>Set Rng = Application.Selection\n</code></pre>\n\n<p>where Rng is an Excel Range object. I imagine you could replicate this object from where you are.</p>\n\n<p>Or you could store the cell address in a string variable as you suggested, which of course doesn't require any objects. </p>\n\n<p>Unfortunately, Excel doesn't keep a history of selections.</p>\n"
},
{
"answer_id": 252853,
"author": "Hobbo",
"author_id": 6387,
"author_profile": "https://Stackoverflow.com/users/6387",
"pm_score": 1,
"selected": false,
"text": "<p>If you do not expect the range to move or change in size I would store the address and later use Range(myAddress) to return the range object for highlighting.</p>\n\n<p>An address reference will always refer to a fixed area of the sheet whereas a range will be updated to reflect cell insertions/deletions. Either of these may suit your intentions but note that the range reference may become undefined if the cells it contains are deleted.</p>\n"
},
{
"answer_id": 252885,
"author": "JTeagle",
"author_id": 162171,
"author_profile": "https://Stackoverflow.com/users/162171",
"pm_score": 1,
"selected": false,
"text": "<p>Whenever you detect a new range (which you're already doing, to highlight the first row and column), save details of that range to variables somewhere (assuming it's a single, rectangular range, store first and last row, and first and last column). </p>\n\n<p>Whenever you detect a new range after that, you now have stored details of the previous range to use to clear the previous highlights (and this event will store the details for next time, and so on).</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965047/"
] |
I'm working on an import (from Excel) dialog to select ranges of cells.
When the range is selected, I use the event sink to catch the event and highlight the first row and first column.
I need to unhighlight the previous selection's first row and column. I don't think it's safe to just get the selected range at the time the selection changes and remember it, such as (pseudocode for brevity and clarity):
```
OnSelectionChange()
{
if (m_PrevSelection)
UnHilite(m_PrevSelection);
HiliteCurrentSelection();
GetSelectedRange(m_PrevSelection);
}
```
I'm guessing that just holding onto that range (obtained from \_Application::Selection) without releasing it is going to cause all sorts of problems. I haven't found a way to copy the range (IRange Copy just copies cell contents from one range to another).
I guess I could take the range's cell addresses and store those, then recreate a range from them when I need to do the unhighlighting. This would seem to me to come up often. Is there a more elegant solution?
|
If you were working in Excel VBA, you could
```
Set Rng = Application.Selection
```
where Rng is an Excel Range object. I imagine you could replicate this object from where you are.
Or you could store the cell address in a string variable as you suggested, which of course doesn't require any objects.
Unfortunately, Excel doesn't keep a history of selections.
|
252,286 |
<p>This sounds dumb, but I can't get it to work. I think i just dont' understand the difference between <code>%%v, %v% and %v</code></p>
<p>Here's what I'm trying to do:</p>
<pre><code>for %%v in (*.flv) do ffmpeg.exe -i "%%v" -y -f mjpeg -ss 0.001 -vframes 1 -an "%%v.jpg"
</code></pre>
<p>This successfully generates a thumbnail for each of the movies, but the problem is:</p>
<pre><code>movie.flv -> movie.flv.jpg
</code></pre>
<p>So what I would like to do is pull the last 4 characters off <code>%%v</code> and use that for the second variable.</p>
<p>I've been trying things like this:</p>
<pre><code>%%v:~0,-3%
</code></pre>
<p>But it's not working, nor are any of the iterations of that that I could think of.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 252308,
"author": "WPWoodJr",
"author_id": 32122,
"author_profile": "https://Stackoverflow.com/users/32122",
"pm_score": 4,
"selected": true,
"text": "<p>Use %%~nV to get the filename only.</p>\n"
},
{
"answer_id": 252316,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": false,
"text": "<pre><code>for %%v in (*.flv) do ffmpeg.exe -i \"%%v\" -y -f mjpeg -ss 0.001 -vframes 1 -an \"%%~nv.jpg\"\n</code></pre>\n\n<p>From \"help for\":</p>\n\n<pre><code>%~I - expands %I removing any surrounding quotes (\")\n%~fI - expands %I to a fully qualified path name\n%~dI - expands %I to a drive letter only\n%~pI - expands %I to a path only\n%~nI - expands %I to a file name only\n%~xI - expands %I to a file extension only\n%~sI - expanded path contains short names only\n%~aI - expands %I to file attributes of file\n%~tI - expands %I to date/time of file\n%~zI - expands %I to size of file\n%~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n</code></pre>\n"
},
{
"answer_id": 252768,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>I am not as good at batch as the above (I use WSH or other script languages instead) but I can try and explain %%v %v and %v%.</p>\n\n<p>The first two forms are used in a <code>for</code> loop. <code>help for</code> explains the difference, the first form is used in a batch file while the second one is used when typing (pasting) the command directly at the command prompt.</p>\n\n<p>The last form just replaces the variable name (environment variable) with its value:</p>\n\n<pre><code>set FOO=C:\\bar\\foo\ncd %FOO%\\gah\n</code></pre>\n"
},
{
"answer_id": 6310580,
"author": "BlueRaja - Danny Pflughoeft",
"author_id": 238419,
"author_profile": "https://Stackoverflow.com/users/238419",
"pm_score": 5,
"selected": false,
"text": "<p>For people who found this thread looking for how to actually perform string operations on for-loop variables (uses <a href=\"http://ss64.com/nt/delayedexpansion.html\" rel=\"noreferrer\">delayed expansion</a>):</p>\n\n<pre><code>setlocal enabledelayedexpansion\n\n...\n\n::Replace \"12345\" with \"abcde\"\nfor %%i in (*.txt) do (\n set temp=%%i\n echo !temp:12345=abcde!\n)\n</code></pre>\n"
},
{
"answer_id": 36946079,
"author": "Farsee",
"author_id": 3366321,
"author_profile": "https://Stackoverflow.com/users/3366321",
"pm_score": 1,
"selected": false,
"text": "<p>Yet another way that I prefer is to create a <em>sub-routine</em> (:processMpeg) that I call for each element in the For loop, to which I pass the %%v variable. </p>\n\n<pre><code>for %%v in (*.flv) do call :processMpeg \"%%v\"\ngoto :eof\n\n:processMpeg\n set fileName=%~n1\n echo P1=%1 fileName=%fileName% fullpath=%~dpnx1\n ffmpeg.exe -i \"%~1\" -y -f mjpeg -ss 0.001 -vframes 1 -an \"%filename%.jpg\"\n goto :eof\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10680/"
] |
This sounds dumb, but I can't get it to work. I think i just dont' understand the difference between `%%v, %v% and %v`
Here's what I'm trying to do:
```
for %%v in (*.flv) do ffmpeg.exe -i "%%v" -y -f mjpeg -ss 0.001 -vframes 1 -an "%%v.jpg"
```
This successfully generates a thumbnail for each of the movies, but the problem is:
```
movie.flv -> movie.flv.jpg
```
So what I would like to do is pull the last 4 characters off `%%v` and use that for the second variable.
I've been trying things like this:
```
%%v:~0,-3%
```
But it's not working, nor are any of the iterations of that that I could think of.
Any ideas?
|
Use %%~nV to get the filename only.
|
252,287 |
<p>Here's my setup: a Mac, running OS X Tiger. Windows XP running in a virtual machine (Parallels). Windows XP has my Mac home directory mapped as a network drive.</p>
<p>I have two files in a directory of my Mac home directory:</p>
<h3>foo.py</h3>
<pre><code>pass
</code></pre>
<h3>test.py</h3>
<pre><code>import foo
</code></pre>
<p>If I run test.py from within my virtual machine by typing 'python test.py', I get this:</p>
<pre><code>Traceback (most recent call last):
File "test.py", line 1, in <module>
import foo
ImportError: No module named foo
</code></pre>
<p>If I try to import foo from the console (running python under Windows from the same directory), all is well:</p>
<pre><code>Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>>
</code></pre>
<p>If I run test.py with Mac python, all is well.</p>
<p>If I copy test.py and foo.py to a different directory, I can run test.py under Windows without problems.</p>
<p>There is an <strong>init</strong>.py in the original directory, but it is empty. Furthermore, copying it with the other files doesn't break anything in the previous paragraph.</p>
<p>There are no python-related environment variables set.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 252299,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "<p>Add import sys; print sys.path to the start of test.py. See what it prints out in the failing case. If \".\" isn't on the list, that may be your problem.</p>\n"
},
{
"answer_id": 254355,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 1,
"selected": false,
"text": "<p>As a random guess: are the permissions on foo.py accessable from the windows client? (eg try opening with notepad from the virtual machine).</p>\n\n<p>If that's OK, try running:</p>\n\n<pre><code>python -v -v test.py\n</code></pre>\n\n<p>and looking at the output (alternatively, set PYTHONVERBOSE=2). This should list all the places it tries to import foo from. Comparing it with a similar trace on the working machine may give some further clues.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15154/"
] |
Here's my setup: a Mac, running OS X Tiger. Windows XP running in a virtual machine (Parallels). Windows XP has my Mac home directory mapped as a network drive.
I have two files in a directory of my Mac home directory:
### foo.py
```
pass
```
### test.py
```
import foo
```
If I run test.py from within my virtual machine by typing 'python test.py', I get this:
```
Traceback (most recent call last):
File "test.py", line 1, in <module>
import foo
ImportError: No module named foo
```
If I try to import foo from the console (running python under Windows from the same directory), all is well:
```
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
>>>
```
If I run test.py with Mac python, all is well.
If I copy test.py and foo.py to a different directory, I can run test.py under Windows without problems.
There is an **init**.py in the original directory, but it is empty. Furthermore, copying it with the other files doesn't break anything in the previous paragraph.
There are no python-related environment variables set.
Any ideas?
|
Add import sys; print sys.path to the start of test.py. See what it prints out in the failing case. If "." isn't on the list, that may be your problem.
|
252,297 |
<p>I was making the following call:</p>
<pre><code>result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);
</code></pre>
<p>(C++, Visual Studio 5, Vista 64bit).</p>
<p>It is failing with error code 2 ("File not found") even though "<code>regedit</code>" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?</p>
|
[
{
"answer_id": 252302,
"author": "Tim Cooper",
"author_id": 10592,
"author_profile": "https://Stackoverflow.com/users/10592",
"pm_score": 7,
"selected": true,
"text": "<p>I discovered that I could solve my problem using the flag: <code>KEY_WOW64_64KEY</code> , as in:</p>\n\n<pre><code>result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key);\n</code></pre>\n\n<p>For a full explanation: <a href=\"http://msdn.microsoft.com/en-us/library/ms724072(VS.85).aspx\" rel=\"noreferrer\">32-bit and 64-bit Application Data in the Registry</a></p>\n"
},
{
"answer_id": 291067,
"author": "Frode Lillerud",
"author_id": 33431,
"author_profile": "https://Stackoverflow.com/users/33431",
"pm_score": 5,
"selected": false,
"text": "<p>On a Windows 64-bit system the Registry is actually divided into two parts. One section is used by 64-bit processes, and one part by 32-bit processes.</p>\n\n<p>For example, if a 32-bit application programatically writes to what it believes is HKLM\\SOFTWARE\\Company\\Application, it's actually redirected by the WoW64-layer to HKLM\\SOFTWARE\\Wow6432Node\\Company\\Application.</p>\n\n<p>So when you run your 32-bit application and call RegOpenKeyEx it's actually working against the Wow6432Node\\ folder, and not the regular \\SOFTWARE node.</p>\n"
},
{
"answer_id": 3104602,
"author": "Alex",
"author_id": 371598,
"author_profile": "https://Stackoverflow.com/users/371598",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem.\nI was using:</p>\n\n<pre><code>dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,\n (LPWSTR)\"SOFTWARE\\\\0test\",\n 0,\n WRITE_DAC ,\n &hKey);\n</code></pre>\n\n<p>That didn't work. I tried it like this and it worked:</p>\n\n<pre><code>dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,\n _T(\"SOFTWARE\\\\0test\"),\n 0,\n WRITE_DAC ,\n &hKey);\n</code></pre>\n"
},
{
"answer_id": 8206649,
"author": "yue",
"author_id": 1057054,
"author_profile": "https://Stackoverflow.com/users/1057054",
"pm_score": 0,
"selected": false,
"text": "<p>yes,win7 64B,add further flag KEY_WOW64_64KEY ,it will work.\nif not work, refer to <a href=\"http://msdn.microsoft.com/en-us/library/ms724897(v=VS.85).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms724897(v=VS.85).aspx</a></p>\n"
},
{
"answer_id": 44355125,
"author": "GMG",
"author_id": 1127429,
"author_profile": "https://Stackoverflow.com/users/1127429",
"pm_score": 1,
"selected": false,
"text": "<p>You have to compile with \"Use Multi-Byte Character Set\" or cast string in code to (LPWSTR)</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10592/"
] |
I was making the following call:
```
result = RegOpenKeyEx(key, s, 0, KEY_READ, &key);
```
(C++, Visual Studio 5, Vista 64bit).
It is failing with error code 2 ("File not found") even though "`regedit`" shows that the key exists. This code has always worked on 32bit XP. Why is it "file not found" when it clearly is there?
|
I discovered that I could solve my problem using the flag: `KEY_WOW64_64KEY` , as in:
```
result = RegOpenKeyEx(key, s, 0, KEY_READ|KEY_WOW64_64KEY, &key);
```
For a full explanation: [32-bit and 64-bit Application Data in the Registry](http://msdn.microsoft.com/en-us/library/ms724072(VS.85).aspx)
|
252,304 |
<p>In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this:</p>
<pre><code>public static CustomerController Instance
{
get
{
lock(singletonLock)
{
if( _instance == null )
{
_instance = new CustomerController();
}
return _instance;
}
}
}
</code></pre>
<p>now, I get what the code is doing, but I was wondering why you would do this over just creating an instance of the class each time it is used?</p>
|
[
{
"answer_id": 252313,
"author": "goldenratio",
"author_id": 31307,
"author_profile": "https://Stackoverflow.com/users/31307",
"pm_score": 3,
"selected": true,
"text": "<p>EDIT: Oh whoops I didn't catch the \"Data Access Layers\" part. But I have an example of that too: If your multithreaded app funnels all of its' database calls through a singleton class, only one thread will ever access the database at once, avoiding race conditions.</p>\n\n<p>If you have a logging mechanism in a multi-threaded application that you use to spit out all exceptions and just write info in (especially for services, or apps that are always running, printing out statuses whenever stuff happens), you will run into file-locking issues. I use a singleton logger class, so that only one thread ever will have access to the Logger, and the rest will wait until the Logger is free to write their line in the text file.</p>\n\n<p>There are lots of cool reasons to use a singleton, but I was like you and had no idea what they were FOR until I ran into this issue with file access in a multithreaded app.</p>\n"
},
{
"answer_id": 252363,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<p>You may wish to do this also, its double checked locking, it will speed up access to your singleton</p>\n\n<pre><code> public static CustomerController Instance\n {\n get \n {\n if( _instance == null )\n {\n lock(singletonLock)\n {\n if( _instance == null )\n {\n _instance = new CustomerController(); \n }\n\n }\n } \n return _instance;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 252447,
"author": "staticsan",
"author_id": 28832,
"author_profile": "https://Stackoverflow.com/users/28832",
"pm_score": 1,
"selected": false,
"text": "<p>The answer is quite simple: you want to get the <strong>same</strong> object each time it's used. </p>\n\n<p>It gives you the advantages of being a global variable (i.e. there's only one) with the advantages of being a class object (amongst other things, it can do invisable initialization the first time it's needed).</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
In our data access layer at work we have this standard implementation where the class is accessed through a singleton public property which looks something like this:
```
public static CustomerController Instance
{
get
{
lock(singletonLock)
{
if( _instance == null )
{
_instance = new CustomerController();
}
return _instance;
}
}
}
```
now, I get what the code is doing, but I was wondering why you would do this over just creating an instance of the class each time it is used?
|
EDIT: Oh whoops I didn't catch the "Data Access Layers" part. But I have an example of that too: If your multithreaded app funnels all of its' database calls through a singleton class, only one thread will ever access the database at once, avoiding race conditions.
If you have a logging mechanism in a multi-threaded application that you use to spit out all exceptions and just write info in (especially for services, or apps that are always running, printing out statuses whenever stuff happens), you will run into file-locking issues. I use a singleton logger class, so that only one thread ever will have access to the Logger, and the rest will wait until the Logger is free to write their line in the text file.
There are lots of cool reasons to use a singleton, but I was like you and had no idea what they were FOR until I ran into this issue with file access in a multithreaded app.
|
252,323 |
<p>I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for cut and paste like the text box does.</p>
<p>What is a better way to implement a console like element embedded in a winforms window.</p>
<p>Edit:
I would still like to be able to embed a output window like visual studio but since I can't figure out an easy way here are the two solutions I use.
In addition to using the RichTextBox which works but you have to clear it every now and then. I use a console that I pinvoke. Here is a little wrapper class that I wrote to handle this. </p>
<pre><code>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Con
{
class Ext_Console
{
static bool console_on = false;
public static void Show(bool on,string title)
{
console_on = on;
if (console_on)
{
AllocConsole();
Console.Title = title;
// use to change color
Console.BackgroundColor = System.ConsoleColor.White;
Console.ForegroundColor = System.ConsoleColor.Black;
}
else
{
FreeConsole();
}
}
public static void Write(string output)
{
if (console_on)
{
Console.Write(output);
}
}
public static void WriteLine(string output)
{
if (console_on)
{
Console.WriteLine(output);
}
}
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
}
// example calls
Ext_Console.Write("console output ");
Ext_Console.WriteLine("console output");
Ext_Console.Show(true,"Title of console");
</code></pre>
|
[
{
"answer_id": 252326,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>set the selectedindex of the listbox to the last element to make it scroll to the bottom</p>\n\n<p>also, limit the number of items in the listbox to something reasonable (delete from the top, keep the later items) so you don't chew up all of your memory</p>\n"
},
{
"answer_id": 252332,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 5,
"selected": true,
"text": "<p>RichTextBox has an AppendText method that is fast.\nAnd it can handle large text well.<br>\nI believe it is the best for what you need.</p>\n"
},
{
"answer_id": 252347,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Ive previously used a textbox. Add it to your form, set Multipline property to true, Scrollbars to Vertical.\nAnd finally add this following code:</p>\n\n<pre><code> private void AddConsoleComment(string comment)\n {\n textBoxConsole.Text += comment + System.Environment.NewLine;\n textBoxConsole.Select(textBoxConsole.Text.Length,0);\n textBoxConsole.ScrollToCaret();\n }\n</code></pre>\n\n<p>Essentially its adding your comment to the existing text, also appending a linefeed. And finally selecting last bit of text of length = 0. ScrollToCaret forces the textbox to scroll down to where the cursor is positioned (at the last line)</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 252366,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": "<p>I've had this exact challenge. I've solved it two different ways, both work and perform will under heavy load. One way is with a ListView. Adding a line of text is like this:</p>\n\n<pre><code> ListViewItem itm = new ListViewItem();\n itm.Text = txt;\n this.listView1.Items.Add(itm);\n this.listView1.EnsureVisible(listView1.Items.Count - 1);\n</code></pre>\n\n<p>The other way is with a DataGridView in virtual mode. I don't have that code as handy. Virtual mode is your friend.</p>\n\n<p>EDIT: re-reading, I see you want copy/paste to work. Maybe the RichText control performs ok - don't know, but if you use the ListView or DataGrid, you'd have to do more coding to get Copy/Paste to work.</p>\n"
},
{
"answer_id": 252460,
"author": "Foredecker",
"author_id": 18256,
"author_profile": "https://Stackoverflow.com/users/18256",
"pm_score": 3,
"selected": false,
"text": "<p>I do this in my C# window programs (WInforms or WPF) using a Win32 console window. I have a small class that wraps some basic Win32 APIs, thin I create a console when the program begins. This is just an example: in 'real life' you'd use a setting or some other thing to only enable the console when you needed it.</p>\n\n<pre><code>using System;\nusing System.Windows.Forms;\nusing Microsoft.Win32.SafeHandles;\nusing System.Diagnostics;\nusing MWin32Api;\n\nnamespace WFConsole\n{\n static class Program\n {\n static private SafeFileHandle ConsoleHandle;\n\n /// <summary>\n /// Initialize the Win32 console for this process.\n /// </summary>\n static private void InitWin32Console()\n {\n if ( !K32.AllocConsole() ) {\n MessageBox.Show( \"Cannot allocate console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr handle = K32.CreateFile(\n \"CONOUT$\", // name\n K32.GENERIC_WRITE | K32.GENERIC_READ, // desired access\n K32.FILE_SHARE_WRITE | K32.FILE_SHARE_READ, // share access\n null, // no security attributes\n K32.OPEN_EXISTING, // device already exists\n 0, // no flags or attributes\n IntPtr.Zero ); // no template file.\n\n ConsoleHandle = new SafeFileHandle( handle, true );\n\n if ( ConsoleHandle.IsInvalid ) {\n MessageBox.Show( \"Cannot create diagnostic console\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n //\n // Set the console screen buffer and window to a reasonable size\n // 1) set the screen buffer sizse\n // 2) Get the maximum window size (in terms of characters) \n // 3) set the window to be this size\n //\n const UInt16 conWidth = 256;\n const UInt16 conHeight = 5000;\n\n K32.Coord dwSize = new K32.Coord( conWidth, conHeight );\n if ( !K32.SetConsoleScreenBufferSize( ConsoleHandle.DangerousGetHandle(), dwSize ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.Console_Screen_Buffer_Info SBInfo = new K32.Console_Screen_Buffer_Info();\n if ( !K32.GetConsoleScreenBufferInfo( ConsoleHandle.DangerousGetHandle(), out SBInfo ) ) {\n MessageBox.Show( \"Can't get console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Exclamation);\n return;\n }\n\n K32.Small_Rect sr; ;\n sr.Left = 0;\n sr.Top = 0;\n sr.Right = 132 - 1;\n sr.Bottom = 51 - 1;\n\n if ( !K32.SetConsoleWindowInfo( ConsoleHandle.DangerousGetHandle(), true, ref sr ) ) {\n MessageBox.Show( \"Can't set console screen buffer information.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n IntPtr conHWND = K32.GetConsoleWindow();\n\n if ( conHWND == IntPtr.Zero ) {\n MessageBox.Show( \"Can't get console window handle.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n if ( !U32.SetForegroundWindow( conHWND ) ) {\n MessageBox.Show( \"Can't set console window as foreground.\",\n \"Error\",\n MessageBoxButtons.OK,\n MessageBoxIcon.Error );\n return;\n }\n\n K32.SetConsoleTitle( \"Test - Console\" );\n\n Trace.Listeners.Add( new ConsoleTraceListener() );\n }\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n InitWin32Console();\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault( false );\n Application.Run( new Main() );\n }\n }\n}\n\n\nusing System;\nusing System.Runtime.InteropServices;\n\nnamespace MWin32Api\n{\n #region Kernel32 Functions\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in Kernel32.dll\n /// </summary>\n public sealed class K32\n {\n #region Data Structures, Types and Constants\n //----------------------------------------------------------------------\n // Data Structures, Types and Constants\n // \n\n [StructLayout( LayoutKind.Sequential )]\n public class SecurityAttributes\n {\n public UInt32 nLength;\n public UIntPtr lpSecurityDescriptor;\n public bool bInheritHandle;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 4 )]\n public struct Coord\n {\n public Coord( UInt16 tx, UInt16 ty )\n {\n x = tx;\n y = ty;\n }\n public UInt16 x;\n public UInt16 y;\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 8 )]\n public struct Small_Rect\n {\n public Int16 Left;\n public Int16 Top;\n public Int16 Right;\n public Int16 Bottom;\n\n public Small_Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [StructLayout( LayoutKind.Sequential, Pack = 1, Size = 24 )]\n public struct Console_Screen_Buffer_Info\n {\n public Coord dwSize;\n public Coord dwCursorPosition;\n public UInt32 wAttributes;\n public Small_Rect srWindow;\n public Coord dwMaximumWindowSize;\n }\n\n\n public const int ZERO_HANDLE_VALUE = 0;\n public const int INVALID_HANDLE_VALUE = -1;\n\n #endregion\n #region Console Functions\n //----------------------------------------------------------------------\n // Console Functions\n // \n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool AllocConsole();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleScreenBufferSize(\n IntPtr hConsoleOutput,\n Coord dwSize );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool GetConsoleScreenBufferInfo(\n IntPtr hConsoleOutput,\n out Console_Screen_Buffer_Info lpConsoleScreenBufferInfo );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleWindowInfo(\n IntPtr hConsoleOutput,\n bool bAbsolute,\n ref Small_Rect lpConsoleWindow );\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr GetConsoleWindow();\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern bool SetConsoleTitle(\n string Filename );\n\n #endregion\n #region Create File\n //----------------------------------------------------------------------\n // Create File\n // \n public const UInt32 CREATE_NEW = 1;\n public const UInt32 CREATE_ALWAYS = 2;\n public const UInt32 OPEN_EXISTING = 3;\n public const UInt32 OPEN_ALWAYS = 4;\n public const UInt32 TRUNCATE_EXISTING = 5;\n public const UInt32 FILE_SHARE_READ = 1;\n public const UInt32 FILE_SHARE_WRITE = 2;\n public const UInt32 GENERIC_WRITE = 0x40000000;\n public const UInt32 GENERIC_READ = 0x80000000;\n\n [DllImport( \"kernel32.dll\", SetLastError = true )]\n public static extern IntPtr CreateFile(\n string Filename,\n UInt32 DesiredAccess,\n UInt32 ShareMode,\n SecurityAttributes SecAttr,\n UInt32 CreationDisposition,\n UInt32 FlagsAndAttributes,\n IntPtr TemplateFile );\n\n #endregion\n #region Win32 Miscelaneous\n //----------------------------------------------------------------------\n // Miscelaneous\n // \n [DllImport( \"kernel32.dll\" )]\n public static extern bool CloseHandle( UIntPtr handle );\n\n #endregion\n\n //----------------------------------------------------------------------\n private K32()\n {\n }\n }\n #endregion\n\n //--------------------------------------------------------------------------\n /// <summary>\n /// Functions in User32.dll\n /// </summary>\n #region User32 Functions\n public sealed class U32\n {\n [StructLayout( LayoutKind.Sequential )]\n public struct Rect\n {\n public Int32 Left;\n public Int32 Top;\n public Int32 Right;\n public Int32 Bottom;\n\n public Rect( short tLeft, short tTop, short tRight, short tBottom )\n {\n Left = tLeft;\n Top = tTop;\n Right = tRight;\n Bottom = tBottom;\n }\n }\n\n [DllImport( \"user32.dll\" )]\n public static extern bool GetWindowRect(\n IntPtr hWnd,\n [In][MarshalAs( UnmanagedType.LPStruct )]Rect lpRect );\n\n [DllImport( \"user32.dll\", SetLastError = true )]\n public static extern bool SetForegroundWindow(\n IntPtr hWnd );\n\n //----------------------------------------------------------------------\n private U32()\n {\n }\n } // U32 class\n #endregion\n} // MWin32Api namespace\n</code></pre>\n"
},
{
"answer_id": 252507,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 3,
"selected": false,
"text": "<p>You can't just keep adding logging items to a WinForms control (ListBox or RichTextBox) -- it will eventually get clogged and start swapping to disk. </p>\n\n<p>I had this exact bug at one point. The solution I had was to clip the list of displayed messages occasionally. In pseudocode, this is something like:</p>\n\n<pre><code>void AddLogMessage(String message)\n{\n list.Items.Add(message);\n\n // DO: Append message to file as needed\n\n // Clip the list\n if (list.count > ListMaxSize)\n { \n list.Items.RemoveRange(0, list.Count - listMinSize);\n }\n\n // DO: Focus the last item on the list\n}\n</code></pre>\n\n<p>ListMaxSize should be substantially bigger than ListMinSize, so clipping does not happen too often. ListMinSize is the number of recent messages that you'd normally need to look through in your logging list.</p>\n\n<p>This is just pseudocode, there is actually no RemoveRange on ListBox item collection (but there is on List). You can figure out the exact code. </p>\n"
},
{
"answer_id": 14944970,
"author": "psamwel",
"author_id": 3089,
"author_profile": "https://Stackoverflow.com/users/3089",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public class ConsoleTextBox: TextBox\n{\n private List<string> contents = new List<string>();\n private const int MAX = 50;\n\n public void WriteLine(string input)\n {\n if (contents.Count == MAX)\n contents.RemoveAt(MAX-1);\n contents.Insert(0, input);\n\n Rewrite();\n }\n\n private void Rewrite()\n {\n var sb = new StringBuilder();\n foreach (var s in contents)\n {\n sb.Append(s);\n sb.Append(Environment.NewLine);\n }\n this.Text = sb.ToString();\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32958/"
] |
I have a program that monitors debug messages and I have tried using a TextBox and appended the messages to it but it doesn't scale very well and slows way down when the number of messages gets large. I then tried a ListBox but the scrolling was snapping to the top when appending new messages. It also doesn't allow for cut and paste like the text box does.
What is a better way to implement a console like element embedded in a winforms window.
Edit:
I would still like to be able to embed a output window like visual studio but since I can't figure out an easy way here are the two solutions I use.
In addition to using the RichTextBox which works but you have to clear it every now and then. I use a console that I pinvoke. Here is a little wrapper class that I wrote to handle this.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace Con
{
class Ext_Console
{
static bool console_on = false;
public static void Show(bool on,string title)
{
console_on = on;
if (console_on)
{
AllocConsole();
Console.Title = title;
// use to change color
Console.BackgroundColor = System.ConsoleColor.White;
Console.ForegroundColor = System.ConsoleColor.Black;
}
else
{
FreeConsole();
}
}
public static void Write(string output)
{
if (console_on)
{
Console.Write(output);
}
}
public static void WriteLine(string output)
{
if (console_on)
{
Console.WriteLine(output);
}
}
[DllImport("kernel32.dll")]
public static extern Boolean AllocConsole();
[DllImport("kernel32.dll")]
public static extern Boolean FreeConsole();
}
}
// example calls
Ext_Console.Write("console output ");
Ext_Console.WriteLine("console output");
Ext_Console.Show(true,"Title of console");
```
|
RichTextBox has an AppendText method that is fast.
And it can handle large text well.
I believe it is the best for what you need.
|
252,355 |
<p>After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query. </p>
<p>Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered.</p>
<pre><code>var result = from item in Products where item.Price > 3 select item.Name;
foreach (var name in result)
{
Console.WriteLine(name);
}
</code></pre>
<p>Seems that current LINQ query spec doesn't provide support to this.</p>
<p>Is there any way to do asynchronous programming LINQ? It works like there is a callback
notification when results are ready to use without any blocking delay on I/O.</p>
|
[
{
"answer_id": 252426,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 6,
"selected": true,
"text": "<p>While LINQ doesn't really have this per se, the framework itself does... You can easily roll your own asynchronous query executor in 30 lines or so... In fact, I just threw this together for you :)</p>\n\n<p><strong>EDIT: Through writing this, I've discovered why they didn't implement it. It cannot handle anonymous types since they are scoped local. Thus, you have no way of defining your callback function.</strong> This is a pretty major thing since a lot of linq to sql stuff creates them in the select clause. Any of the below suggestions suffer the same fate, so I still think this one is the easiest to use!</p>\n\n<p>EDIT: The only solution is to not use anonymous types. You can declare the callback as just taking IEnumerable (no type args), and use reflection to access the fields (ICK!!). Another way would be to declare the callback as \"dynamic\"... oh... wait... That's not out yet. :) This is another decent example of how dynamic could be used. Some may call it abuse.</p>\n\n<p>Throw this in your utilities library:</p>\n\n<pre><code>public static class AsynchronousQueryExecutor\n{\n public static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback)\n {\n Func<IEnumerable<T>, IEnumerable<T>> func =\n new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>);\n IEnumerable<T> result = null;\n IAsyncResult ar = func.BeginInvoke(\n query,\n new AsyncCallback(delegate(IAsyncResult arr)\n {\n try\n {\n result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr);\n }\n catch (Exception ex)\n {\n if (errorCallback != null)\n {\n errorCallback(ex);\n }\n return;\n }\n //errors from inside here are the callbacks problem\n //I think it would be confusing to report them\n callback(result);\n }),\n null);\n }\n private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query)\n {\n foreach (var item in query) //the method hangs here while the query executes\n {\n yield return item;\n }\n }\n}\n</code></pre>\n\n<p>And you could use it like this:</p>\n\n<pre><code>class Program\n{\n\n public static void Main(string[] args)\n {\n //this could be your linq query\n var qry = TestSlowLoadingEnumerable();\n\n //We begin the call and give it our callback delegate\n //and a delegate to an error handler\n AsynchronousQueryExecutor.Call(qry, HandleResults, HandleError);\n\n Console.WriteLine(\"Call began on seperate thread, execution continued\");\n Console.ReadLine();\n }\n\n public static void HandleResults(IEnumerable<int> results)\n {\n //the results are available in here\n foreach (var item in results)\n {\n Console.WriteLine(item);\n }\n }\n\n public static void HandleError(Exception ex)\n {\n Console.WriteLine(\"error\");\n }\n\n //just a sample lazy loading enumerable\n public static IEnumerable<int> TestSlowLoadingEnumerable()\n {\n Thread.Sleep(5000);\n foreach (var i in new int[] { 1, 2, 3, 4, 5, 6 })\n {\n yield return i;\n }\n }\n\n}\n</code></pre>\n\n<p>Going to go put this up on my blog now, pretty handy.</p>\n"
},
{
"answer_id": 6561839,
"author": "Michael Freidgeim",
"author_id": 52277,
"author_profile": "https://Stackoverflow.com/users/52277",
"pm_score": 4,
"selected": false,
"text": "<p>TheSoftwareJedi's and <a href=\"http://ulrikb.wordpress.com/2010/04/14/executing-a-linq-query-asynchronously/\" rel=\"noreferrer\">ulrikb</a>'s(aka user316318) solutions are good for any LINQ type, but (as pointed by <a href=\"https://stackoverflow.com/users/176877/chris-moschini\">Chris Moschini</a>) do NOT delegating to underlying asynchronous calls that leverage Windows I/O Completion Ports.</p>\n\n<p>Wesley Bakker's <a href=\"http://weblogs.asp.net/wesleybakker/archive/2010/03/03/asynchronous-datacontext.aspx\" rel=\"noreferrer\">Asynchronous DataContext</a> post (triggered by <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode51AsynchronousDatabaseAccessAndLINQToSQLFun.aspx\" rel=\"noreferrer\">a blog post of Scott Hanselman</a> ) describe class for LINQ to SQL that uses sqlCommand.BeginExecuteReader/sqlCommand.EndExecuteReader, which leverage Windows I/O Completion Ports. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa365198%28v=vs.85%29.aspx\" rel=\"noreferrer\">I/O completion ports</a> provide an efficient threading model for processing multiple asynchronous I/O requests on a multiprocessor system. </p>\n"
},
{
"answer_id": 7085108,
"author": "James Dunne",
"author_id": 172557,
"author_profile": "https://Stackoverflow.com/users/172557",
"pm_score": 2,
"selected": false,
"text": "<p>I started a simple github project named <a href=\"https://github.com/JamesDunne/Asynq/\" rel=\"nofollow\">Asynq</a> to do asynchronous LINQ-to-SQL query execution. The idea is quite simple albeit \"brittle\" at this stage (as of 8/16/2011):</p>\n\n<ol>\n<li>Let LINQ-to-SQL do the \"heavy\" work of translating your <code>IQueryable</code> into a <code>DbCommand</code> via the <code>DataContext.GetCommand()</code>.</li>\n<li>For SQL 200[058], cast up from the abstract <code>DbCommand</code> instance you got from <code>GetCommand()</code> to get a <code>SqlCommand</code>. If you're using SQL CE you're out of luck since <code>SqlCeCommand</code> does not expose the async pattern for <code>BeginExecuteReader</code> and <code>EndExecuteReader</code>.</li>\n<li>Use <code>BeginExecuteReader</code> and <code>EndExecuteReader</code> off the <code>SqlCommand</code> using the standard .NET framework asynchronous I/O pattern to get yourself a <code>DbDataReader</code> in the completion callback delegate that you pass to the <code>BeginExecuteReader</code> method.</li>\n<li>Now we have a <code>DbDataReader</code> which we have no idea what columns it contains nor how to map those values back up to the <code>IQueryable</code>'s <code>ElementType</code> (most likely to be an anonymous type in the case of joins). Sure, at this point you could hand-write your own column mapper that materializes its results back into your anonymous type or whatever. You'd have to write a new one per each query result type, depending on how LINQ-to-SQL treats your IQueryable and what SQL code it generates. This is a pretty nasty option and I don't recommend it since it's not maintainable nor would it be always correct. LINQ-to-SQL can change your query form depending on the parameter values you pass in, for example <code>query.Take(10).Skip(0)</code> produces different SQL than <code>query.Take(10).Skip(10)</code>, and perhaps a different resultset schema. Your best bet is to handle this materialization problem programmatically:</li>\n<li>\"Re-implement\" a simplistic runtime object materializer that pulls columns off the <code>DbDataReader</code> in a defined order according to the LINQ-to-SQL mapping attributes of the <code>ElementType</code> Type for the <code>IQueryable</code>. Implementing this correctly is probably the most challenging part of this solution.</li>\n</ol>\n\n<p>As others have discovered, the <code>DataContext.Translate()</code> method does not handle anonymous types and can only map a <code>DbDataReader</code> directly to a properly attributed LINQ-to-SQL proxy object. Since most queries worth writing in LINQ are going to involve complex joins which inevitably end up requiring anonymous types for the final select clause, it's pretty pointless to use this provided watered-down <code>DataContext.Translate()</code> method anyway.</p>\n\n<p>There are a few minor drawbacks to this solution when leveraging the existing mature LINQ-to-SQL IQueryable provider:</p>\n\n<ol>\n<li>You cannot map a single object instance to multiple anonymous type properties in the final select clause of your <code>IQueryable</code>, e.g. <code>from x in db.Table1 select new { a = x, b = x }</code>. LINQ-to-SQL internally keeps track of which column ordinals map to which properties; it does not expose this information to the end user so you have no idea which columns in the <code>DbDataReader</code> are reused and which are \"distinct\".</li>\n<li>You cannot include constant values in your final select clause - these do not get translated into SQL and will be absent from the <code>DbDataReader</code> so you'd have to build custom logic to pull these constant values up from the <code>IQueryable</code>'s <code>Expression</code> tree, which would be quite a hassle and is simply not justifiable.</li>\n</ol>\n\n<p>I'm sure there are other query patterns that might break but these are the two biggest I could think of that could cause problems in an existing LINQ-to-SQL data access layer.</p>\n\n<p>These problems are easy to defeat - simply don't do them in your queries since neither pattern provides any benefit to the end result of the query. Hopefully this advice applies to all query patterns that would potentially cause object materialization problems :-P. It's a hard problem to solve not having access to LINQ-to-SQL's column mapping information.</p>\n\n<p>A more \"complete\" approach to solving the problem would be to effectively re-implement nearly all of LINQ-to-SQL, which is a bit more time-consuming :-P. Starting from a quality, open-source LINQ-to-SQL provider implementation would be a good way to go here. The reason you'd need to reimplement it is so that you'd have access to all of the column mapping information used to materialize the <code>DbDataReader</code> results back up to an object instance without any loss of information.</p>\n"
},
{
"answer_id": 38678827,
"author": "Nenad",
"author_id": 186822,
"author_profile": "https://Stackoverflow.com/users/186822",
"pm_score": 3,
"selected": false,
"text": "<p>Based on <a href=\"https://stackoverflow.com/a/6561839/186822\">Michael Freidgeim's answer</a> and mentioned <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode51AsynchronousDatabaseAccessAndLINQToSQLFun.aspx\" rel=\"noreferrer\">blog post from Scott Hansellman</a> and fact that you can use <code>async</code>/<code>await</code>, you can implement reusable <code>ExecuteAsync<T>(...)</code> method, which executes underlying <code>SqlCommand</code> asynchronously:</p>\n\n<pre><code>protected static async Task<IEnumerable<T>> ExecuteAsync<T>(IQueryable<T> query,\n DataContext ctx,\n CancellationToken token = default(CancellationToken))\n{\n var cmd = (SqlCommand)ctx.GetCommand(query);\n\n if (cmd.Connection.State == ConnectionState.Closed)\n await cmd.Connection.OpenAsync(token);\n var reader = await cmd.ExecuteReaderAsync(token);\n\n return ctx.Translate<T>(reader);\n}\n</code></pre>\n\n<p>And then you can (re)use it like this:</p>\n\n<pre><code>public async Task WriteNamesToConsoleAsync(string connectionString, CancellationToken token = default(CancellationToken))\n{\n using (var ctx = new DataContext(connectionString))\n {\n var query = from item in Products where item.Price > 3 select item.Name;\n var result = await ExecuteAsync(query, ctx, token);\n foreach (var name in result)\n {\n Console.WriteLine(name);\n }\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
After I read a bunch of LINQ related stuff, I suddenly realized that no articles introduce how to write asynchronous LINQ query.
Suppose we use LINQ to SQL, below statement is clear. However, if the SQL database responds slowly, then the thread using this block of code would be hindered.
```
var result = from item in Products where item.Price > 3 select item.Name;
foreach (var name in result)
{
Console.WriteLine(name);
}
```
Seems that current LINQ query spec doesn't provide support to this.
Is there any way to do asynchronous programming LINQ? It works like there is a callback
notification when results are ready to use without any blocking delay on I/O.
|
While LINQ doesn't really have this per se, the framework itself does... You can easily roll your own asynchronous query executor in 30 lines or so... In fact, I just threw this together for you :)
**EDIT: Through writing this, I've discovered why they didn't implement it. It cannot handle anonymous types since they are scoped local. Thus, you have no way of defining your callback function.** This is a pretty major thing since a lot of linq to sql stuff creates them in the select clause. Any of the below suggestions suffer the same fate, so I still think this one is the easiest to use!
EDIT: The only solution is to not use anonymous types. You can declare the callback as just taking IEnumerable (no type args), and use reflection to access the fields (ICK!!). Another way would be to declare the callback as "dynamic"... oh... wait... That's not out yet. :) This is another decent example of how dynamic could be used. Some may call it abuse.
Throw this in your utilities library:
```
public static class AsynchronousQueryExecutor
{
public static void Call<T>(IEnumerable<T> query, Action<IEnumerable<T>> callback, Action<Exception> errorCallback)
{
Func<IEnumerable<T>, IEnumerable<T>> func =
new Func<IEnumerable<T>, IEnumerable<T>>(InnerEnumerate<T>);
IEnumerable<T> result = null;
IAsyncResult ar = func.BeginInvoke(
query,
new AsyncCallback(delegate(IAsyncResult arr)
{
try
{
result = ((Func<IEnumerable<T>, IEnumerable<T>>)((AsyncResult)arr).AsyncDelegate).EndInvoke(arr);
}
catch (Exception ex)
{
if (errorCallback != null)
{
errorCallback(ex);
}
return;
}
//errors from inside here are the callbacks problem
//I think it would be confusing to report them
callback(result);
}),
null);
}
private static IEnumerable<T> InnerEnumerate<T>(IEnumerable<T> query)
{
foreach (var item in query) //the method hangs here while the query executes
{
yield return item;
}
}
}
```
And you could use it like this:
```
class Program
{
public static void Main(string[] args)
{
//this could be your linq query
var qry = TestSlowLoadingEnumerable();
//We begin the call and give it our callback delegate
//and a delegate to an error handler
AsynchronousQueryExecutor.Call(qry, HandleResults, HandleError);
Console.WriteLine("Call began on seperate thread, execution continued");
Console.ReadLine();
}
public static void HandleResults(IEnumerable<int> results)
{
//the results are available in here
foreach (var item in results)
{
Console.WriteLine(item);
}
}
public static void HandleError(Exception ex)
{
Console.WriteLine("error");
}
//just a sample lazy loading enumerable
public static IEnumerable<int> TestSlowLoadingEnumerable()
{
Thread.Sleep(5000);
foreach (var i in new int[] { 1, 2, 3, 4, 5, 6 })
{
yield return i;
}
}
}
```
Going to go put this up on my blog now, pretty handy.
|
252,365 |
<p>I'm trying to create a TCP connection and send/read data that uses SSL, but I haven't been able to successfully accomplish this.</p>
<p>What I'd like to do is something like this:</p>
<pre><code> TcpClient _tcpClient = new TcpClient("host", 110);
BinaryReader reader =
new BinaryReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));
Console.WriteLine(reader.ReadString());
</code></pre>
<p>I haven't had any luck with it though. An exception is thrown when creating the BinaryReader.</p>
<p>Does anyone know of a simple example that does this? I'm not interested in writing the server side of this, just the client.</p>
|
[
{
"answer_id": 252372,
"author": "toddk",
"author_id": 17640,
"author_profile": "https://Stackoverflow.com/users/17640",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not entirely sure if this will work for your application but I would recommend taking a look at stunnel:<br />\n<a href=\"http://www.stunnel.org\" rel=\"nofollow noreferrer\">http://www.stunnel.org</a><br/>\n<br />\nI've used it for wrapping existing TCP connections in the past.</p>\n"
},
{
"answer_id": 252389,
"author": "Ovidiu Pacurar",
"author_id": 28419,
"author_profile": "https://Stackoverflow.com/users/28419",
"pm_score": 5,
"selected": true,
"text": "<p>BinaryReader reads primitive data types as binary values in a specific encoding, is that what your server sends?<br>\nIf not use StreamReader:</p>\n\n<pre><code>TcpClient _tcpClient = new TcpClient(\"host\", 110);\n\nStreamReader reader = \n new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));\n\nConsole.WriteLine(reader.ReadToEnd());\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32226/"
] |
I'm trying to create a TCP connection and send/read data that uses SSL, but I haven't been able to successfully accomplish this.
What I'd like to do is something like this:
```
TcpClient _tcpClient = new TcpClient("host", 110);
BinaryReader reader =
new BinaryReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));
Console.WriteLine(reader.ReadString());
```
I haven't had any luck with it though. An exception is thrown when creating the BinaryReader.
Does anyone know of a simple example that does this? I'm not interested in writing the server side of this, just the client.
|
BinaryReader reads primitive data types as binary values in a specific encoding, is that what your server sends?
If not use StreamReader:
```
TcpClient _tcpClient = new TcpClient("host", 110);
StreamReader reader =
new StreamReader(new System.Net.Security.SslStream(_tcpClient.GetStream(), true));
Console.WriteLine(reader.ReadToEnd());
```
|
252,391 |
<p>Currently I have:</p>
<pre><code><system.net>
<mailSettings>
<smtp from="[email protected]">
<network
host="localhost"
port="25"
/>
</smtp>
</mailSettings>
</system.net>
</code></pre>
<p>How can I change it so the email is sent with a name and not the email address only? </p>
|
[
{
"answer_id": 252415,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 7,
"selected": true,
"text": "<p>Well, in code you need to put the sender's name in quotes, followed by the e-mail address.</p>\n\n<pre><code>new SmtpClient(...).Send(\"\\\"John Smith\\\" [email protected]\", ...);\n</code></pre>\n\n<p>And...it looks like you can encode it into the attribute too...</p>\n\n<pre><code><smtp from=\"&quot;John Smith&quot; &lt;[email protected]&gt;\">\n</code></pre>\n"
},
{
"answer_id": 28046831,
"author": "Aakash Dhoundiyal",
"author_id": 2833709,
"author_profile": "https://Stackoverflow.com/users/2833709",
"pm_score": -1,
"selected": false,
"text": "<pre><code><system.net>\n<mailSettings>\n<smtp from =\"XYZ&lt;[email protected]&gt;\">\n<network host=\"smtp.gmail.com\" port=\"25\" userName=\"[email protected]\" password=\"******\" enableSsl=\"true\"/>\n</smtp>\n</mailSettings>\n</system.net>\n</code></pre>\n\n<p>1)Please Use these setting in app.config file</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2385/"
] |
Currently I have:
```
<system.net>
<mailSettings>
<smtp from="[email protected]">
<network
host="localhost"
port="25"
/>
</smtp>
</mailSettings>
</system.net>
```
How can I change it so the email is sent with a name and not the email address only?
|
Well, in code you need to put the sender's name in quotes, followed by the e-mail address.
```
new SmtpClient(...).Send("\"John Smith\" [email protected]", ...);
```
And...it looks like you can encode it into the attribute too...
```
<smtp from=""John Smith" <[email protected]>">
```
|
252,411 |
<p>At the moment I have a console application. I would like to be able to exit the application, update through svn, recompile and then relaunch. This is running under a Linux environment. At the moment I'm not sure how I would be able to relaunch the application. Is there a way to do this?</p>
|
[
{
"answer_id": 252415,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 7,
"selected": true,
"text": "<p>Well, in code you need to put the sender's name in quotes, followed by the e-mail address.</p>\n\n<pre><code>new SmtpClient(...).Send(\"\\\"John Smith\\\" [email protected]\", ...);\n</code></pre>\n\n<p>And...it looks like you can encode it into the attribute too...</p>\n\n<pre><code><smtp from=\"&quot;John Smith&quot; &lt;[email protected]&gt;\">\n</code></pre>\n"
},
{
"answer_id": 28046831,
"author": "Aakash Dhoundiyal",
"author_id": 2833709,
"author_profile": "https://Stackoverflow.com/users/2833709",
"pm_score": -1,
"selected": false,
"text": "<pre><code><system.net>\n<mailSettings>\n<smtp from =\"XYZ&lt;[email protected]&gt;\">\n<network host=\"smtp.gmail.com\" port=\"25\" userName=\"[email protected]\" password=\"******\" enableSsl=\"true\"/>\n</smtp>\n</mailSettings>\n</system.net>\n</code></pre>\n\n<p>1)Please Use these setting in app.config file</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
At the moment I have a console application. I would like to be able to exit the application, update through svn, recompile and then relaunch. This is running under a Linux environment. At the moment I'm not sure how I would be able to relaunch the application. Is there a way to do this?
|
Well, in code you need to put the sender's name in quotes, followed by the e-mail address.
```
new SmtpClient(...).Send("\"John Smith\" [email protected]", ...);
```
And...it looks like you can encode it into the attribute too...
```
<smtp from=""John Smith" <[email protected]>">
```
|
252,417 |
<p>What is the easiest way to use a <code>DLL</code> file from within <code>Python</code>?</p>
<p>Specifically, how can this be done <em>without</em> writing any additional wrapper <code>C++</code> code to expose the functionality to <code>Python</code>?</p>
<p>Native <code>Python</code> functionality is strongly preferred over using a third-party library.</p>
|
[
{
"answer_id": 252438,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 3,
"selected": false,
"text": "<p>ctypes can be used to access dlls, here's a tutorial:</p>\n\n<p><a href=\"http://docs.python.org/library/ctypes.html#module-ctypes\" rel=\"noreferrer\">http://docs.python.org/library/ctypes.html#module-ctypes</a></p>\n"
},
{
"answer_id": 252444,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<p>ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.</p>\n\n<p>I would encourage you to check out <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/python/doc/index.html\" rel=\"nofollow noreferrer\">Boost Python</a>. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) <a href=\"http://www.microsoft.com/express/vc/\" rel=\"nofollow noreferrer\">C++ compiler from Microsoft</a>.</p>\n"
},
{
"answer_id": 252473,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 8,
"selected": true,
"text": "<p>For ease of use, <a href=\"http://docs.python.org/library/ctypes.html\" rel=\"noreferrer\">ctypes</a> is the way to go.</p>\n\n<p>The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.</p>\n\n<pre><code>import ctypes\n\n# Load DLL into memory.\n\nhllDll = ctypes.WinDLL (\"c:\\\\PComm\\\\ehlapi32.dll\")\n\n# Set up prototype and parameters for the desired function call.\n# HLLAPI\n\nhllApiProto = ctypes.WINFUNCTYPE (\n ctypes.c_int, # Return type.\n ctypes.c_void_p, # Parameters 1 ...\n ctypes.c_void_p,\n ctypes.c_void_p,\n ctypes.c_void_p) # ... thru 4.\nhllApiParams = (1, \"p1\", 0), (1, \"p2\", 0), (1, \"p3\",0), (1, \"p4\",0),\n\n# Actually map the call (\"HLLAPI(...)\") to a Python name.\n\nhllApi = hllApiProto ((\"HLLAPI\", hllDll), hllApiParams)\n\n# This is how you can actually call the DLL function.\n# Set up the variables and call the Python name with them.\n\np1 = ctypes.c_int (1)\np2 = ctypes.c_char_p (sessionVar)\np3 = ctypes.c_int (1)\np4 = ctypes.c_int (0)\nhllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))\n</code></pre>\n\n<p>The <code>ctypes</code> stuff has all the C-type data types (<code>int</code>, <code>char</code>, <code>short</code>, <code>void*</code>, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).</p>\n\n<hr>\n\n<p>In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.</p>\n\n<p>All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an <code>int</code> so, while I specify <code>int</code> as the return type, I can safely ignore it) as per IBM's documentation <a href=\"http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm\" rel=\"noreferrer\">here</a>. In other words, the C variant of the function would be:</p>\n\n<pre><code>int hllApi (void *p1, void *p2, void *p3, void *p4)\n</code></pre>\n\n<p>This makes for a single, simple <code>ctypes</code> function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate <code>ctypes</code> function set up per library function.</p>\n\n<p>The return value from <code>WINFUNCTYPE</code> is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in <code>hllApiParams</code> has a parameter \"direction\" (1 = input, 2 = output and so on), a parameter name and a default value - see the <code>ctypes</code> doco for details</p>\n\n<p>Once you have the prototype and parameter information, you can create a Python \"callable\" <code>hllApi</code> with which to call the function. You simply create the needed variable (<code>p1</code> through <code>p4</code> in my case) and call the function with them.</p>\n"
},
{
"answer_id": 3173926,
"author": "atul",
"author_id": 382977,
"author_profile": "https://Stackoverflow.com/users/382977",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://web.archive.org/web/20111006042404/http://www.knowledgetantra.com/component/content/article/2-python/1-call-dll-function-in-python.html\" rel=\"nofollow noreferrer\">This page</a> has a very simple example of calling functions from a DLL file.</p>\n<p>Paraphrasing the details here for completeness:</p>\n<blockquote>\n<p>It's very easy to call a DLL function in Python. I have a self-made DLL file with two functions: <code>add</code> and <code>sub</code> which take two arguments.</p>\n<p><code>add(a, b)</code> returns addition of two numbers<br/>\n<code>sub(a, b)</code> returns substraction of two numbers</p>\n<p>The name of the DLL file will be "demo.dll"</p>\n<p><strong>Program:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>from ctypes import*\n# give location of dll\nmydll = cdll.LoadLibrary("C:\\\\demo.dll")\nresult1= mydll.add(10,1)\nresult2= mydll.sub(10,1)\nprint "Addition value:"+result1\nprint "Substraction:"+result2\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>Addition value:11\nSubstraction:9\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 17157302,
"author": "Carlos Gomez",
"author_id": 2495062,
"author_profile": "https://Stackoverflow.com/users/2495062",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe with <code>Dispatch</code>:</p>\n\n<pre><code>from win32com.client import Dispatch\n\nzk = Dispatch(\"zkemkeeper.ZKEM\") \n</code></pre>\n\n<p>Where zkemkeeper is a registered DLL file on the system...\nAfter that, you can access functions just by calling them:</p>\n\n<pre><code>zk.Connect_Net(IP_address, port)\n</code></pre>\n"
},
{
"answer_id": 55509725,
"author": "Vitality",
"author_id": 1886641,
"author_profile": "https://Stackoverflow.com/users/1886641",
"pm_score": 4,
"selected": false,
"text": "<h1>Building a DLL and linking it under Python using ctypes</h1>\n\n<p>I present a fully worked example on how building a <code>shared library</code> and using it under <code>Python</code> by means of <code>ctypes</code>. I consider the <code>Windows</code> case and deal with <code>DLLs</code>. Two steps are needed:</p>\n\n<ol>\n<li>Build the DLL using Visual Studio's compiler either from the command line or from the IDE;</li>\n<li>Link the DLL under Python using ctypes.</li>\n</ol>\n\n<h2>The shared library</h2>\n\n<p>The <code>shared library</code> I consider is the following and is contained in the <code>testDLL.cpp</code> file. The only function <code>testDLL</code> just receives an <code>int</code> and prints it.</p>\n\n<pre><code>#include <stdio.h>\n\nextern \"C\" {\n\n__declspec(dllexport)\n\nvoid testDLL(const int i) {\n printf(\"%d\\n\", i);\n}\n\n} // extern \"C\"\n</code></pre>\n\n<h2>Building the DLL from the command line</h2>\n\n<p>To build a <code>DLL</code> with <code>Visual Studio</code> from the command line run</p>\n\n<pre><code>\"C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\Tools\\vsdevcmd\"\n</code></pre>\n\n<p>to set the include path and then run</p>\n\n<pre><code>cl.exe /D_USRDLL /D_WINDLL testDLL.cpp /MT /link /DLL /OUT:testDLL.dll\n</code></pre>\n\n<p>to build the DLL.</p>\n\n<h2>Building the <code>DLL</code> from the IDE</h2>\n\n<p>Alternatively, the <code>DLL</code> can be build using <code>Visual Studio</code> as follows:</p>\n\n<ol>\n<li>File -> New -> Project;</li>\n<li>Installed -> Templates -> Visual C++ -> Windows -> Win32 -> Win32Project;</li>\n<li>Next;</li>\n<li>Application type -> DLL;</li>\n<li>Additional options -> Empty project (select);</li>\n<li>Additional options -> Precompiled header (unselect);</li>\n<li>Project -> Properties -> Configuration Manager -> Active solution platform: x64;</li>\n<li>Project -> Properties -> Configuration Manager -> Active solution configuration: Release.</li>\n</ol>\n\n<h2>Linking the DLL under Python</h2>\n\n<p>Under Python, do the following</p>\n\n<pre><code>import os\nimport sys\nfrom ctypes import *\n\nlib = cdll.LoadLibrary('testDLL.dll')\n\nlib.testDLL(3)\n</code></pre>\n"
},
{
"answer_id": 62104617,
"author": "sattva_venu",
"author_id": 5605353,
"author_profile": "https://Stackoverflow.com/users/5605353",
"pm_score": 2,
"selected": false,
"text": "<p>If the DLL is of type COM library, then you can use pythonnet.</p>\n<pre><code>pip install pythonnet\n</code></pre>\n<p>Then in your python code, try the following</p>\n<pre><code>import clr\nclr.AddReference('path_to_your_dll')\n\n# import the namespace and class\n\nfrom Namespace import Class\n\n# create an object of the class\n\nobj = Class()\n\n# access functions return type using object\n\nvalue = obj.Function(<arguments>)\n\n\n</code></pre>\n<p>then instantiate an object as per the class in the DLL, and access the methods within it.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6839/"
] |
What is the easiest way to use a `DLL` file from within `Python`?
Specifically, how can this be done *without* writing any additional wrapper `C++` code to expose the functionality to `Python`?
Native `Python` functionality is strongly preferred over using a third-party library.
|
For ease of use, [ctypes](http://docs.python.org/library/ctypes.html) is the way to go.
The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.
```
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call.
# HLLAPI
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int, # Return type.
ctypes.c_void_p, # Parameters 1 ...
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p) # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),
# Actually map the call ("HLLAPI(...)") to a Python name.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
```
The `ctypes` stuff has all the C-type data types (`int`, `char`, `short`, `void*`, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).
---
In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.
All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an `int` so, while I specify `int` as the return type, I can safely ignore it) as per IBM's documentation [here](http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm). In other words, the C variant of the function would be:
```
int hllApi (void *p1, void *p2, void *p3, void *p4)
```
This makes for a single, simple `ctypes` function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate `ctypes` function set up per library function.
The return value from `WINFUNCTYPE` is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in `hllApiParams` has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the `ctypes` doco for details
Once you have the prototype and parameter information, you can create a Python "callable" `hllApi` with which to call the function. You simply create the needed variable (`p1` through `p4` in my case) and call the function with them.
|
252,459 |
<p>If you have multiple, unrelated projects, is it a good idea to put them in the same repository?</p>
<pre><code>myRepo/projectA/trunk
myRepo/projectA/tags
myRepo/projectA/branches
myRepo/projectB/trunk
myRepo/projectB/tags
myRepo/projectB/branches
</code></pre>
<p>or would you create new repositories for each?</p>
<pre><code>myRepoA/trunk
myRepoA/tags
myRepoA/branches
myRepoB/trunk
myRepoB/tags
myRepoB/branches
</code></pre>
<p>What are the pros and cons of each? All that I can currently think of is that you get mixed revision numbers (so what?), and that you can't use <code>svn:externals</code> unless the repository is actually external. (i think?)</p>
<p>The reason I ask is because I'm considering consolidating my multiple repos into one, since my SVN host has started charging per repo.</p>
|
[
{
"answer_id": 252463,
"author": "Levi Rosol",
"author_id": 23458,
"author_profile": "https://Stackoverflow.com/users/23458",
"pm_score": 1,
"selected": false,
"text": "<p>My suggestion is one. Unless you have different users accessing each one, then I'd say use multiple.</p>\n\n<p>But again, even that's not a good reason to use multiple.</p>\n"
},
{
"answer_id": 252468,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>I would use multiple repositories. In addition to the user access issue, it also makes backup and restore easier. And if you find yourself in a position where somebody wants to pay you for your code (and its history), it's easier to give them just a repository dump.</p>\n\n<p>I would suggest that consolidating repositories just because of the charging policies of your hosting provider is not a very good reason.</p>\n"
},
{
"answer_id": 252472,
"author": "Paul Wicks",
"author_id": 85,
"author_profile": "https://Stackoverflow.com/users/85",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I'd create new repositories for each. It keeps the check out process much simpler and makes administration on the whole easier, at least with regards to user access and backups. Also, it avoids the global version number problem, so the version number is meaningful on all projects.</p>\n\n<p>Really though, you should just use git ;)</p>\n"
},
{
"answer_id": 252475,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "<p>I would create <strong>separate repositories</strong>... Why? The revision numbers and commit messages will just not make any sense if you have a lot of unrelated projects in only one repository, it will be for sure a big mess in short term....</p>\n"
},
{
"answer_id": 252491,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 7,
"selected": true,
"text": "<p>The single vs. multiple issue comes down to personal or organizational preference.</p>\n\n<p>Management of multiple vs. single mainly comes down to access control and maintenance.</p>\n\n<p>Access control for a single repository can be contained in a single file; Multiple repositories are may require multiple files. Maintenance has similar issues - one big backup, or a lot of little backups.</p>\n\n<p>I manage my own. There's one repository, multiple projects, each with its own tags, trunk and branches. If one gets too big or I need to physically isolate a customer's code for their comfort, I can quickly and easily create a new repository.</p>\n\n<p>I recently consulted with a relatively large firm on migrating multiple source code control systems to Subversion. They have ~50 projects, ranging from very small to enterprise applications and their corporate website. Their plan? Start with a single repository, migrate to multiple if necessary. The migration is almost complete and they're still on a single repository, no complaints or issues reported due to it being a single repository.</p>\n\n<p>This isn't a binary, black & white issue. </p>\n\n<p><strong><em>Do what works for you</em></strong> - were I in your position, I'd combine projects into a single repository as fast as I could type the commands, because the cost would be a major consideration in my (very, very small) company.</p>\n\n<p>JFTR: </p>\n\n<p><strong><em>revision numbers</em></strong> in Subversion really have no meaning outside the repository. If you need meaningful names for a revision, <em>create a TAG</em></p>\n\n<p>Commit messages are easily filtered by path in the repository, so reading only those related to a particular project is a trivial exercise.</p>\n\n<hr>\n\n<p>Edit: See <a href=\"https://stackoverflow.com/users/4064/blade\">Blade</a>'s response for details on using a single authorization/authentication configuration for SVN.</p>\n"
},
{
"answer_id": 252549,
"author": "Peter Parker",
"author_id": 23264,
"author_profile": "https://Stackoverflow.com/users/23264",
"pm_score": 5,
"selected": false,
"text": "<p>For your specific case one(1) repository is perfect. You will save a lot of money. I always encourage people to use a single repository. Because it is similar to a single filesystem: <strong>It is easier</strong></p>\n\n<ul>\n<li>You will have a single place where you look for code</li>\n<li>You will have a single authorisation</li>\n<li>You will have a single commit number(ever tried to build a project which is spread over 3 repos?)</li>\n<li>You can better reuse common libraries and track your progress in these libs(svn:externals are PITA and will not solve all problems)</li>\n<li>Projects planned as fully different items, can grow together and share functions and interfaces. This will be very difficult to achieve in multiple repos.</li>\n</ul>\n\n<p>There is a single point for multiple repositories: administration of huge repos is uncomfortable.\nDumping/loading huge repos takes a lot of time. But as you do not do any administration, I think it will not be your concern ;)</p>\n\n<p>SVN scales very well with bigger repositories, there is no slowdown even on huge (>100GB) repositories. </p>\n\n<p>So you will have less hassle with a single repository. <strong>But you really should think about the repo layout!</strong></p>\n"
},
{
"answer_id": 252553,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 3,
"selected": false,
"text": "<p>We use a single repository. My only concern was scale, but after seeing <a href=\"http://svn.apache.org/viewvc/\" rel=\"nofollow noreferrer\">ASF's repository</a> (700k revisions and counting) I was pretty convinced performance would not be an issue. </p>\n\n<p>Our projects are all related, different interlocking modules which form a set of dependencies for any given app. For this reason, a single repository is ideal. You may want seperate trunk/branches/tags for each project, but you're still able to atomically commit a change across your entire codebase within a single revision. This is awesome for refactoring.</p>\n"
},
{
"answer_id": 252586,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": 2,
"selected": false,
"text": "<p>If you plan to or use tool like trac wich integrate with SVN, it makes more sense to use one repo per project.</p>\n"
},
{
"answer_id": 252659,
"author": "mlambie",
"author_id": 17453,
"author_profile": "https://Stackoverflow.com/users/17453",
"pm_score": 3,
"selected": false,
"text": "<p>We are a small software company and we use a single repo for all of our development. The tree looks like this:</p>\n\n<pre><code>/client/<clientname>/<project>/<trunk, branches, tags>\n</code></pre>\n\n<p>The idea was that we would have client and internal work in the same repo, but we ended up having our company as a \"client\" of itself. </p>\n\n<p>This has worked really well for us, and we use Trac to interface to it. Revision numbers are across the whole repo and not specific to one project, but that doesn't phase us.</p>\n"
},
{
"answer_id": 252717,
"author": "Frederic Morin",
"author_id": 4064,
"author_profile": "https://Stackoverflow.com/users/4064",
"pm_score": 3,
"selected": false,
"text": "<p>Be aware that when making your decision, <a href=\"http://www.gentoo-wiki.info/HOWTO_Trac_with_Apache2_SVN_and_multiple_Repositories\" rel=\"noreferrer\">many SVN repos can share the same config file.</a></p>\n\n<p>Example (taken from link above):</p>\n\n<p>In shell:</p>\n\n<pre><code>$ svn-admin create /var/svn/repos1\n$ svn-admin create /var/svn/repos2\n$ svn-admin create /var/svn/repos3\n</code></pre>\n\n<p>File: /var/svn/repos1/conf/svnserve.conf</p>\n\n<pre><code>[general]\nanon-access = none # or read or write\nauth-access = write\npassword-db = /var/svn/conf/passwd\nauthz-db = /var/svn/conf/authz\nrealm = Repos1 SVN Repository\n</code></pre>\n\n<p>File: /var/svn/conf/authz</p>\n\n<pre><code>[groups]\ngroup_repos1_read = user1, user2\ngroup_repos1_write = user3, user4\ngroup_repos2_read = user1, user4\n\n### Global Right for all repositories ###\n[/]\n### Could be a superadmin or something else ###\nuser5 = rw\n\n### Global Rights for one repository (e.g. repos1) ###\n[repos1:/]\n@group_repos1_read = r\n@group_repos1_write = rw\n\n### Repository folder specific rights (e.g. the trunk folder) ###\n[repos1:/trunk]\nuser1 = rw\n\n### And soon for the other repositories ###\n[repos2:/]\n@group_repos2_read = r\nuser3 = rw\n</code></pre>\n"
},
{
"answer_id": 701323,
"author": "Harvey",
"author_id": 47078,
"author_profile": "https://Stackoverflow.com/users/47078",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to Blade's suggestion about sharing files, here is a slightly easier, yet less flexible solution. I setup ours like so:</p>\n\n<ul>\n<li>/var/svn/</li>\n<li>/var/svn/bin</li>\n<li>/var/svn/repository_files</li>\n<li>/var/svn/svnroot</li>\n<li>/var/svn/svnroot/repos1</li>\n<li>/var/svn/svnroot/repos2</li>\n<li>...</li>\n</ul>\n\n<p>In \"bin\", I keep a script called svn-create.sh which will do all of the setup work of creating an empty repository. I also keep the backup script there.</p>\n\n<p>In \"repository_files\", I keep common \"conf\" and \"hooks\" directories that all of the repositories have sym links to. Then, there's only one set of files. This does eliminate the ability to have granular, per-project access without breaking the links, though. That was not a concern where I set this up.</p>\n\n<p>Last, I keep the main directory /var/svn under source control ignoring everything in svnroot. That way the repository files and scripts are under source control as well.</p>\n\n<pre><code>#!/bin/bash\n\n# Usage:\n# svn-create.sh repository_name\n\n# This will:\n# - create a new repository\n# - link the necessary commit scripts\n# - setup permissions\n# - create and commit the initial directory structure\n# - clean up after itself\n\nif [ \"empty\" = ${1}\"empty\" ] ; then\n echo \"Usage:\"\n echo \" ${0} repository_name\"\n exit\nfi\n\nSVN_HOME=/svn\nSVN_ROOT=${SVN_HOME}/svnroot\nSVN_COMMON_FILES=${SVN_HOME}/repository_files\nNEW_DIR=${SVN_ROOT}/${1}\nTMP_DIR=/tmp/${1}_$$\n\necho \"Creating repository: ${1}\"\n\n# Create the repository\nsvnadmin create ${NEW_DIR}\n\n# Copy/Link the hook scripts\ncd ${NEW_DIR}\nrm -rf hooks\nln -s ${SVN_COMMON_FILES}/hooks hooks\n\n# Setup the user configuration\ncd ${NEW_DIR}\nrm -rf conf\nln -s ${SVN_COMMON_FILES}/conf conf\n\n# Checkout the newly created project\nsvn co file://${NEW_DIR} ${TMP_DIR}\n\n# Create the initial directory structure\ncd ${TMP_DIR}\nmkdir trunk\nmkdir tags\nmkdir branches\n\n# Schedule the directories addition to the repository\nsvn add trunk tags branches\n\n# Check in the changes\nsvn ci -m \"Initial Setup\"\n\n# Delete the temporary working copy\ncd /\nrm -rf ${TMP_DIR}\n\n# That's it!\necho \"Repository ${1} created. (most likely)\"\n</code></pre>\n"
},
{
"answer_id": 1877205,
"author": "ofer",
"author_id": 33030,
"author_profile": "https://Stackoverflow.com/users/33030",
"pm_score": 2,
"selected": false,
"text": "<p>one additional thing to consider is the fact that using multiple repositories cause you to loose the ability to have unified logging(svn log command) this alone will be good reason for choosing single repository.</p>\n\n<p>I use TortuiseSvn and found that the \"Show Log\" option is a mandatory tool. although your projects are unrelated, I'm sure that you will find that having a centralized global cross-projects information (paths, bug ids, messages and so on....) is always useful.</p>\n"
},
{
"answer_id": 2951325,
"author": "J.D.",
"author_id": 82934,
"author_profile": "https://Stackoverflow.com/users/82934",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to mlambie's of using a single repo, but went bit further with the folder structure to easily zoom to particular type of projects - web html based projects vs. cs (C#) vs. sql (SQL create/execute scripts) vs. xyz (Domain Specific Languages like afl (AmiBroker Formula Language) or ts (TradeStation)):</p>\n\n<pre><code>/<src|lib>/<app-settings|afl|cs|js|iphone|sql|ts|web>/<ClientName>/<ProjectName>/<branches|tags>\n</code></pre>\n\n<p>Note, I have trunk live within branches as I treat it as the default branch. The only pain sometimes is when you want to quickly create another project you need to build out the ProjectName/branches|tags structure. I use app-settings simply as place to keep specific Apps settings files in repo so easily shareable to others (and substitute ClientName to VendorName and ProjectName to AppName in this folder structure; and the branches|tags can be useful to tag settings across different major versions of vendor products too).</p>\n\n<p>Welcome to any comments on my structure - I recently changed it to this and so far pretty happy but sometimes find it burdensome to maintain branches|tags structures per project - particularly if the project is simply a project setup simply to Unit Test another project.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
If you have multiple, unrelated projects, is it a good idea to put them in the same repository?
```
myRepo/projectA/trunk
myRepo/projectA/tags
myRepo/projectA/branches
myRepo/projectB/trunk
myRepo/projectB/tags
myRepo/projectB/branches
```
or would you create new repositories for each?
```
myRepoA/trunk
myRepoA/tags
myRepoA/branches
myRepoB/trunk
myRepoB/tags
myRepoB/branches
```
What are the pros and cons of each? All that I can currently think of is that you get mixed revision numbers (so what?), and that you can't use `svn:externals` unless the repository is actually external. (i think?)
The reason I ask is because I'm considering consolidating my multiple repos into one, since my SVN host has started charging per repo.
|
The single vs. multiple issue comes down to personal or organizational preference.
Management of multiple vs. single mainly comes down to access control and maintenance.
Access control for a single repository can be contained in a single file; Multiple repositories are may require multiple files. Maintenance has similar issues - one big backup, or a lot of little backups.
I manage my own. There's one repository, multiple projects, each with its own tags, trunk and branches. If one gets too big or I need to physically isolate a customer's code for their comfort, I can quickly and easily create a new repository.
I recently consulted with a relatively large firm on migrating multiple source code control systems to Subversion. They have ~50 projects, ranging from very small to enterprise applications and their corporate website. Their plan? Start with a single repository, migrate to multiple if necessary. The migration is almost complete and they're still on a single repository, no complaints or issues reported due to it being a single repository.
This isn't a binary, black & white issue.
***Do what works for you*** - were I in your position, I'd combine projects into a single repository as fast as I could type the commands, because the cost would be a major consideration in my (very, very small) company.
JFTR:
***revision numbers*** in Subversion really have no meaning outside the repository. If you need meaningful names for a revision, *create a TAG*
Commit messages are easily filtered by path in the repository, so reading only those related to a particular project is a trivial exercise.
---
Edit: See [Blade](https://stackoverflow.com/users/4064/blade)'s response for details on using a single authorization/authentication configuration for SVN.
|
252,464 |
<p>I'm trying to send the output to the console (or colouredconsole) ... which I'm hoping would (also?) go to the Visual Studio's <code>Output</code> window for any ASP.NET web site/app/mvc app.</p>
<p>It doesn't by default, but if I change the target to 'file' then it works for sure.</p>
<p>Can NLog output to the <code>Output</code> window for web apps?</p>
|
[
{
"answer_id": 260576,
"author": "Scott P",
"author_id": 33848,
"author_profile": "https://Stackoverflow.com/users/33848",
"pm_score": 8,
"selected": true,
"text": "<p>You can use this configuration file (nlog.config in the app path):</p>\n<pre><code><?xml version="1.0" encoding="utf-8" ?>\n<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n\n <targets>\n <target name="debugger" xsi:type="Debugger" layout="${logger}::${message}"/>\n </targets>\n\n <rules>\n <logger name="*" minlevel="Trace" writeTo="debugger" />\n </rules>\n</nlog>\n</code></pre>\n<p>See also: <a href=\"https://github.com/NLog/NLog/wiki/Debugger-target\" rel=\"nofollow noreferrer\">https://github.com/NLog/NLog/wiki/Debugger-target</a></p>\n<p>-Scott</p>\n"
},
{
"answer_id": 72901426,
"author": "NickG",
"author_id": 229587,
"author_profile": "https://Stackoverflow.com/users/229587",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to Scott P's answer, you can add a filter for when the environment is not "Development" to prevent any slowdowns in Staging/Production etc.</p>\n<pre><code><logger name="*" minlevel="Trace" writeTo="debugger">\n <filters defaultAction="Ignore">\n <when condition="'${environment:ASPNETCORE_ENVIRONMENT}' == 'Development'" action="Log" />\n </filters>\n</logger>\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
I'm trying to send the output to the console (or colouredconsole) ... which I'm hoping would (also?) go to the Visual Studio's `Output` window for any ASP.NET web site/app/mvc app.
It doesn't by default, but if I change the target to 'file' then it works for sure.
Can NLog output to the `Output` window for web apps?
|
You can use this configuration file (nlog.config in the app path):
```
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="debugger" xsi:type="Debugger" layout="${logger}::${message}"/>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="debugger" />
</rules>
</nlog>
```
See also: <https://github.com/NLog/NLog/wiki/Debugger-target>
-Scott
|
252,489 |
<p>Given a simple switch statement</p>
<pre><code>switch (int)
{
case 1 :
{
printf("1\n");
break;
}
case 2 :
{
printf("2\n");
}
case 3 :
{
printf("3\n");
}
}
</code></pre>
<p>The absence of a break statement in case 2, implies that execution will continue inside the code for case 3.
This is not an accident; it was designed that way. Why was this decisions made? What benefit does this provide vs. having an automatic break semantic for the blocks? What was the rationale?</p>
|
[
{
"answer_id": 252497,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<p>If cases were designed to break implicitly then you couldn't have fallthrough.</p>\n\n<pre><code>case 0:\ncase 1:\ncase 2:\n // all do the same thing.\n break;\ncase 3:\ncase 4:\n // do something different.\n break;\ndefault:\n // something else entirely.\n</code></pre>\n\n<p>If the switch was designed to break out implicitly after every case you wouldn't have a choice about it. The switch-case structure was designed the way it is to be more flexible.</p>\n"
},
{
"answer_id": 252498,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>It eliminates code duplication when several cases need to execute the same code (or the same code in sequence).</p>\n\n<p>Since on the assembly language level it doesn't care whether you break between each one or not there is zero overhead for fall through cases anyways, so why not allow them since they offer significant advantages in certain cases.</p>\n"
},
{
"answer_id": 252500,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 4,
"selected": false,
"text": "<p>The case statements in a switch statements are simply labels.</p>\n\n<p>When you switch on a value, the switch statement essentially does a <em>goto</em> to the label with the matching value.</p>\n\n<p>This means that the break is necessary to avoid passing through to the code under the next label.</p>\n\n<p>As for the reason <em>why</em> it was implemented this way - the fall-through nature of a switch statement can be useful in some scenarios. For example:</p>\n\n<pre><code>case optionA:\n // optionA needs to do its own thing, and also B's thing.\n // Fall-through to optionB afterwards.\n // Its behaviour is a superset of B's.\ncase optionB:\n // optionB needs to do its own thing\n // Its behaviour is a subset of A's.\n break;\ncase optionC:\n // optionC is quite independent so it does its own thing.\n break;\n</code></pre>\n"
},
{
"answer_id": 252501,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 5,
"selected": false,
"text": "<p>To implement Duff's device, obviously:</p>\n\n<pre><code>dsend(to, from, count)\nchar *to, *from;\nint count;\n{\n int n = (count + 7) / 8;\n switch (count % 8) {\n case 0: do { *to = *from++;\n case 7: *to = *from++;\n case 6: *to = *from++;\n case 5: *to = *from++;\n case 4: *to = *from++;\n case 3: *to = *from++;\n case 2: *to = *from++;\n case 1: *to = *from++;\n } while (--n > 0);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 252502,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 5,
"selected": false,
"text": "<p>In a lot of ways c is just a clean interface to standard assembly idioms. When writing jump table driven flow control, the programmer has the choice of falling through or jumping out of the \"control structure\", and a jump out requires an explicit instruction.</p>\n\n<p>So, c does the same thing...</p>\n"
},
{
"answer_id": 252673,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "<p>As many here have specified, it's to allow a single block of code to work for multiple cases. This <strong>should</strong> be a more common occurrence for your switch statements than the \"block of code per case\" you specify in your example.</p>\n\n<p>If you have a block of code per case without fall-through, perhaps you should consider using an if-elseif-else block, as that would seem more appropriate.</p>\n"
},
{
"answer_id": 252733,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 8,
"selected": true,
"text": "<p>Many answers seem to focus on the ability to fall through as the <em>reason</em> for requiring the <code>break</code> statement.</p>\n\n<p>I believe it was simply a mistake, due largely because when C was designed there was not nearly as much experience with how these constructs would be used.</p>\n\n<p>Peter Van der Linden makes the case in his book \"Expert C Programming\":</p>\n\n<blockquote>\n <p>We analyzed the Sun C compiler sources\n to see how often the default fall\n through was used. The Sun ANSI C\n compiler front end has 244 switch\n statements, each of which has an\n average of seven cases. Fall through\n occurs in just 3% of all these cases.</p>\n \n <p>In other words, the normal switch\n behavior is <em>wrong</em> 97% of the time.\n It's not just in a compiler - on the\n contrary, where fall through was used\n in this analysis it was often for\n situations that occur more frequently\n in a compiler than in other software,\n for instance, when compiling operators\n that can have either one or two\n operands:</p>\n\n<pre><code>switch (operator->num_of_operands) {\n case 2: process_operand( operator->operand_2);\n /* FALLTHRU */\n\n case 1: process_operand( operator->operand_1);\n break;\n}\n</code></pre>\n \n <p>Case fall through is so widely\n recognized as a defect that there's\n even a special comment convention,\n shown above, that tells lint \"this is\n really one of those 3% of cases where\n fall through was desired.\"</p>\n</blockquote>\n\n<p>I think it was a good idea for C# to require an explicit jump statement at the end of each case block (while still allowing multiple case labels to be stacked - as long as there's only a single block of statements). In C# you can still have one case fall through to another - you just have to make the fall thru explicit by jumping to the next case using a <code>goto</code>.</p>\n\n<p>It's too bad Java didn't take the opportunity to break from the C semantics.</p>\n"
},
{
"answer_id": 4169724,
"author": "R.. GitHub STOP HELPING ICE",
"author_id": 379897,
"author_profile": "https://Stackoverflow.com/users/379897",
"pm_score": 3,
"selected": false,
"text": "<p>To allow things like:</p>\n\n<pre><code>switch(foo) {\ncase 1:\n /* stuff for case 1 only */\n if (0) {\ncase 2:\n /* stuff for case 2 only */\n }\n /* stuff for cases 1 and 2 */\ncase 3:\n /* stuff for cases 1, 2, and 3 */\n}\n</code></pre>\n\n<p>Think of the <code>case</code> keyword as a <code>goto</code> label and it comes a lot more naturally.</p>\n"
},
{
"answer_id": 51839034,
"author": "Martti K",
"author_id": 9126440,
"author_profile": "https://Stackoverflow.com/users/9126440",
"pm_score": 2,
"selected": false,
"text": "<p>I happened to run in to a case of assigning values in vectors to structs: it had to be done in such a manner that if the data vector was shorter than the number of data members in the struct, the rest of the members would remain in their default value. In that case omitting <code>break</code> was quite useful.</p>\n\n<pre><code>switch (nShorts)\n{\ncase 4: frame.leadV1 = shortArray[3];\ncase 3: frame.leadIII = shortArray[2];\ncase 2: frame.leadII = shortArray[1];\ncase 1: frame.leadI = shortArray[0]; break;\ndefault: TS_ASSERT(false);\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7734/"
] |
Given a simple switch statement
```
switch (int)
{
case 1 :
{
printf("1\n");
break;
}
case 2 :
{
printf("2\n");
}
case 3 :
{
printf("3\n");
}
}
```
The absence of a break statement in case 2, implies that execution will continue inside the code for case 3.
This is not an accident; it was designed that way. Why was this decisions made? What benefit does this provide vs. having an automatic break semantic for the blocks? What was the rationale?
|
Many answers seem to focus on the ability to fall through as the *reason* for requiring the `break` statement.
I believe it was simply a mistake, due largely because when C was designed there was not nearly as much experience with how these constructs would be used.
Peter Van der Linden makes the case in his book "Expert C Programming":
>
> We analyzed the Sun C compiler sources
> to see how often the default fall
> through was used. The Sun ANSI C
> compiler front end has 244 switch
> statements, each of which has an
> average of seven cases. Fall through
> occurs in just 3% of all these cases.
>
>
> In other words, the normal switch
> behavior is *wrong* 97% of the time.
> It's not just in a compiler - on the
> contrary, where fall through was used
> in this analysis it was often for
> situations that occur more frequently
> in a compiler than in other software,
> for instance, when compiling operators
> that can have either one or two
> operands:
>
>
>
> ```
> switch (operator->num_of_operands) {
> case 2: process_operand( operator->operand_2);
> /* FALLTHRU */
>
> case 1: process_operand( operator->operand_1);
> break;
> }
>
> ```
>
> Case fall through is so widely
> recognized as a defect that there's
> even a special comment convention,
> shown above, that tells lint "this is
> really one of those 3% of cases where
> fall through was desired."
>
>
>
I think it was a good idea for C# to require an explicit jump statement at the end of each case block (while still allowing multiple case labels to be stacked - as long as there's only a single block of statements). In C# you can still have one case fall through to another - you just have to make the fall thru explicit by jumping to the next case using a `goto`.
It's too bad Java didn't take the opportunity to break from the C semantics.
|
252,506 |
<p>I am having a great deal of trouble getting named queries to work with nHibernate. My latest problem is getting the error message "could not execute query" with no additional information. Are there any complete examples I can download from somewhere because all the tutorials and documentation examples provide code snippits but only tell half the story about getting it to work.</p>
<p>Here is the code that is giving me problems.</p>
<p><strong>Class</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model.Entities
{
public class TableInfo
{
public string TABLENAME { get; set; }
public string COLUMNNAME { get; set; }
#region Overrides
public override int GetHashCode()
{
int result = TABLENAME.GetHashCode();
result += COLUMNNAME.GetHashCode();
return result;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
TableInfo dict = (TableInfo)obj;
return
dict.TABLENAME.IsEqual(this.TABLENAME) &&
dict.COLUMNNAME.IsEqual(this.COLUMNNAME);
}
#endregion
}
}
</code></pre>
<p><strong>Mapping File</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" assembly="Model" default-lazy="false">
<class name="Model.Entities.TableInfo, Model" table="UIM_TableColumnInfo">
<composite-id>
<key-property name="TABLENAME" column="TABLENAME" type="string"></key-property>
<key-property name="COLUMNNAME" column="COLUMNNAME" type="string"></key-property>
</composite-id>
</class>
<sql-query name="GetTableInfo">
<return alias="tableInfo" class="Model.Entities.TableInfo, Model">
<return-property name="TABLENAME" column="TABLENAME"/>
<return-property name="COLUMNNAME" column="COLUMNNAME"/>
</return>
<![CDATA[
select
info.tci_table_name TABLENAME
, info.tci_column_name COLUMNNAME
from ALL_TAB_COLS c
,( select 'DATE' TYPE_NAME, 'D' data_type_ind from dual
union select 'NUMBER','N' from dual
union select 'VARCHAR2','S' from dual
) ct
, UIM_TableColumnInfo info
where c.DATA_TYPE = ct.TYPE_NAME (+)
and c.column_id is not null
and UPPER(c.TABLE_NAME) = :TableName
and UPPER(c.COLUMN_NAME) = UPPER(info.tci_column_name (+))
order by c.column_id
]]>
</sql-query>
</hibernate-mapping>
</code></pre>
<p><strong>Calling Code</strong></p>
<pre><code>public List<TableInfo> GetTableInfo(string tableName)
{
return m_TableInfoRepository
.NamedQuery("GetTableInfo")
.SetString("TableName", tableName)
.List<TableInfo>() as List<TableInfo>;
}
</code></pre>
|
[
{
"answer_id": 252541,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe I'm wrong but it seems that could be a conflict between the table \"TABLENAME\" and the parameter \":TableName\", what happens if you try to use another parameter name? </p>\n"
},
{
"answer_id": 253828,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 2,
"selected": false,
"text": "<p>I assume that you have tested before the SQL in your client database, so I think that maybe we should see what is happening inside, so I can recommend you this links;</p>\n\n<ol>\n<li><a href=\"http://forum.hibernate.org/viewtopic.php?t=938710&sid=f457c1ab5873b97794203503d750567e\" rel=\"nofollow noreferrer\">Named Query Error</a></li>\n<li><a href=\"http://www.beansoftware.com/asp.net-tutorials/nhibernate-log4net.aspx\" rel=\"nofollow noreferrer\">Using NHibernate and Log4Net in ASP.NET 2.0 applications</a></li>\n<li><a href=\"https://stackoverflow.com/questions/129133/how-do-i-view-the-sql-that-is-generated-by-nhibernate\">How do I view the SQL that is generated by nHibernate?</a> </li>\n</ol>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 5778578,
"author": "Nick Harrison",
"author_id": 481856,
"author_profile": "https://Stackoverflow.com/users/481856",
"pm_score": 0,
"selected": false,
"text": "<p>The inner exception should provide the actual sql that was generated and tried to run. Paste this into a database query and run it directly in the database. This will help guide you. It will be a lot easier once you know why the SQL could not be executed </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27294/"
] |
I am having a great deal of trouble getting named queries to work with nHibernate. My latest problem is getting the error message "could not execute query" with no additional information. Are there any complete examples I can download from somewhere because all the tutorials and documentation examples provide code snippits but only tell half the story about getting it to work.
Here is the code that is giving me problems.
**Class**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model.Entities
{
public class TableInfo
{
public string TABLENAME { get; set; }
public string COLUMNNAME { get; set; }
#region Overrides
public override int GetHashCode()
{
int result = TABLENAME.GetHashCode();
result += COLUMNNAME.GetHashCode();
return result;
}
public override bool Equals(object obj)
{
if (obj == null) return false;
TableInfo dict = (TableInfo)obj;
return
dict.TABLENAME.IsEqual(this.TABLENAME) &&
dict.COLUMNNAME.IsEqual(this.COLUMNNAME);
}
#endregion
}
}
```
**Mapping File**
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" assembly="Model" default-lazy="false">
<class name="Model.Entities.TableInfo, Model" table="UIM_TableColumnInfo">
<composite-id>
<key-property name="TABLENAME" column="TABLENAME" type="string"></key-property>
<key-property name="COLUMNNAME" column="COLUMNNAME" type="string"></key-property>
</composite-id>
</class>
<sql-query name="GetTableInfo">
<return alias="tableInfo" class="Model.Entities.TableInfo, Model">
<return-property name="TABLENAME" column="TABLENAME"/>
<return-property name="COLUMNNAME" column="COLUMNNAME"/>
</return>
<![CDATA[
select
info.tci_table_name TABLENAME
, info.tci_column_name COLUMNNAME
from ALL_TAB_COLS c
,( select 'DATE' TYPE_NAME, 'D' data_type_ind from dual
union select 'NUMBER','N' from dual
union select 'VARCHAR2','S' from dual
) ct
, UIM_TableColumnInfo info
where c.DATA_TYPE = ct.TYPE_NAME (+)
and c.column_id is not null
and UPPER(c.TABLE_NAME) = :TableName
and UPPER(c.COLUMN_NAME) = UPPER(info.tci_column_name (+))
order by c.column_id
]]>
</sql-query>
</hibernate-mapping>
```
**Calling Code**
```
public List<TableInfo> GetTableInfo(string tableName)
{
return m_TableInfoRepository
.NamedQuery("GetTableInfo")
.SetString("TableName", tableName)
.List<TableInfo>() as List<TableInfo>;
}
```
|
I assume that you have tested before the SQL in your client database, so I think that maybe we should see what is happening inside, so I can recommend you this links;
1. [Named Query Error](http://forum.hibernate.org/viewtopic.php?t=938710&sid=f457c1ab5873b97794203503d750567e)
2. [Using NHibernate and Log4Net in ASP.NET 2.0 applications](http://www.beansoftware.com/asp.net-tutorials/nhibernate-log4net.aspx)
3. [How do I view the SQL that is generated by nHibernate?](https://stackoverflow.com/questions/129133/how-do-i-view-the-sql-that-is-generated-by-nhibernate)
Hope it helps.
|
252,515 |
<p>This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the <code>delete</code> operator (without brackets) works even with the <code>new[]</code> operator.</p>
<p>In my opinion, writing this:</p>
<pre><code>int* p = new int;
</code></pre>
<p>should be equivalent to allocating an array of 1 element:</p>
<pre><code>int* p = new int[1];
</code></pre>
<p>If this was true, the <code>delete</code> operator could always be deleting arrays, and we wouldn't need the <code>delete[]</code> operator.</p>
<p>Is there any reason why the <code>delete[]</code> operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing <code>delete</code> vs <code>delete[]</code> was a small memory optimization.</p>
|
[
{
"answer_id": 252518,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 6,
"selected": true,
"text": "<p>It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.</p>\n\n<p>Now, your question is, why not make <code>new</code> and <code>delete</code> behave like <code>new[]</code> and <code>delete[]</code> and get rid of <code>new[]</code> and <code>delete[]</code>? I would go back Stroustrup's \"Design and Evolution\" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a <code>new</code> or <code>delete</code> will behave as efficiently as <code>malloc</code> and <code>free</code>. If <code>delete</code> had the <code>delete[]</code> meaning, there would be some extra overhead at run time (as James Curran pointed out).</p>\n"
},
{
"answer_id": 252521,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 2,
"selected": false,
"text": "<p><code>delete []</code> ensures that the destructor of each member is called (if applicable to the type) while <code>delete</code> just deletes the memory allocated for the array.</p>\n\n<p>Here's a good read: <a href=\"http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=287\" rel=\"nofollow noreferrer\">http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=287</a></p>\n\n<p><del>And no, array sizes are not stored anywhere in C++.</del> (Thanks everyone for pointing out that this statement is inaccurate.)</p>\n"
},
{
"answer_id": 252524,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 2,
"selected": false,
"text": "<p>Marshall Cline has some <a href=\"http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13\" rel=\"nofollow noreferrer\">info on this topic</a>.</p>\n"
},
{
"answer_id": 252623,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<p>Since everyone else seems to have missed the point of your question, I'll just add that I had the same thought some year ago, and have never been able to get an answer.</p>\n\n<p>The only thing I can think of is that there's a very tiny bit of extra overhead to treat a single object as an array (an unnecessary \"<code>for(int i=0; i<1; ++i)</code>\" )</p>\n"
},
{
"answer_id": 252830,
"author": "Malkocoglu",
"author_id": 31152,
"author_profile": "https://Stackoverflow.com/users/31152",
"pm_score": 3,
"selected": false,
"text": "<p>Damn, I missed the whole point of question but I will leave my original answer as a sidenote. Why we have <code>delete[]</code> is because long time ago we had <code>delete[cnt]</code>, even today if you write <code>delete[9]</code> or <code>delete[cnt]</code>, the compiler just ignores the thing between <code>[]</code> but compiles OK. At that time, C++ was first processed by a front-end and then fed to an ordinary C compiler. They could not do the trick of storing the count somewhere beneath the curtain, maybe they could not even think of it at that time. And for backward compatibility, the compilers most probably used the value given between the <code>[]</code> as the count of array, if there is no such value then they got the count from the prefix, so it worked both ways. Later on, we typed nothing between <code>[]</code> and everything worked. Today, I do not think <code>delete[]</code> is necessary but the implementations demand it that way.</p>\n\n<p>My original answer (that misses the point):</p>\n\n<p><code>delete</code> deletes a single object. <code>delete[]</code> deletes an object array. For <code>delete[]</code> to work, the implementation keeps the number of elements in the array. I just double-checked this by debugging ASM code. In the implementation (VS2005) I tested, the count was stored as a prefix to the object array.</p>\n\n<p>If you use <code>delete[]</code> on a single object, the count variable is garbage so the code crashes. If you use <code>delete</code> for an object array, because of some inconsistency, the code crashes. I tested these cases just now !</p>\n\n<p>\"<code>delete</code> just deletes the memory allocated for the array.\" statement in another answer is not right. If the object is a class, <code>delete</code> will call the DTOR. Just place a breakpoint int the DTOR code and <code>delete</code> the object, the breakpoint will hit.</p>\n\n<p>What occurred to me is that, if the compiler & libraries assumed that all the objects allocated by <code>new</code> are object arrays, it would be OK to call <code>delete</code> for single objects or object arrays. Single objects just would be the special case of an object array having a count of 1. Maybe there is something I am missing, anyway.</p>\n"
},
{
"answer_id": 254862,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 3,
"selected": false,
"text": "<p>Adding this since no other answer currently addresses it:</p>\n\n<p>Array <code>delete[]</code> cannot be used on a pointer-to-base class ever -- while the compiler stores the count of objects when you invoke <code>new[]</code>, it doesn't store the types or sizes of the objects (as David pointed out, in C++ you rarely pay for a feature you're not using). However, scalar <code>delete</code> can safely delete through base class, so it's used both for normal object cleanup and polymorphic cleanup:</p>\n\n<pre><code>struct Base { virtual ~Base(); };\nstruct Derived : Base { };\nint main(){\n Base* b = new Derived;\n delete b; // this is good\n\n Base* b = new Derived[2];\n delete[] b; // bad! undefined behavior\n}\n</code></pre>\n\n<p>However, in the opposite case -- non-virtual destructor -- scalar <code>delete</code> should be as cheap as possible -- it should not check for number of objects, nor for the type of object being deleted. This makes delete on a built-in type or plain-old-data type very cheap, as the compiler need only invoke <code>::operator delete</code> and nothing else:</p>\n\n<pre><code>int main(){\n int * p = new int;\n delete p; // cheap operation, no dynamic dispatch, no conditional branching\n}\n</code></pre>\n\n<p>While not an exhaustive treatment of memory allocation, I hope this helps clarify the breadth of memory management options available in C++.</p>\n"
},
{
"answer_id": 20378501,
"author": "David E.",
"author_id": 438085,
"author_profile": "https://Stackoverflow.com/users/438085",
"pm_score": 1,
"selected": false,
"text": "<p>I'm a bit confused by Aaron's answer and frankly admit I don't completely understand why and where <code>delete[]</code> is needed.</p>\n\n<p>I did some experiments with his sample code (after fixing a few typos). Here are my results.\n Typos:<code>~Base</code> needed a function body\n <code>Base *b</code> was declared twice</p>\n\n<pre><code>struct Base { virtual ~Base(){ }>; };\nstruct Derived : Base { };\nint main(){\nBase* b = new Derived;\ndelete b; // this is good\n\n<strike>Base</strike> b = new Derived[2];\ndelete[] b; // bad! undefined behavior\n}\n</code></pre>\n\n<p>Compilation and execution</p>\n\n<pre><code>david@Godel:g++ -o atest atest.cpp \ndavid@Godel: ./atest \ndavid@Godel: # No error message\n</code></pre>\n\n<p>Modified program with <code>delete[]</code> removed</p>\n\n<pre><code>struct Base { virtual ~Base(){}; };\nstruct Derived : Base { };\n\nint main(){\n Base* b = new Derived;\n delete b; // this is good\n\n b = new Derived[2];\n delete b; // bad! undefined behavior\n}\n</code></pre>\n\n<p>Compilation and execution</p>\n\n<pre><code>david@Godel:g++ -o atest atest.cpp \ndavid@Godel: ./atest \natest(30746) malloc: *** error for object 0x1099008c8: pointer being freed was n\not allocated\n*** set a breakpoint in malloc_error_break to debug\nAbort trap: 6\n</code></pre>\n\n<p>Of course, I don't know if <code>delete[] b</code> is actually working in the first example; I only know it does not give a compiler error message.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9936/"
] |
This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the `delete` operator (without brackets) works even with the `new[]` operator.
In my opinion, writing this:
```
int* p = new int;
```
should be equivalent to allocating an array of 1 element:
```
int* p = new int[1];
```
If this was true, the `delete` operator could always be deleting arrays, and we wouldn't need the `delete[]` operator.
Is there any reason why the `delete[]` operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing `delete` vs `delete[]` was a small memory optimization.
|
It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.
Now, your question is, why not make `new` and `delete` behave like `new[]` and `delete[]` and get rid of `new[]` and `delete[]`? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a `new` or `delete` will behave as efficiently as `malloc` and `free`. If `delete` had the `delete[]` meaning, there would be some extra overhead at run time (as James Curran pointed out).
|
252,517 |
<p>I'm using c#, and have an open tcpip connection receiving data. Is it possible to save the stream to an ms sql server database as I'm receiving it, instead of receiving all the data then saving it all? If the stream could be sent to the database as it's being received, you wouldn't have to keep the entire chunk of data in memory. Is this at all possible?</p>
|
[
{
"answer_id": 252526,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "<p>Are you writing to the DB as a BLOB, or translating the data in some form, then executing inserts for each row?</p>\n\n<p>Your answer in the comments has me confused. Writing a stream to a BLOB column is vastly different then getting the data then translating it into inserts for separate rows.</p>\n\n<p>Regardless, streaming into a BLOB column is possible by first creating the row with the blob column that you need to insert into, the repeatedly calling an update statement:</p>\n\n<pre><code>update myTable set myColumn.Write(@data, @offset, @length) where someid = @someId\n</code></pre>\n\n<p>for chunks of bytes from the stream.</p>\n\n<p><a href=\"http://weblogs.asp.net/alessandro/archive/2008/09/22/conserving-resources-when-writing-blob-values-to-sql-server-and-streaming-blob-values-back-to-the-client.aspx\" rel=\"nofollow noreferrer\">Perfect example located here.</a></p>\n"
},
{
"answer_id": 252934,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "<p>SQL Server 2005 supports HTTP endpoints (without requiring IIS) so one solution would be to create a web service on SQL Server to directly receive the streamed data.</p>\n\n<p>These links explain setting one up:\n<a href=\"http://codebetter.com/blogs/raymond.lewallen/archive/2005/06/23/65089.aspx\" rel=\"nofollow noreferrer\">http://codebetter.com/blogs/raymond.lewallen/archive/2005/06/23/65089.aspx</a>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms345123.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms345123.aspx</a></p>\n"
},
{
"answer_id": 252973,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/314e7e3782e59a93\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/fcd173f1db2951f1\" rel=\"nofollow noreferrer\">here</a> for exmaples of working with streams and databases. Essentially, you need to pass repeated buffers (ideally of multiples of 8040 bytes in SQL Server). Note that the examples are based on SQL 2000; with SQL 2005, varbinary(max) would be easier. Very similar, though.</p>\n"
},
{
"answer_id": 256465,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just write the buffer to a file as you receive packets, then insert to the database when the transfer is complete? </p>\n\n<p>If you stream directly to the database, you'll be holding a connection to the database open a long time, especially if the client's network connection isn't the best.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9266/"
] |
I'm using c#, and have an open tcpip connection receiving data. Is it possible to save the stream to an ms sql server database as I'm receiving it, instead of receiving all the data then saving it all? If the stream could be sent to the database as it's being received, you wouldn't have to keep the entire chunk of data in memory. Is this at all possible?
|
Are you writing to the DB as a BLOB, or translating the data in some form, then executing inserts for each row?
Your answer in the comments has me confused. Writing a stream to a BLOB column is vastly different then getting the data then translating it into inserts for separate rows.
Regardless, streaming into a BLOB column is possible by first creating the row with the blob column that you need to insert into, the repeatedly calling an update statement:
```
update myTable set myColumn.Write(@data, @offset, @length) where someid = @someId
```
for chunks of bytes from the stream.
[Perfect example located here.](http://weblogs.asp.net/alessandro/archive/2008/09/22/conserving-resources-when-writing-blob-values-to-sql-server-and-streaming-blob-values-back-to-the-client.aspx)
|
252,519 |
<p>How can I calculate the number of work days between two dates in SQL Server? </p>
<p>Monday to Friday and it must be T-SQL.</p>
|
[
{
"answer_id": 252532,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 5,
"selected": false,
"text": "<p>In <em><a href=\"http://www.sqlservercentral.com/articles/Advanced+Querying/calculatingworkdays/1660/\" rel=\"noreferrer\">Calculating Work Days</a></em> you can find a good article about this subject, but as you can see it is not that advanced.</p>\n\n<pre><code>--Changing current database to the Master database allows function to be shared by everyone.\nUSE MASTER\nGO\n--If the function already exists, drop it.\nIF EXISTS\n(\n SELECT *\n FROM dbo.SYSOBJECTS\n WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')\n AND XType IN (N'FN', N'IF', N'TF')\n)\nDROP FUNCTION [dbo].[fn_WorkDays]\nGO\n CREATE FUNCTION dbo.fn_WorkDays\n--Presets\n--Define the input parameters (OK if reversed by mistake).\n(\n @StartDate DATETIME,\n @EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed\n)\n\n--Define the output data type.\nRETURNS INT\n\nAS\n--Calculate the RETURN of the function.\nBEGIN\n --Declare local variables\n --Temporarily holds @EndDate during date reversal.\n DECLARE @Swap DATETIME\n\n --If the Start Date is null, return a NULL and exit.\n IF @StartDate IS NULL\n RETURN NULL\n\n --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).\n IF @EndDate IS NULL\n SELECT @EndDate = @StartDate\n\n --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.\n --Usually faster than CONVERT.\n --0 is a date (01/01/1900 00:00:00.000)\n SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),\n @EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)\n\n --If the inputs are in the wrong order, reverse them.\n IF @StartDate > @EndDate\n SELECT @Swap = @EndDate,\n @EndDate = @StartDate,\n @StartDate = @Swap\n\n --Calculate and return the number of workdays using the input parameters.\n --This is the meat of the function.\n --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.\n RETURN (\n SELECT\n --Start with total number of days including weekends\n (DATEDIFF(dd,@StartDate, @EndDate)+1)\n --Subtact 2 days for each full weekend\n -(DATEDIFF(wk,@StartDate, @EndDate)*2)\n --If StartDate is a Sunday, Subtract 1\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'\n THEN 1\n ELSE 0\n END)\n --If EndDate is a Saturday, Subtract 1\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'\n THEN 1\n ELSE 0\n END)\n )\n END\nGO\n</code></pre>\n\n<p>If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.</p>\n"
},
{
"answer_id": 252533,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 9,
"selected": true,
"text": "<p>For workdays, Monday to Friday, you can do it with a single SELECT, like this:</p>\n\n<pre><code>DECLARE @StartDate DATETIME\nDECLARE @EndDate DATETIME\nSET @StartDate = '2008/10/01'\nSET @EndDate = '2008/10/31'\n\n\nSELECT\n (DATEDIFF(dd, @StartDate, @EndDate) + 1)\n -(DATEDIFF(wk, @StartDate, @EndDate) * 2)\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n</code></pre>\n\n<p>If you want to include holidays, you have to work it out a bit...</p>\n"
},
{
"answer_id": 2416297,
"author": "Muthuvel",
"author_id": 290422,
"author_profile": "https://Stackoverflow.com/users/290422",
"pm_score": 3,
"selected": false,
"text": "<pre><code> DECLARE @TotalDays INT,@WorkDays INT\n DECLARE @ReducedDayswithEndDate INT\n DECLARE @WeekPart INT\n DECLARE @DatePart INT\n\n SET @TotalDays= DATEDIFF(day, @StartDate, @EndDate) +1\n SELECT @ReducedDayswithEndDate = CASE DATENAME(weekday, @EndDate)\n WHEN 'Saturday' THEN 1\n WHEN 'Sunday' THEN 2\n ELSE 0 END \n SET @TotalDays=@TotalDays-@ReducedDayswithEndDate\n SET @WeekPart=@TotalDays/7;\n SET @DatePart=@TotalDays%7;\n SET @WorkDays=(@WeekPart*5)+@DatePart\n\n RETURN @WorkDays\n</code></pre>\n"
},
{
"answer_id": 2416322,
"author": "Muthuvel",
"author_id": 290422,
"author_profile": "https://Stackoverflow.com/users/290422",
"pm_score": 1,
"selected": false,
"text": "<pre><code>DECLARE @StartDate datetime,@EndDate datetime\n\nselect @StartDate='3/2/2010', @EndDate='3/7/2010'\n\nDECLARE @TotalDays INT,@WorkDays INT\n\nDECLARE @ReducedDayswithEndDate INT\n\nDECLARE @WeekPart INT\n\nDECLARE @DatePart INT\n\nSET @TotalDays= DATEDIFF(day, @StartDate, @EndDate) +1\n\nSELECT @ReducedDayswithEndDate = CASE DATENAME(weekday, @EndDate)\n WHEN 'Saturday' THEN 1\n WHEN 'Sunday' THEN 2\n ELSE 0 END\n\nSET @TotalDays=@TotalDays-@ReducedDayswithEndDate\n\nSET @WeekPart=@TotalDays/7;\n\nSET @DatePart=@TotalDays%7;\n\nSET @WorkDays=(@WeekPart*5)+@DatePart\n\nSELECT @WorkDays\n</code></pre>\n"
},
{
"answer_id": 5109908,
"author": "Carter Cole",
"author_id": 180434,
"author_profile": "https://Stackoverflow.com/users/180434",
"pm_score": 3,
"selected": false,
"text": "<p>My version of the accepted answer as a function using <code>DATEPART</code>, so I don't have to do a string comparison on the line with </p>\n\n<pre><code>DATENAME(dw, @StartDate) = 'Sunday'\n</code></pre>\n\n<p>Anyway, here's my business datediff function</p>\n\n<pre><code>SET ANSI_NULLS ON\nGO\nSET QUOTED_IDENTIFIER ON\nGO\n\nCREATE FUNCTION BDATEDIFF\n(\n @startdate as DATETIME,\n @enddate as DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @res int\n\nSET @res = (DATEDIFF(dd, @startdate, @enddate) + 1)\n -(DATEDIFF(wk, @startdate, @enddate) * 2)\n -(CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END)\n -(CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END)\n\n RETURN @res\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 9124292,
"author": "bel",
"author_id": 1186819,
"author_profile": "https://Stackoverflow.com/users/1186819",
"pm_score": 1,
"selected": false,
"text": "<pre><code>CREATE FUNCTION x\n(\n @StartDate DATETIME,\n @EndDate DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @Teller INT\n\n SET @StartDate = DATEADD(dd,1,@StartDate)\n\n SET @Teller = 0\n IF DATEDIFF(dd,@StartDate,@EndDate) <= 0\n BEGIN\n SET @Teller = 0 \n END\n ELSE\n BEGIN\n WHILE\n DATEDIFF(dd,@StartDate,@EndDate) >= 0\n BEGIN\n IF DATEPART(dw,@StartDate) < 6\n BEGIN\n SET @Teller = @Teller + 1\n END\n SET @StartDate = DATEADD(dd,1,@StartDate)\n END\n END\n RETURN @Teller\nEND\n</code></pre>\n"
},
{
"answer_id": 9228962,
"author": "phareim",
"author_id": 373975,
"author_profile": "https://Stackoverflow.com/users/373975",
"pm_score": 3,
"selected": false,
"text": "<p><em>(I'm a few points shy of commenting privileges)</em></p>\n\n<p>If you decide to forgo the +1 day in <a href=\"https://stackoverflow.com/a/252533/373975\">CMS's elegant solution</a>, note that if your start date and end date are in the same weekend, you get a negative answer. Ie., 2008/10/26 to 2008/10/26 returns -1.</p>\n\n<p>my rather simplistic solution:</p>\n\n<pre><code>select @Result = (..CMS's answer..)\nif (@Result < 0)\n select @Result = 0\n RETURN @Result\n</code></pre>\n\n<p>.. which also sets all erroneous posts with <em>start date</em> after <em>end date</em> to zero. Something you may or may not be looking for.</p>\n"
},
{
"answer_id": 12898069,
"author": "joaopintocruz",
"author_id": 1139347,
"author_profile": "https://Stackoverflow.com/users/1139347",
"pm_score": 3,
"selected": false,
"text": "<p>For difference between dates including holidays I went this way:</p>\n\n<p>1) Table with Holidays:</p>\n\n<pre><code> CREATE TABLE [dbo].[Holiday](\n[Id] [int] IDENTITY(1,1) NOT NULL,\n[Name] [nvarchar](50) NULL,\n[Date] [datetime] NOT NULL)\n</code></pre>\n\n<p>2) I had my plannings Table like this and wanted to fill column Work_Days which was empty:</p>\n\n<pre><code> CREATE TABLE [dbo].[Plan_Phase](\n[Id] [int] IDENTITY(1,1) NOT NULL,\n[Id_Plan] [int] NOT NULL,\n[Id_Phase] [int] NOT NULL,\n[Start_Date] [datetime] NULL,\n[End_Date] [datetime] NULL,\n[Work_Days] [int] NULL)\n</code></pre>\n\n<p>3) So in order to get \"Work_Days\" to later fill in my column just had to:</p>\n\n<pre><code>SELECT Start_Date, End_Date,\n (DATEDIFF(dd, Start_Date, End_Date) + 1)\n-(DATEDIFF(wk, Start_Date, End_Date) * 2)\n-(SELECT COUNT(*) From Holiday Where Date >= Start_Date AND Date <= End_Date)\n-(CASE WHEN DATENAME(dw, Start_Date) = 'Sunday' THEN 1 ELSE 0 END)\n-(CASE WHEN DATENAME(dw, End_Date) = 'Saturday' THEN 1 ELSE 0 END)\n-(CASE WHEN (SELECT COUNT(*) From Holiday Where Start_Date = Date) > 0 THEN 1 ELSE 0 END)\n-(CASE WHEN (SELECT COUNT(*) From Holiday Where End_Date = Date) > 0 THEN 1 ELSE 0 END) AS Work_Days\nfrom Plan_Phase\n</code></pre>\n\n<p>Hope that I could help.</p>\n\n<p>Cheers</p>\n"
},
{
"answer_id": 14653545,
"author": "RobertD",
"author_id": 2033691,
"author_profile": "https://Stackoverflow.com/users/2033691",
"pm_score": 1,
"selected": false,
"text": "<p>I took the various examples here, but in my particular situation we have a @PromisedDate for delivery and a @ReceivedDate for the actual receipt of the item. When an item was received before the \"PromisedDate\" the calculations were not totaling correctly unless I ordered the dates passed into the function by calendar order. Not wanting to check the dates every time, I changed the function to handle this for me.</p>\n\n<pre><code>Create FUNCTION [dbo].[fnGetBusinessDays]\n(\n @PromiseDate date,\n @ReceivedDate date\n)\nRETURNS integer\nAS\nBEGIN\n DECLARE @days integer\n\n SELECT @days = \n Case when @PromiseDate > @ReceivedDate Then\n DATEDIFF(d,@PromiseDate,@ReceivedDate) + \n ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 +\n CASE \n WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1 \n WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1 \n ELSE 0\n END +\n (Select COUNT(*) FROM CompanyHolidays \n WHERE HolidayDate BETWEEN @ReceivedDate AND @PromiseDate \n AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')\n Else\n DATEDIFF(d,@PromiseDate,@ReceivedDate) -\n ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 -\n CASE \n WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1 \n WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1 \n ELSE 0\n END -\n (Select COUNT(*) FROM CompanyHolidays \n WHERE HolidayDate BETWEEN @PromiseDate and @ReceivedDate \n AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')\n End\n\n\n RETURN (@days)\n\nEND\n</code></pre>\n"
},
{
"answer_id": 18538037,
"author": "user2733766",
"author_id": 2733766,
"author_profile": "https://Stackoverflow.com/users/2733766",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a version that works well (I think). Holiday table contains Holiday_date columns that contains holidays your company observe.</p>\n\n<pre><code>DECLARE @RAWDAYS INT\n\n SELECT @RAWDAYS = DATEDIFF(day, @StartDate, @EndDate )--+1\n -( 2 * DATEDIFF( week, @StartDate, @EndDate ) )\n + CASE WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN 1 ELSE 0 END\n - CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END \n\n SELECT @RAWDAYS - COUNT(*) \n FROM HOLIDAY NumberOfBusinessDays\n WHERE [Holiday_Date] BETWEEN @StartDate+1 AND @EndDate \n</code></pre>\n"
},
{
"answer_id": 20149314,
"author": "Danimal111",
"author_id": 1197405,
"author_profile": "https://Stackoverflow.com/users/1197405",
"pm_score": 5,
"selected": false,
"text": "<p>All Credit to Bogdan Maxim & Peter Mortensen. This is their post, I just added holidays to the function (This assumes you have a table \"tblHolidays\" with a datetime field \"HolDate\". </p>\n\n<pre><code>--Changing current database to the Master database allows function to be shared by everyone.\nUSE MASTER\nGO\n--If the function already exists, drop it.\nIF EXISTS\n(\n SELECT *\n FROM dbo.SYSOBJECTS\n WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')\n AND XType IN (N'FN', N'IF', N'TF')\n)\n\nDROP FUNCTION [dbo].[fn_WorkDays]\nGO\n CREATE FUNCTION dbo.fn_WorkDays\n--Presets\n--Define the input parameters (OK if reversed by mistake).\n(\n @StartDate DATETIME,\n @EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed\n)\n\n--Define the output data type.\nRETURNS INT\n\nAS\n--Calculate the RETURN of the function.\nBEGIN\n --Declare local variables\n --Temporarily holds @EndDate during date reversal.\n DECLARE @Swap DATETIME\n\n --If the Start Date is null, return a NULL and exit.\n IF @StartDate IS NULL\n RETURN NULL\n\n --If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).\n IF @EndDate IS NULL\n SELECT @EndDate = @StartDate\n\n --Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.\n --Usually faster than CONVERT.\n --0 is a date (01/01/1900 00:00:00.000)\n SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),\n @EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)\n\n --If the inputs are in the wrong order, reverse them.\n IF @StartDate > @EndDate\n SELECT @Swap = @EndDate,\n @EndDate = @StartDate,\n @StartDate = @Swap\n\n --Calculate and return the number of workdays using the input parameters.\n --This is the meat of the function.\n --This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.\n RETURN (\n SELECT\n --Start with total number of days including weekends\n (DATEDIFF(dd,@StartDate, @EndDate)+1)\n --Subtact 2 days for each full weekend\n -(DATEDIFF(wk,@StartDate, @EndDate)*2)\n --If StartDate is a Sunday, Subtract 1\n -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'\n THEN 1\n ELSE 0\n END)\n --If EndDate is a Saturday, Subtract 1\n -(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'\n THEN 1\n ELSE 0\n END)\n --Subtract all holidays\n -(Select Count(*) from [DB04\\DB04].[Gateway].[dbo].[tblHolidays]\n where [HolDate] between @StartDate and @EndDate )\n )\n END \nGO\n-- Test Script\n/*\ndeclare @EndDate datetime= dateadd(m,2,getdate())\nprint @EndDate\nselect [Master].[dbo].[fn_WorkDays] (getdate(), @EndDate)\n*/\n</code></pre>\n"
},
{
"answer_id": 21098589,
"author": "Mário Meyrelles",
"author_id": 692083,
"author_profile": "https://Stackoverflow.com/users/692083",
"pm_score": 1,
"selected": false,
"text": "<p>If you need to add work days to a given date, you can create a function that depends on a calendar table, described below:</p>\n\n<pre><code>CREATE TABLE Calendar\n(\n dt SMALLDATETIME PRIMARY KEY, \n IsWorkDay BIT\n);\n\n--fill the rows with normal days, weekends and holidays.\n\n\ncreate function AddWorkingDays (@initialDate smalldatetime, @numberOfDays int)\n returns smalldatetime as \n\n begin\n declare @result smalldatetime\n set @result = \n (\n select t.dt from\n (\n select dt, ROW_NUMBER() over (order by dt) as daysAhead from calendar \n where dt > @initialDate\n and IsWorkDay = 1\n ) t\n where t.daysAhead = @numberOfDays\n )\n\n return @result\n end\n</code></pre>\n"
},
{
"answer_id": 22358571,
"author": "Brian",
"author_id": 3411807,
"author_profile": "https://Stackoverflow.com/users/3411807",
"pm_score": 2,
"selected": false,
"text": "<p>Using a date table:</p>\n\n<pre><code> DECLARE \n @StartDate date = '2014-01-01',\n @EndDate date = '2014-01-31'; \n SELECT \n COUNT(*) As NumberOfWeekDays\n FROM dbo.Calendar\n WHERE CalendarDate BETWEEN @StartDate AND @EndDate\n AND IsWorkDay = 1;\n</code></pre>\n\n<p>If you don't have that, you can use a numbers table:</p>\n\n<pre><code> DECLARE \n @StartDate datetime = '2014-01-01',\n @EndDate datetime = '2014-01-31'; \n SELECT \n SUM(CASE WHEN DATEPART(dw, DATEADD(dd, Number-1, @StartDate)) BETWEEN 2 AND 6 THEN 1 ELSE 0 END) As NumberOfWeekDays\n FROM dbo.Numbers\n WHERE Number <= DATEDIFF(dd, @StartDate, @EndDate) + 1 -- Number table starts at 1, we want a 0 base\n</code></pre>\n\n<p>They should both be fast and it takes out the ambiguity/complexity. The first option is the best but if you don't have a calendar table you can allways create a numbers table with a CTE.</p>\n"
},
{
"answer_id": 22428919,
"author": "user3424126",
"author_id": 3424126,
"author_profile": "https://Stackoverflow.com/users/3424126",
"pm_score": 0,
"selected": false,
"text": "<p>That's working for me, in my country on Saturday and Sunday are non-working days.</p>\n\n<p>For me is important the time of @StartDate and @EndDate.</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fnGetCountWorkingBusinessDays]\n(\n @StartDate as DATETIME,\n @EndDate as DATETIME\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @res int\n\nSET @StartDate = CASE \n WHEN DATENAME(dw, @StartDate) = 'Saturday' THEN DATEADD(dd, 2, DATEDIFF(dd, 0, @StartDate))\n WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN DATEADD(dd, 1, DATEDIFF(dd, 0, @StartDate))\n ELSE @StartDate END\n\nSET @EndDate = CASE \n WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN DATEADD(dd, 0, DATEDIFF(dd, 0, @EndDate))\n WHEN DATENAME(dw, @EndDate) = 'Sunday' THEN DATEADD(dd, -1, DATEDIFF(dd, 0, @EndDate))\n ELSE @EndDate END\n\n\nSET @res =\n (DATEDIFF(hour, @StartDate, @EndDate) / 24)\n - (DATEDIFF(wk, @StartDate, @EndDate) * 2)\n\nSET @res = CASE WHEN @res < 0 THEN 0 ELSE @res END\n\n RETURN @res\nEND\n\nGO\n</code></pre>\n"
},
{
"answer_id": 37956058,
"author": "Igor Krupitsky",
"author_id": 1781849,
"author_profile": "https://Stackoverflow.com/users/1781849",
"pm_score": 0,
"selected": false,
"text": "<p>Create function like:</p>\n\n<pre><code>CREATE FUNCTION dbo.fn_WorkDays(@StartDate DATETIME, @EndDate DATETIME= NULL )\nRETURNS INT \nAS\nBEGIN\n DECLARE @Days int\n SET @Days = 0\n\n IF @EndDate = NULL\n SET @EndDate = EOMONTH(@StartDate) --last date of the month\n\n WHILE DATEDIFF(dd,@StartDate,@EndDate) >= 0\n BEGIN\n IF DATENAME(dw, @StartDate) <> 'Saturday' \n and DATENAME(dw, @StartDate) <> 'Sunday' \n and Not ((Day(@StartDate) = 1 And Month(@StartDate) = 1)) --New Year's Day.\n and Not ((Day(@StartDate) = 4 And Month(@StartDate) = 7)) --Independence Day.\n BEGIN\n SET @Days = @Days + 1\n END\n\n SET @StartDate = DATEADD(dd,1,@StartDate)\n END\n\n RETURN @Days\nEND\n</code></pre>\n\n<p>You can call the function like: </p>\n\n<pre><code>select dbo.fn_WorkDays('1/1/2016', '9/25/2016')\n</code></pre>\n\n<p>Or like:</p>\n\n<pre><code>select dbo.fn_WorkDays(StartDate, EndDate) \nfrom table1\n</code></pre>\n"
},
{
"answer_id": 38065346,
"author": "shawnt00",
"author_id": 1322268,
"author_profile": "https://Stackoverflow.com/users/1322268",
"pm_score": 2,
"selected": false,
"text": "<p>This is basically CMS's answer without the reliance on a particular language setting. And since we're shooting for generic, that means it should work for all <code>@@datefirst</code> settings as well.</p>\n\n<pre><code>datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2\n /* if start is a Sunday, adjust by -1 */\n + case when datepart(weekday, <start>) = 8 - @@datefirst then -1 else 0 end\n /* if end is a Saturday, adjust by -1 */\n + case when datepart(weekday, <end>) = (13 - @@datefirst) % 7 + 1 then -1 else 0 end\n</code></pre>\n\n<p><code>datediff(week, ...)</code> always uses a Saturday-to-Sunday boundary for weeks, so that expression is deterministic and doesn't need to be modified (as long as our definition of weekdays is consistently Monday through Friday.) Day numbering does vary according to the <code>@@datefirst</code> setting and the modified calculations handle this correction with the small complication of some modular arithmetic.</p>\n\n<p>A cleaner way to deal with the Saturday/Sunday thing is to translate the dates prior to extracting a day of week value. After shifting, the values will be back in line with a fixed (and probably more familiar) numbering that starts with 1 on Sunday and ends with 7 on Saturday.</p>\n\n<pre><code>datediff(day, <start>, <end>) + 1 - datediff(week, <start>, <end>) * 2\n + case when datepart(weekday, dateadd(day, @@datefirst, <start>)) = 1 then -1 else 0 end\n + case when datepart(weekday, dateadd(day, @@datefirst, <end>)) = 7 then -1 else 0 end\n</code></pre>\n\n<p>I've tracked this form of the solution back at least as far as 2002 and an Itzik Ben-Gan article. (<a href=\"https://technet.microsoft.com/en-us/library/aa175781(v=sql.80).aspx\" rel=\"nofollow noreferrer\">https://technet.microsoft.com/en-us/library/aa175781(v=sql.80).aspx</a>) Though it needed a small tweak since newer <code>date</code> types don't allow date arithmetic, it is otherwise identical.</p>\n\n<p>EDIT:\nI added back the <code>+1</code> that had somehow been left off. It's also worth noting that this method always counts the start and end days. It also assumes that the end date is on or after the start date.</p>\n"
},
{
"answer_id": 40405616,
"author": "pix1985",
"author_id": 1166604,
"author_profile": "https://Stackoverflow.com/users/1166604",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Create Function dbo.DateDiff_WeekDays \n(\n@StartDate DateTime,\n@EndDate DateTime\n)\nReturns Int\nAs\n\nBegin \n\nDeclare @Result Int = 0\n\nWhile @StartDate <= @EndDate\nBegin \n If DateName(DW, @StartDate) not in ('Saturday','Sunday')\n Begin\n Set @Result = @Result +1\n End\n Set @StartDate = DateAdd(Day, +1, @StartDate)\nEnd\n\nReturn @Result\n</code></pre>\n\n<p>End</p>\n"
},
{
"answer_id": 44820540,
"author": "AliceF",
"author_id": 3810105,
"author_profile": "https://Stackoverflow.com/users/3810105",
"pm_score": 3,
"selected": false,
"text": "<p>Another approach to calculating working days is to use a WHILE loop which basically iterates through a date range and increment it by 1 whenever days are found to be within Monday – Friday. The complete script for calculating working days using the WHILE loop is shown below:</p>\n\n<pre><code>CREATE FUNCTION [dbo].[fn_GetTotalWorkingDaysUsingLoop]\n(@DateFrom DATE,\n@DateTo DATE\n)\nRETURNS INT\nAS\n BEGIN\n DECLARE @TotWorkingDays INT= 0;\n WHILE @DateFrom <= @DateTo\n BEGIN\n IF DATENAME(WEEKDAY, @DateFrom) IN('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')\n BEGIN\n SET @TotWorkingDays = @TotWorkingDays + 1;\n END;\n SET @DateFrom = DATEADD(DAY, 1, @DateFrom);\n END;\n RETURN @TotWorkingDays;\n END;\nGO\n</code></pre>\n\n<p>Although the WHILE loop option is cleaner and uses less lines of code, it has the potential of being a performance bottleneck in your environment particularly when your date range spans across several years.</p>\n\n<p>You can see more methods on how to calculate work days and hours in this article:\n<a href=\"https://www.sqlshack.com/how-to-calculate-work-days-and-hours-in-sql-server/\" rel=\"noreferrer\">https://www.sqlshack.com/how-to-calculate-work-days-and-hours-in-sql-server/</a></p>\n"
},
{
"answer_id": 45841283,
"author": "Baseline9",
"author_id": 4657998,
"author_profile": "https://Stackoverflow.com/users/4657998",
"pm_score": 0,
"selected": false,
"text": "<p>I found the below TSQL a fairly elegant solution (I don't have permissions to run functions). I found the <code>DATEDIFF</code> ignores <code>DATEFIRST</code> and I wanted my first day of the week to be a Monday. I also wanted the first working day to be set a zero and if it falls on a weekend Monday will be a zero. This may help someone who has a slightly different requirement :) </p>\n\n<p>It does not handle bank holidays</p>\n\n<pre><code>SET DATEFIRST 1\nSELECT\n,(DATEDIFF(DD, [StartDate], [EndDate])) \n-(DATEDIFF(wk, [StartDate], [EndDate])) \n-(DATEDIFF(wk, DATEADD(dd,-@@DATEFIRST,[StartDate]), DATEADD(dd,-@@DATEFIRST,[EndDate]))) AS [WorkingDays] \nFROM /*Your Table*/ \n</code></pre>\n"
},
{
"answer_id": 48802311,
"author": "umbersar",
"author_id": 364084,
"author_profile": "https://Stackoverflow.com/users/364084",
"pm_score": 0,
"selected": false,
"text": "<p>One approach is to 'walk the dates' from start to finish in conjunction with a case expression which checks if the day is not a Saturday or a Sunday and flagging it(1 for weekday, 0 for weekend). And in the end just sum flags(it would be equal to the count of 1-flags as the other flag is 0) to give you the number of weekdays.</p>\n\n<p>You can use a GetNums(startNumber,endNumber) type of utility function which generates a series of numbers for 'looping' from start date to end date. Refer <a href=\"http://tsql.solidq.com/SourceCodes/GetNums.txt\" rel=\"nofollow noreferrer\">http://tsql.solidq.com/SourceCodes/GetNums.txt</a> for an implementation. The logic can also be extended to cater for holidays(say if you have a holidays table)</p>\n\n<pre><code>declare @date1 as datetime = '19900101'\ndeclare @date2 as datetime = '19900120'\n\nselect sum(case when DATENAME(DW,currentDate) not in ('Saturday', 'Sunday') then 1 else 0 end) as noOfWorkDays\nfrom dbo.GetNums(0,DATEDIFF(day,@date1, @date2)-1) as Num\ncross apply (select DATEADD(day,n,@date1)) as Dates(currentDate)\n</code></pre>\n"
},
{
"answer_id": 51104858,
"author": "Wolfgang Kais",
"author_id": 6777839,
"author_profile": "https://Stackoverflow.com/users/6777839",
"pm_score": 1,
"selected": false,
"text": "<p>As with DATEDIFF, I do not consider the end date to be part of the interval.\nThe number of (for example) Sundays between @StartDate and @EndDate is the number of Sundays between an \"initial\" Monday and the @EndDate minus the number of Sundays between this \"initial\" Monday and the @StartDate. Knowing this, we can calculate the number of workdays as follows:</p>\n\n<pre><code>DECLARE @StartDate DATETIME\nDECLARE @EndDate DATETIME\nSET @StartDate = '2018/01/01'\nSET @EndDate = '2019/01/01'\n\nSELECT DATEDIFF(Day, @StartDate, @EndDate) -- Total Days\n - (DATEDIFF(Day, 0, @EndDate)/7 - DATEDIFF(Day, 0, @StartDate)/7) -- Sundays\n - (DATEDIFF(Day, -1, @EndDate)/7 - DATEDIFF(Day, -1, @StartDate)/7) -- Saturdays\n</code></pre>\n\n<p>Best regards!</p>\n"
},
{
"answer_id": 51192099,
"author": "adrianm",
"author_id": 157224,
"author_profile": "https://Stackoverflow.com/users/157224",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old question but I needed a formula for workdays excluding the start date since I have several items and need the days to accumulate correctly.</p>\n\n<p>None of the non-iterative answers worked for me.</p>\n\n<p>I used a defintion like</p>\n\n<blockquote>\n <p>Number of times midnight to monday, tuesday, wednesday, thursday and friday is passed</p>\n</blockquote>\n\n<p>(others might count midnight to saturday instead of monday)</p>\n\n<p>I ended up with this formula</p>\n\n<pre><code>SELECT DATEDIFF(day, @StartDate, @EndDate) /* all midnights passed */\n - DATEDIFF(week, @StartDate, @EndDate) /* remove sunday midnights */\n - DATEDIFF(week, DATEADD(day, 1, @StartDate), DATEADD(day, 1, @EndDate)) /* remove saturday midnights */\n</code></pre>\n"
},
{
"answer_id": 56942465,
"author": "Gary",
"author_id": 795047,
"author_profile": "https://Stackoverflow.com/users/795047",
"pm_score": 1,
"selected": false,
"text": "<p>I borrowed some ideas from others to create my solution. I use inline code to ignore weekends and U.S. federal holidays. In my environment, EndDate may be null, but it will never precede StartDate.</p>\n\n<pre><code>CREATE FUNCTION dbo.ufn_CalculateBusinessDays(\n@StartDate DATE,\n@EndDate DATE = NULL)\n\nRETURNS INT\nAS\n\nBEGIN\nDECLARE @TotalBusinessDays INT = 0;\nDECLARE @TestDate DATE = @StartDate;\n\n\nIF @EndDate IS NULL\n RETURN NULL;\n\nWHILE @TestDate < @EndDate\nBEGIN\n DECLARE @Month INT = DATEPART(MM, @TestDate);\n DECLARE @Day INT = DATEPART(DD, @TestDate);\n DECLARE @DayOfWeek INT = DATEPART(WEEKDAY, @TestDate) - 1; --Monday = 1, Tuesday = 2, etc.\n DECLARE @DayOccurrence INT = (@Day - 1) / 7 + 1; --Nth day of month (3rd Monday, for example)\n\n --Increment business day counter if not a weekend or holiday\n SELECT @TotalBusinessDays += (\n SELECT CASE\n --Saturday OR Sunday\n WHEN @DayOfWeek IN (6,7) THEN 0\n --New Year's Day\n WHEN @Month = 1 AND @Day = 1 THEN 0\n --MLK Jr. Day\n WHEN @Month = 1 AND @DayOfWeek = 1 AND @DayOccurrence = 3 THEN 0\n --G. Washington's Birthday\n WHEN @Month = 2 AND @DayOfWeek = 1 AND @DayOccurrence = 3 THEN 0\n --Memorial Day\n WHEN @Month = 5 AND @DayOfWeek = 1 AND @Day BETWEEN 25 AND 31 THEN 0\n --Independence Day\n WHEN @Month = 7 AND @Day = 4 THEN 0\n --Labor Day\n WHEN @Month = 9 AND @DayOfWeek = 1 AND @DayOccurrence = 1 THEN 0\n --Columbus Day\n WHEN @Month = 10 AND @DayOfWeek = 1 AND @DayOccurrence = 2 THEN 0\n --Veterans Day\n WHEN @Month = 11 AND @Day = 11 THEN 0\n --Thanksgiving\n WHEN @Month = 11 AND @DayOfWeek = 4 AND @DayOccurrence = 4 THEN 0\n --Christmas\n WHEN @Month = 12 AND @Day = 25 THEN 0\n ELSE 1\n END AS Result);\n\n SET @TestDate = DATEADD(dd, 1, @TestDate);\nEND\n\nRETURN @TotalBusinessDays;\nEND\n</code></pre>\n"
},
{
"answer_id": 64725325,
"author": "Igor Krupitsky",
"author_id": 1781849,
"author_profile": "https://Stackoverflow.com/users/1781849",
"pm_score": 2,
"selected": false,
"text": "<p>None of the functions above work for the same week or deal with holidays. I wrote this:</p>\n<pre><code>create FUNCTION [dbo].[ShiftHolidayToWorkday](@date date)\nRETURNS date\nAS\nBEGIN\n IF DATENAME( dw, @Date ) = 'Saturday'\n SET @Date = DATEADD(day, - 1, @Date)\n\n ELSE IF DATENAME( dw, @Date ) = 'Sunday'\n SET @Date = DATEADD(day, 1, @Date)\n\n RETURN @date\nEND\nGO\n\ncreate FUNCTION [dbo].[GetHoliday](@date date)\nRETURNS varchar(50)\nAS\nBEGIN\n declare @s varchar(50)\n\n SELECT @s = CASE\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-01-01') = @date THEN 'New Year'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]+1) + '-01-01') = @date THEN 'New Year'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-07-04') = @date THEN 'Independence Day'\n WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year] ) + '-12-25') = @date THEN 'Christmas Day'\n --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-12-31') = @date THEN 'New Years Eve'\n --WHEN dbo.ShiftHolidayToWorkday(CONVERT(varchar, [Year]) + '-11-11') = @date THEN 'Veteran''s Day'\n\n WHEN [Month] = 1 AND [DayOfMonth] BETWEEN 15 AND 21 AND [DayName] = 'Monday' THEN 'Martin Luther King Day'\n WHEN [Month] = 5 AND [DayOfMonth] >= 25 AND [DayName] = 'Monday' THEN 'Memorial Day'\n WHEN [Month] = 9 AND [DayOfMonth] <= 7 AND [DayName] = 'Monday' THEN 'Labor Day'\n WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 22 AND 28 AND [DayName] = 'Thursday' THEN 'Thanksgiving Day'\n WHEN [Month] = 11 AND [DayOfMonth] BETWEEN 23 AND 29 AND [DayName] = 'Friday' THEN 'Day After Thanksgiving'\n ELSE NULL END\n FROM (\n SELECT\n [Year] = YEAR(@date),\n [Month] = MONTH(@date),\n [DayOfMonth] = DAY(@date),\n [DayName] = DATENAME(weekday,@date)\n ) c\n\n RETURN @s\nEND\nGO\n\ncreate FUNCTION [dbo].GetHolidays(@year int)\nRETURNS TABLE \nAS\nRETURN ( \n select dt, dbo.GetHoliday(dt) as Holiday\n from (\n select dateadd(day, number, convert(varchar,@year) + '-01-01') dt\n from master..spt_values \n where type='p' \n ) d\n where year(dt) = @year and dbo.GetHoliday(dt) is not null\n)\n\ncreate proc UpdateHolidaysTable\nas\n\nif not exists(select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'Holidays')\n create table Holidays(dt date primary key clustered, Holiday varchar(50))\n\ndeclare @year int\nset @year = 1990\n\nwhile @year < year(GetDate()) + 20\nbegin\n insert into Holidays(dt, Holiday)\n select a.dt, a.Holiday\n from dbo.GetHolidays(@year) a\n left join Holidays b on b.dt = a.dt\n where b.dt is null\n\n set @year = @year + 1\nend\n\ncreate FUNCTION [dbo].[GetWorkDays](@StartDate DATE = NULL, @EndDate DATE = NULL)\nRETURNS INT \nAS\nBEGIN\n IF @StartDate IS NULL OR @EndDate IS NULL\n RETURN 0\n\n IF @StartDate >= @EndDate \n RETURN 0\n\n DECLARE @Days int\n SET @Days = 0\n\n IF year(@StartDate) * 100 + datepart(week, @StartDate) = year(@EndDate) * 100 + datepart(week, @EndDate) \n --same week\n select @Days = (DATEDIFF(dd, @StartDate, @EndDate))\n - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n - (select count(*) from Holidays where dt between @StartDate and @EndDate)\n ELSE\n --diff weeks\n select @Days = (DATEDIFF(dd, @StartDate, @EndDate) + 1)\n - (DATEDIFF(wk, @StartDate, @EndDate) * 2)\n - (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)\n - (CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)\n - (select count(*) from Holidays where dt between @StartDate and @EndDate)\n \n RETURN @Days\nEND\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28419/"
] |
How can I calculate the number of work days between two dates in SQL Server?
Monday to Friday and it must be T-SQL.
|
For workdays, Monday to Friday, you can do it with a single SELECT, like this:
```
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'
SELECT
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
```
If you want to include holidays, you have to work it out a bit...
|
252,539 |
<p>I have an app where I create many uiviews and add them to the self.view of the UIViewController. My app is running really slowly. I am releasing all of my objects and have no memory leaks (I ran the performance tool). Can anyone tell me what could be making my app so slow? (code is below)</p>
<p>[EDIT] The array has around 30 items. [/EndEdit]</p>
<p>Thanks so much!</p>
<p>Here is the code for the loadView method of my UIViewController:</p>
<pre><code>- (void)loadView {
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor whiteColor];
self.view = contentView;
[contentView release];
int length = 0;
for(NSString *item in arrayTips)
{
length++;
[item release];
}
int index = 0;
for(NSString *item in arrayTitles)
{
SingleFlipView *backView = [[SingleFlipView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
backView.userInteractionEnabled = YES;
backView.backgroundColor = [UIColor whiteColor];
[backView setViewIndex:index];
[backView setLastViewIndex:length];
CGRect labelFrame = CGRectMake(10.0f, 0.0f, 300.0f, 30.0f);
UILabel *backLabel = [[UILabel alloc] initWithFrame:labelFrame];
backLabel.textAlignment = UITextAlignmentCenter;
backLabel.userInteractionEnabled = YES;
backLabel.text = item;
backLabel.font = [UIFont fontWithName:@"Georgia" size:24.0f];
backLabel.textColor = [UIColor blackColor];
backLabel.backgroundColor = [UIColor whiteColor];
CGRect textFrame = CGRectMake(10.0f, 30.0f, 300.0f, 110.0f);
UITextView *tbxView = [[UITextView alloc] initWithFrame:textFrame];
tbxView.textAlignment = UITextAlignmentCenter;
tbxView.userInteractionEnabled = YES;
tbxView.editable = FALSE;
tbxView.text = [arrayTips objectAtIndex:index];
tbxView.font = [UIFont fontWithName:@"Arial" size:14.0f];
tbxView.textColor = [UIColor blackColor];
tbxView.backgroundColor = [UIColor whiteColor];
//CGRect labelFrame = CGRectMake(10.0f, 0.0f, 84.0f, 30.0f);
UIImage *nextTip = [[UIImage imageNamed:@"NextTip.png"] retain];
UIImageView *nextTipView = [ [ UIImageView alloc ] initWithImage:nextTip];
nextTipView.frame = CGRectMake(230.0f, -10.0f, 84.0f, 30.0f);
nextTipView.userInteractionEnabled = YES;
UIImageView *view = [[ UIImageView alloc ] init];
view.userInteractionEnabled = YES;
if(self.sexString == @"Men")
{
UIImage *imgTip = [[UIImage imageNamed:@"feet_small.jpg"] retain];
view.image = imgTip;
view.frame = CGRectMake(0.0f, 110.0f, 416.0f, 228.0f); //59*161
[imgTip release];
}
[backView addSubview:view];
[backView addSubview:tbxView];
[backView addSubview:backLabel];
//[backView addSubview:nextTipView];
[self.view addSubview:backView];
[backView release];
[backLabel release];
[nextTip release];
[nextTipView release];
[tbxView release];
[view release];
index++;
[item release];
}
}
</code></pre>
|
[
{
"answer_id": 252566,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 2,
"selected": false,
"text": "<p>It's going to depend upon how many items are in arrayTitles. If you're just adding one or two of these, you shouldn't see a HUGE slowdown; more, and you will. You should probably take a look at the way UITableView handles its cells; only create these as they're actually needed/used, or, better yet, only create one of these, and set its contents on-the-fly. </p>\n\n<p>A few other notes:</p>\n\n<ul>\n<li>== is not a valid string comparison operator in Objective-C; use [string1 isEqualTo: string2]</li>\n<li>It appears you're trying to place a lot of these on screen at the same time, which doesn't seem like it would make a lot of sense.</li>\n<li>it looks like you've got a spurious <code>[item release]</code> at the end there (you're never retaining <code>item</code>, so there's no need to release it.</li>\n<li>the whole first loop (<code> for(NSString *item in arrayTips)...</code> frightens and confuses me; items in NSArrays are already retained by the array. You shouldn't have to explicitly retain/release them in this way.</li>\n</ul>\n"
},
{
"answer_id": 252569,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 3,
"selected": true,
"text": "<p>Having deep view hierarchies can lead to slow downs that you can often fix through flattening them some with custom views, but if you are using simple views you can have dozens on the screen with no perceptible performance impact, so in general I recommend ignoring how many views you have when you are developing, and then reducing the view count if it proves to be a performance problem.</p>\n\n<p>Having said that, you appear to be setting up something with an unboundedily large number of views which is not good. Without knowing how many entries there are in array titles I can't tell you what is going on exactly, but I suspect that while the actual visual heiarchy with each backView you are creating is fine, making a backView for each item in the array and using indices to have the front most one hide all the other ones behind it is causing you to have way too many views.</p>\n\n<p>So, how to test it:</p>\n\n<p>Add a break to the bottom of your for loop. Make the loop drop out after a single iteration and see if performance improves. If it does, then the huge view hierarchies are your issue. YOu may have to hack up the routine that changes the indexes to make sure it never swaps to an invalid index to test.</p>\n\n<p>If that is the case you have a few options. You could implement a custom view and flatten every backview into a single view, but depending on how many you have that mat not be sufficient, and it is more work than simply building the back views the way you currently are, but on demand instead of at load time:</p>\n\n<p>1) Refactor the code in your for loop into a separate method that makes a backView for a specific title and attaches it to the view at that time.\n2) Where ever you are currently altering the indexes to make the backview visible, instead call the new method to actually build and attach the backview at that time</p>\n"
},
{
"answer_id": 653272,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>Don't forget to make as many of your views opaque as you can. Transparent views are a major source of performance issues.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I have an app where I create many uiviews and add them to the self.view of the UIViewController. My app is running really slowly. I am releasing all of my objects and have no memory leaks (I ran the performance tool). Can anyone tell me what could be making my app so slow? (code is below)
[EDIT] The array has around 30 items. [/EndEdit]
Thanks so much!
Here is the code for the loadView method of my UIViewController:
```
- (void)loadView {
UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
contentView.backgroundColor = [UIColor whiteColor];
self.view = contentView;
[contentView release];
int length = 0;
for(NSString *item in arrayTips)
{
length++;
[item release];
}
int index = 0;
for(NSString *item in arrayTitles)
{
SingleFlipView *backView = [[SingleFlipView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
backView.userInteractionEnabled = YES;
backView.backgroundColor = [UIColor whiteColor];
[backView setViewIndex:index];
[backView setLastViewIndex:length];
CGRect labelFrame = CGRectMake(10.0f, 0.0f, 300.0f, 30.0f);
UILabel *backLabel = [[UILabel alloc] initWithFrame:labelFrame];
backLabel.textAlignment = UITextAlignmentCenter;
backLabel.userInteractionEnabled = YES;
backLabel.text = item;
backLabel.font = [UIFont fontWithName:@"Georgia" size:24.0f];
backLabel.textColor = [UIColor blackColor];
backLabel.backgroundColor = [UIColor whiteColor];
CGRect textFrame = CGRectMake(10.0f, 30.0f, 300.0f, 110.0f);
UITextView *tbxView = [[UITextView alloc] initWithFrame:textFrame];
tbxView.textAlignment = UITextAlignmentCenter;
tbxView.userInteractionEnabled = YES;
tbxView.editable = FALSE;
tbxView.text = [arrayTips objectAtIndex:index];
tbxView.font = [UIFont fontWithName:@"Arial" size:14.0f];
tbxView.textColor = [UIColor blackColor];
tbxView.backgroundColor = [UIColor whiteColor];
//CGRect labelFrame = CGRectMake(10.0f, 0.0f, 84.0f, 30.0f);
UIImage *nextTip = [[UIImage imageNamed:@"NextTip.png"] retain];
UIImageView *nextTipView = [ [ UIImageView alloc ] initWithImage:nextTip];
nextTipView.frame = CGRectMake(230.0f, -10.0f, 84.0f, 30.0f);
nextTipView.userInteractionEnabled = YES;
UIImageView *view = [[ UIImageView alloc ] init];
view.userInteractionEnabled = YES;
if(self.sexString == @"Men")
{
UIImage *imgTip = [[UIImage imageNamed:@"feet_small.jpg"] retain];
view.image = imgTip;
view.frame = CGRectMake(0.0f, 110.0f, 416.0f, 228.0f); //59*161
[imgTip release];
}
[backView addSubview:view];
[backView addSubview:tbxView];
[backView addSubview:backLabel];
//[backView addSubview:nextTipView];
[self.view addSubview:backView];
[backView release];
[backLabel release];
[nextTip release];
[nextTipView release];
[tbxView release];
[view release];
index++;
[item release];
}
}
```
|
Having deep view hierarchies can lead to slow downs that you can often fix through flattening them some with custom views, but if you are using simple views you can have dozens on the screen with no perceptible performance impact, so in general I recommend ignoring how many views you have when you are developing, and then reducing the view count if it proves to be a performance problem.
Having said that, you appear to be setting up something with an unboundedily large number of views which is not good. Without knowing how many entries there are in array titles I can't tell you what is going on exactly, but I suspect that while the actual visual heiarchy with each backView you are creating is fine, making a backView for each item in the array and using indices to have the front most one hide all the other ones behind it is causing you to have way too many views.
So, how to test it:
Add a break to the bottom of your for loop. Make the loop drop out after a single iteration and see if performance improves. If it does, then the huge view hierarchies are your issue. YOu may have to hack up the routine that changes the indexes to make sure it never swaps to an invalid index to test.
If that is the case you have a few options. You could implement a custom view and flatten every backview into a single view, but depending on how many you have that mat not be sufficient, and it is more work than simply building the back views the way you currently are, but on demand instead of at load time:
1) Refactor the code in your for loop into a separate method that makes a backView for a specific title and attaches it to the view at that time.
2) Where ever you are currently altering the indexes to make the backview visible, instead call the new method to actually build and attach the backview at that time
|
252,548 |
<p>When upgrading MySQL, I first create a backup of the database. Then I will uninstall the current version installed, and delete all the files that were left by the installer. Then I install the latest GA version, and restore the created back-up, using the MySQL Administrator.</p>
<p>Is there a better way of doing an upgrade of the MySQL. Because I have to create again all the users that are allowed to connect to the database.</p>
<p>The installation of the MySQL is used in a college enrollment system, a client server system I have developed using VB.Net and MySQL. I can only do the update at night because i know no one is connected to the database.</p>
|
[
{
"answer_id": 252587,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "<p>you can dump the <code>mysql.user</code> and <code>mysql.db</code> tables, which contains all the user info, and reimport that as well, to avoid having to recreate all that. i'd also suggest running repairs on the table after you re-import.</p>\n\n<p>alternatively, you could create a listing of grants:</p>\n\n<pre><code>select concat('show grants for ',quote(user),'@',quote(host),';') from mysql.user\n</code></pre>\n\n<p>this will output a list of sql statements that you can then run to get specific grant statements.</p>\n\n<p>ultimately though, you'll want to check out your specific version information regarding upgrades, to make sure you've considered any version specific compatibility issues.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/upgrading-from-4-1.html\" rel=\"nofollow noreferrer\">here</a> is some information for a 4.1 - 5.x upgrade, for example.</p>\n"
},
{
"answer_id": 271068,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": 1,
"selected": false,
"text": "<p>Why is the mysql upgrade so braindead? The fact that you need to back up all your data, install MySQL to a different directory, reimport your data -- just to upgrade is ridiculous. There has to be an easier way.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26087/"
] |
When upgrading MySQL, I first create a backup of the database. Then I will uninstall the current version installed, and delete all the files that were left by the installer. Then I install the latest GA version, and restore the created back-up, using the MySQL Administrator.
Is there a better way of doing an upgrade of the MySQL. Because I have to create again all the users that are allowed to connect to the database.
The installation of the MySQL is used in a college enrollment system, a client server system I have developed using VB.Net and MySQL. I can only do the update at night because i know no one is connected to the database.
|
you can dump the `mysql.user` and `mysql.db` tables, which contains all the user info, and reimport that as well, to avoid having to recreate all that. i'd also suggest running repairs on the table after you re-import.
alternatively, you could create a listing of grants:
```
select concat('show grants for ',quote(user),'@',quote(host),';') from mysql.user
```
this will output a list of sql statements that you can then run to get specific grant statements.
ultimately though, you'll want to check out your specific version information regarding upgrades, to make sure you've considered any version specific compatibility issues.
[here](http://dev.mysql.com/doc/refman/5.0/en/upgrading-from-4-1.html) is some information for a 4.1 - 5.x upgrade, for example.
|
252,552 |
<p>When should unions be used? Why do we need them?</p>
|
[
{
"answer_id": 252561,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 5,
"selected": false,
"text": "<p>Unions allow data members which are mutually exclusive to share the same memory. This is quite important when memory is more scarce, such as in embedded systems.</p>\n\n<p>In the following example:</p>\n\n<pre><code>union {\n int a;\n int b;\n int c;\n} myUnion;\n</code></pre>\n\n<p>This union will take up the space of a single int, rather than 3 separate int values. If the user set the value of <strong>a</strong>, and then set the value of <strong>b</strong>, it would overwrite the value of <strong>a</strong> since they are both sharing the same memory location.</p>\n"
},
{
"answer_id": 252564,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Unions are used when you want to model structs defined by hardware, devices or network protocols, or when you're creating a large number of objects and want to save space. You really don't need them 95% of the time though, stick with easy-to-debug code.</p>\n"
},
{
"answer_id": 252568,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 8,
"selected": false,
"text": "<p>Unions are often used to convert between the binary representations of integers and floats:</p>\n\n<pre><code>union\n{\n int i;\n float f;\n} u;\n\n// Convert floating-point bits to integer:\nu.f = 3.14159f;\nprintf(\"As integer: %08x\\n\", u.i);\n</code></pre>\n\n<p>Although this is technically undefined behavior according to the C standard (you're only supposed to read the field which was most recently written), it will act in a well-defined manner in virtually any compiler.</p>\n\n<p>Unions are also sometimes used to implement pseudo-polymorphism in C, by giving a structure some tag indicating what type of object it contains, and then unioning the possible types together:</p>\n\n<pre><code>enum Type { INTS, FLOATS, DOUBLE };\nstruct S\n{\n Type s_type;\n union\n {\n int s_ints[2];\n float s_floats[2];\n double s_double;\n };\n};\n\nvoid do_something(struct S *s)\n{\n switch(s->s_type)\n {\n case INTS: // do something with s->s_ints\n break;\n\n case FLOATS: // do something with s->s_floats\n break;\n\n case DOUBLE: // do something with s->s_double\n break;\n }\n}\n</code></pre>\n\n<p>This allows the size of <code>struct S</code> to be only 12 bytes, instead of 28.</p>\n"
},
{
"answer_id": 252580,
"author": "Xiaofu",
"author_id": 31967,
"author_profile": "https://Stackoverflow.com/users/31967",
"pm_score": 3,
"selected": false,
"text": "<p>It's difficult to think of a specific occasion when you'd need this type of flexible structure, perhaps in a message protocol where you would be sending different sizes of messages, but even then there are probably better and more programmer friendly alternatives.</p>\n\n<p>Unions are a bit like variant types in other languages - they can only hold one thing at a time, but that thing could be an int, a float etc. depending on how you declare it.</p>\n\n<p>For example:</p>\n\n<pre><code>typedef union MyUnion MYUNION;\nunion MyUnion\n{\n int MyInt;\n float MyFloat;\n};\n</code></pre>\n\n<p>MyUnion will only contain an int OR a float, <em>depending on which you most recently set</em>. So doing this:</p>\n\n<pre><code>MYUNION u;\nu.MyInt = 10;\n</code></pre>\n\n<p>u now holds an int equal to 10;</p>\n\n<pre><code>u.MyFloat = 1.0;\n</code></pre>\n\n<p>u now holds a float equal to 1.0. It no longer holds an int. Obviously now if you try and do printf(\"MyInt=%d\", u.MyInt); then you're probably going to get an error, though I'm unsure of the specific behaviour.</p>\n\n<p>The size of the union is dictated by the size of its largest field, in this case the float.</p>\n"
},
{
"answer_id": 252603,
"author": "dicroce",
"author_id": 3886,
"author_profile": "https://Stackoverflow.com/users/3886",
"pm_score": 1,
"selected": false,
"text": "<p>Unions are great. One clever use of unions I've seen is to use them when defining an event. For example, you might decide that an event is 32 bits.</p>\n\n<p>Now, within that 32 bits, you might like to designate the first 8 bits as for an identifier of the sender of the event... Sometimes you deal with the event as a whole, sometimes you dissect it and compare it's components. unions give you the flexibility to do both.</p>\n\n<pre>\nunion Event\n{\n unsigned long eventCode;\n unsigned char eventParts[4];\n};\n</pre>\n"
},
{
"answer_id": 252725,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 4,
"selected": false,
"text": "<p>Here's an example of a union from my own codebase (from memory and paraphrased so it may not be exact). It was used to store language elements in an interpreter I built. For example, the following code:</p>\n<pre><code>set a to b times 7.\n</code></pre>\n<p>consists of the following language elements:</p>\n<ul>\n<li>symbol[set]</li>\n<li>variable[a]</li>\n<li>symbol[to]</li>\n<li>variable[b]</li>\n<li>symbol[times]</li>\n<li>constant[7]</li>\n<li>symbol[.]</li>\n</ul>\n<p>Language elements were defines as '<code>#define</code>' values thus:</p>\n<pre><code>#define ELEM_SYM_SET 0\n#define ELEM_SYM_TO 1\n#define ELEM_SYM_TIMES 2\n#define ELEM_SYM_FULLSTOP 3\n#define ELEM_VARIABLE 100\n#define ELEM_CONSTANT 101\n</code></pre>\n<p>and the following structure was used to store each element:</p>\n<pre><code>typedef struct {\n int typ;\n union {\n char *str;\n int val;\n }\n} tElem;\n</code></pre>\n<p>then the size of each element was the size of the maximum union (4 bytes for the typ and 4 bytes for the union, though those are typical values, the <em>actual</em> sizes depend on the implementation).</p>\n<p>In order to create a "set" element, you would use:</p>\n<pre><code>tElem e;\ne.typ = ELEM_SYM_SET;\n</code></pre>\n<p>In order to create a "variable[b]" element, you would use:</p>\n<pre><code>tElem e;\ne.typ = ELEM_VARIABLE;\ne.str = strdup ("b"); // make sure you free this later\n</code></pre>\n<p>In order to create a "constant[7]" element, you would use:</p>\n<pre><code>tElem e;\ne.typ = ELEM_CONSTANT;\ne.val = 7;\n</code></pre>\n<p>and you could easily expand it to include floats (<code>float flt</code>) or rationals (<code>struct ratnl {int num; int denom;}</code>) and other types.</p>\n<p>The basic premise is that the <code>str</code> and <code>val</code> are not contiguous in memory, they actually overlap, so it's a way of getting a different view on the same block of memory, illustrated here, where the structure is based at memory location <code>0x1010</code> and integers and pointers are both 4 bytes:</p>\n<pre><code> +-----------+\n0x1010 | |\n0x1011 | typ |\n0x1012 | |\n0x1013 | |\n +-----+-----+\n0x1014 | | |\n0x1015 | str | val |\n0x1016 | | |\n0x1017 | | |\n +-----+-----+\n</code></pre>\n<p>If it were just in a structure, it would look like this:</p>\n<pre><code> +-------+\n0x1010 | |\n0x1011 | typ |\n0x1012 | |\n0x1013 | |\n +-------+\n0x1014 | |\n0x1015 | str |\n0x1016 | |\n0x1017 | |\n +-------+\n0x1018 | |\n0x1019 | val |\n0x101A | |\n0x101B | |\n +-------+\n</code></pre>\n"
},
{
"answer_id": 252778,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 7,
"selected": false,
"text": "<p>Unions are particularly useful in Embedded programming or in situations where direct access to the hardware/memory is needed. Here is a trivial example:</p>\n\n<pre><code>typedef union\n{\n struct {\n unsigned char byte1;\n unsigned char byte2;\n unsigned char byte3;\n unsigned char byte4;\n } bytes;\n unsigned int dword;\n} HW_Register;\nHW_Register reg;\n</code></pre>\n\n<p>Then you can access the reg as follows:</p>\n\n<pre><code>reg.dword = 0x12345678;\nreg.bytes.byte3 = 4;\n</code></pre>\n\n<p>Endianness (byte order) and processor architecture are of course important.</p>\n\n<p>Another useful feature is the bit modifier:</p>\n\n<pre><code>typedef union\n{\n struct {\n unsigned char b1:1;\n unsigned char b2:1;\n unsigned char b3:1;\n unsigned char b4:1;\n unsigned char reserved:4;\n } bits;\n unsigned char byte;\n} HW_RegisterB;\nHW_RegisterB reg;\n</code></pre>\n\n<p>With this code you can access directly a single bit in the register/memory address:</p>\n\n<pre><code>x = reg.bits.b2;\n</code></pre>\n"
},
{
"answer_id": 7228241,
"author": "sharptooth",
"author_id": 57428,
"author_profile": "https://Stackoverflow.com/users/57428",
"pm_score": 1,
"selected": false,
"text": "<p>What about <a href=\"http://msdn.microsoft.com/en-us/library/e305240e-9e11-4006-98cc-26f4932d2118%28VS.85%29\" rel=\"nofollow\"><code>VARIANT</code></a> that is used in COM interfaces? It has two fields - \"type\" and a union holding an actual value that is treated depending on \"type\" field.</p>\n"
},
{
"answer_id": 7228278,
"author": "Mu Qiao",
"author_id": 665901,
"author_profile": "https://Stackoverflow.com/users/665901",
"pm_score": 1,
"selected": false,
"text": "<p>I used union when I was coding for embedded devices. I have C int that is 16 bit long. And I need to retrieve the higher 8 bits and the lower 8 bits when I need to read from/store to EEPROM. So I used this way:</p>\n\n<pre><code>union data {\n int data;\n struct {\n unsigned char higher;\n unsigned char lower;\n } parts;\n};\n</code></pre>\n\n<p>It doesn't require shifting so the code is easier to read.</p>\n\n<p>On the other hand, I saw some old C++ stl code that used union for stl allocator. If you are interested, you can read the <a href=\"http://www.sgi.com/tech/stl/stl_alloc.h\" rel=\"nofollow\">sgi stl</a> source code. Here is a piece of it:</p>\n\n<pre><code>union _Obj {\n union _Obj* _M_free_list_link;\n char _M_client_data[1]; /* The client sees this. */\n};\n</code></pre>\n"
},
{
"answer_id": 7228281,
"author": "James Anderson",
"author_id": 38207,
"author_profile": "https://Stackoverflow.com/users/38207",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>A file containing different record types.</li>\n<li>A network interface containing different request types.</li>\n</ul>\n\n<p>Take a look at this: <a href=\"http://download.oracle.com/docs/cd/E19069-01/sol.x25.92/806-1235/6jahlacnk/index.html\" rel=\"nofollow\">X.25 buffer command handling</a></p>\n\n<p>One of the many possible X.25 commands is received into a buffer and handled in place by using a UNION of all the possible structures.</p>\n"
},
{
"answer_id": 7228285,
"author": "Mario",
"author_id": 409744,
"author_profile": "https://Stackoverflow.com/users/409744",
"pm_score": 3,
"selected": false,
"text": "<p>I'd say it makes it easier to reuse memory that might be used in different ways, i.e. saving memory. E.g. you'd like to do some \"variant\" struct that's able to save a short string as well as a number:</p>\n\n<pre><code>struct variant {\n int type;\n double number;\n char *string;\n};\n</code></pre>\n\n<p>In a 32 bit system this would result in at least 96 bits or 12 bytes being used for each instance of <code>variant</code>.</p>\n\n<p>Using an union you can reduce the size down to 64 bits or 8 bytes:</p>\n\n<pre><code>struct variant {\n int type;\n union {\n double number;\n char *string;\n } value;\n};\n</code></pre>\n\n<p>You're able to save even more if you'd like to add more different variable types etc. It might be true, that you can do similar things casting a void pointer - but the union makes it a lot more accessible as well as type safe. Such savings don't sound massive, but you're saving one third of the memory used for all instances of this struct.</p>\n"
},
{
"answer_id": 7228287,
"author": "phoxis",
"author_id": 702361,
"author_profile": "https://Stackoverflow.com/users/702361",
"pm_score": 5,
"selected": false,
"text": "<p>Lots of usages. Just do <code>grep union /usr/include/*</code> or in similar directories. Most of the cases the <code>union</code> is wrapped in a <code>struct</code> and one member of the struct tells which element in the union to access. For example checkout <code>man elf</code> for real life implementations.</p>\n\n<p>This is the basic principle:</p>\n\n<pre><code>struct _mydata {\n int which_one;\n union _data {\n int a;\n float b;\n char c;\n } foo;\n} bar;\n\nswitch (bar.which_one)\n{\n case INTEGER : /* access bar.foo.a;*/ break;\n case FLOATING : /* access bar.foo.b;*/ break;\n case CHARACTER: /* access bar.foo.c;*/ break;\n}\n</code></pre>\n"
},
{
"answer_id": 7228299,
"author": "Zoneur",
"author_id": 817831,
"author_profile": "https://Stackoverflow.com/users/817831",
"pm_score": 2,
"selected": false,
"text": "<p>In school, I used unions like this:</p>\n\n<pre><code>typedef union\n{\n unsigned char color[4];\n int new_color;\n} u_color;\n</code></pre>\n\n<p>I used it to handle colors more easily, instead of using >> and << operators, I just had to go through the different index of my char array.</p>\n"
},
{
"answer_id": 7228308,
"author": "bb-generation",
"author_id": 367777,
"author_profile": "https://Stackoverflow.com/users/367777",
"pm_score": 5,
"selected": false,
"text": "<p>I've seen it in a couple of libraries as a replacement for object oriented inheritance.</p>\n\n<p>E.g.</p>\n\n<pre><code> Connection\n / | \\\n Network USB VirtualConnection\n</code></pre>\n\n<p>If you want the Connection \"class\" to be either one of the above, you could write something like:</p>\n\n<pre><code>struct Connection\n{\n int type;\n union\n {\n struct Network network;\n struct USB usb;\n struct Virtual virtual;\n }\n};\n</code></pre>\n\n<p>Example use in libinfinity: <a href=\"http://git.0x539.de/?p=infinote.git;a=blob;f=libinfinity/common/inf-session.c;h=3e887f0d63bd754c6b5ec232948027cbbf4d61fc;hb=HEAD#l74\">http://git.0x539.de/?p=infinote.git;a=blob;f=libinfinity/common/inf-session.c;h=3e887f0d63bd754c6b5ec232948027cbbf4d61fc;hb=HEAD#l74</a></p>\n"
},
{
"answer_id": 7228357,
"author": "Snips",
"author_id": 451544,
"author_profile": "https://Stackoverflow.com/users/451544",
"pm_score": 6,
"selected": false,
"text": "<p>Low level system programming is a reasonable example.</p>\n\n<p>IIRC, I've used unions to breakdown hardware registers into the component bits. So, you can access an 8-bit register (as it was, in the day I did this ;-) into the component bits.</p>\n\n<p>(I forget the exact syntax but...) This structure would allow a control register to be accessed as a control_byte or via the individual bits. It would be important to ensure the bits map on to the correct register bits for a given endianness.</p>\n\n<pre><code>typedef union {\n unsigned char control_byte;\n struct {\n unsigned int nibble : 4;\n unsigned int nmi : 1;\n unsigned int enabled : 1;\n unsigned int fired : 1;\n unsigned int control : 1;\n };\n} ControlRegister;\n</code></pre>\n"
},
{
"answer_id": 18875939,
"author": "dhein",
"author_id": 2003898,
"author_profile": "https://Stackoverflow.com/users/2003898",
"pm_score": 0,
"selected": false,
"text": "<p>A simple and very usefull example, is....</p>\n\n<p>Imagine:</p>\n\n<p>you have a <code>uint32_t array[2]</code> and want to access the 3rd and 4th Byte of the Byte chain.\nyou could do <code>*((uint16_t*) &array[1])</code>.\nBut this sadly breaks the strict aliasing rules!</p>\n\n<p>But known compilers allow you to do the following :</p>\n\n<pre><code>union un\n{\n uint16_t array16[4];\n uint32_t array32[2];\n}\n</code></pre>\n\n<p>technically this is still a violation of the rules. but all known standards support this usage.</p>\n"
},
{
"answer_id": 19055852,
"author": "Adam Lewis",
"author_id": 157744,
"author_profile": "https://Stackoverflow.com/users/157744",
"pm_score": 3,
"selected": false,
"text": "<p>Many of these answers deal with casting from one type to another. I get the most use from unions with the same types just more of them (ie when parsing a serial data stream). They allow the parsing / construction of a <em>framed</em> packet to become trivial.</p>\n\n<pre><code>typedef union\n{\n UINT8 buffer[PACKET_SIZE]; // Where the packet size is large enough for\n // the entire set of fields (including the payload)\n\n struct\n {\n UINT8 size;\n UINT8 cmd;\n UINT8 payload[PAYLOAD_SIZE];\n UINT8 crc;\n } fields;\n\n}PACKET_T;\n\n// This should be called every time a new byte of data is ready \n// and point to the packet's buffer:\n// packet_builder(packet.buffer, new_data);\n\nvoid packet_builder(UINT8* buffer, UINT8 data)\n{\n static UINT8 received_bytes = 0;\n\n // All range checking etc removed for brevity\n\n buffer[received_bytes] = data;\n received_bytes++;\n\n // Using the struc only way adds lots of logic that relates \"byte 0\" to size\n // \"byte 1\" to cmd, etc...\n}\n\nvoid packet_handler(PACKET_T* packet)\n{\n // Process the fields in a readable manner\n if(packet->fields.size > TOO_BIG)\n {\n // handle error...\n }\n\n if(packet->fields.cmd == CMD_X)\n {\n // do stuff..\n }\n}\n</code></pre>\n\n<p><em><strong>Edit</em></strong> \nThe comment about endianness and struct padding are valid, and great, concerns. I have used this body of code almost entirely in embedded software, most of which I had control of both ends of the pipe.</p>\n"
},
{
"answer_id": 43527061,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>In early versions of C, all structure declarations would share a common set of fields. Given:</p>\n\n<pre><code>struct x {int x_mode; int q; float x_f};\nstruct y {int y_mode; int q; int y_l};\nstruct z {int z_mode; char name[20];};\n</code></pre>\n\n<p>a compiler would essentially produce a table of structures' sizes (and possibly alignments), and a separate table of structures' members' names, types, and offsets. The compiler didn't keep track of which members belonged to which structures, and would allow two structures to have a member with the same name only if the type and offset matched (as with member <code>q</code> of <code>struct x</code> and <code>struct y</code>). If p was a pointer to any structure type, p->q would add the offset of \"q\" to pointer p and fetch an \"int\" from the resulting address.</p>\n\n<p>Given the above semantics, it was possible to write a function that could perform some useful operations on multiple kinds of structure interchangeably, provided that all the fields used by the function lined up with useful fields within the structures in question. This was a useful feature, and changing C to validate members used for structure access against the types of the structures in question would have meant losing it in the absence of a means of having a structure that can contain multiple named fields at the same address. Adding \"union\" types to C helped fill that gap somewhat (though not, IMHO, as well as it should have been).</p>\n\n<p>An essential part of unions' ability to fill that gap was the fact that a pointer to a union member could be converted into a pointer to any union containing that member, and a pointer to any union could be converted to a pointer to any member. While the C89 Standard didn't expressly say that casting a <code>T*</code> directly to a <code>U*</code> was equivalent to casting it to a pointer to any union type containing both <code>T</code> and <code>U</code>, and then casting that to <code>U*</code>, no defined behavior of the latter cast sequence would be affected by the union type used, and the Standard didn't specify any contrary semantics for a direct cast from <code>T</code> to <code>U</code>. Further, in cases where a function received a pointer of unknown origin, the behavior of writing an object via <code>T*</code>, converting the <code>T*</code> to a <code>U*</code>, and then reading the object via <code>U*</code> would be equivalent to writing a union via member of type <code>T</code> and reading as type <code>U</code>, which would be standard-defined in a few cases (e.g. when accessing Common Initial Sequence members) and Implementation-Defined (rather than Undefined) for the rest. While it was rare for programs to exploit the CIS guarantees with actual objects of union type, it was far more common to exploit the fact that pointers to objects of unknown origin had to behave like pointers to union members and have the behavioral guarantees associated therewith.</p>\n"
},
{
"answer_id": 66085742,
"author": "Tejaswini",
"author_id": 5252118,
"author_profile": "https://Stackoverflow.com/users/5252118",
"pm_score": -1,
"selected": false,
"text": "<p>Use a union when you have some function where you return a value that can be different depending on what the function did.</p>\n"
},
{
"answer_id": 69955782,
"author": "Kerim FIRAT",
"author_id": 2499808,
"author_profile": "https://Stackoverflow.com/users/2499808",
"pm_score": 2,
"selected": false,
"text": "<p>union are used to save memory, especially used on devices with limited memory where memory is important.\nExp:</p>\n<pre><code>union _Union{\n int a;\n double b;\n char c;\n};\n</code></pre>\n<p>For example,let's say we need the above 3 data types(int,double,char) in a system where memory is limited.If we don't use "union",we need to define these 3 data types. In this case sizeof(a) + sizeof(b) + sizeof(c) memory space will be allocated.But if we use onion,only one memory space will be allocated according to the largest data t ype in these 3 data types.Because all variables in union structure will use the same memory space. Hence the memory space allocated accroding to the largest data type will be common space for all variables.\nFor example:</p>\n<pre><code>union _Union{\nint a;\ndouble b;\nchar c;\n};\n\nint main() {\n union _Union uni;\n uni.a = 44;\n uni.b = 144.5;\n printf("a:%d\\n",uni.a);\n printf("b:%lf\\n",uni.b);\n return 0;\n }\n</code></pre>\n<p>Output is:\na: 0\nand b:144.500000</p>\n<p>Why a is zero?. Because union structure has only one memory area and all data structures use it in common. So the last assigned value overwrites the old one.\nOne more example:</p>\n<pre><code> union _Union{\n char name[15];\n int id;\n};\n\n\nint main(){\n union _Union uni;\n char choice;\n printf("YOu can enter name or id value.");\n printf("Do you want to enter the name(y or n):");\n scanf("%c",&choice);\n if(choice == 'Y' || choice == 'y'){\n printf("Enter name:");\n scanf("%s",uni.name);\n printf("\\nName:%s",uni.name);\n }else{\n printf("Enter Id:");\n scanf("%d",&uni.id);\n printf("\\nId:%d",uni.id);\n }\nreturn 0;\n}\n</code></pre>\n<p>Note:Size of the union is the size of its largest field because sufficient number of bytes must be reserved to store the larges sized field.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
When should unions be used? Why do we need them?
|
Unions are often used to convert between the binary representations of integers and floats:
```
union
{
int i;
float f;
} u;
// Convert floating-point bits to integer:
u.f = 3.14159f;
printf("As integer: %08x\n", u.i);
```
Although this is technically undefined behavior according to the C standard (you're only supposed to read the field which was most recently written), it will act in a well-defined manner in virtually any compiler.
Unions are also sometimes used to implement pseudo-polymorphism in C, by giving a structure some tag indicating what type of object it contains, and then unioning the possible types together:
```
enum Type { INTS, FLOATS, DOUBLE };
struct S
{
Type s_type;
union
{
int s_ints[2];
float s_floats[2];
double s_double;
};
};
void do_something(struct S *s)
{
switch(s->s_type)
{
case INTS: // do something with s->s_ints
break;
case FLOATS: // do something with s->s_floats
break;
case DOUBLE: // do something with s->s_double
break;
}
}
```
This allows the size of `struct S` to be only 12 bytes, instead of 28.
|
252,575 |
<p>Can we call functions using function pointer? if yes how?</p>
|
[
{
"answer_id": 252579,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Yes you can.</p>\n"
},
{
"answer_id": 252581,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 4,
"selected": false,
"text": "<p>Yes. Trivial example:</p>\n\n<pre><code>\n// Functions that will be executed via pointer.\nint add(int i, int j) { return i+j; }\nint subtract(int i, int j) {return i-j; }\n\n// Enum selects one of the functions\ntypedef enum {\n ADD,\n SUBTRACT\n} OP;\n\n// Calculate the sum or difference of two ints.\nint math(int i, int j, OP op)\n{\n int (*func)(int i, int j); // Function pointer.\n\n // Set the function pointer based on the specified operation.\n switch (op)\n {\n case ADD: func = add; break;\n case SUBTRACT: func = subtract; break;\n default:\n // Handle error\n }\n\n return (*func)(i, j); // Call the selected function.\n}\n\n</code></pre>\n"
},
{
"answer_id": 252584,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 1,
"selected": false,
"text": "<p>Yes. An example: </p>\n\n<p>Before code...</p>\n\n<pre>\ntypedef int ( _stdcall *FilterTypeTranslatorType )\n (\n int TypeOfImportRecord,\n PMAType *PMA\n );\n\n\nFilterTypeTranslatorType FilterTypeTranslator = {NULL};\n</pre>\n\n<p>Now in the code...</p>\n\n<pre>\nPMAType *PMA;\nHANDLE hFilterDll;\n\n// assume DLL loaded\n// Now find the address...\n...\n FilterTypeTranslator[TheGroup] =\n ( FilterTypeTranslatorType ) GetProcAddress( hFilterDll,\n \"FilterTypeTranslator\" );\n...\n// now call it\n\n\nFilterTypeTranslator(1,PMA);\n... \n</pre>\n"
},
{
"answer_id": 252585,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 2,
"selected": false,
"text": "<p>Yes. Here's a <a href=\"http://www.newty.de/fpt/index.html\" rel=\"nofollow noreferrer\">good tutorial</a> with examples.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Can we call functions using function pointer? if yes how?
|
Yes. Trivial example:
```
// Functions that will be executed via pointer.
int add(int i, int j) { return i+j; }
int subtract(int i, int j) {return i-j; }
// Enum selects one of the functions
typedef enum {
ADD,
SUBTRACT
} OP;
// Calculate the sum or difference of two ints.
int math(int i, int j, OP op)
{
int (*func)(int i, int j); // Function pointer.
// Set the function pointer based on the specified operation.
switch (op)
{
case ADD: func = add; break;
case SUBTRACT: func = subtract; break;
default:
// Handle error
}
return (*func)(i, j); // Call the selected function.
}
```
|
252,588 |
<p>On large files (~200+ MB), I get the 503 error when I read the stream.</p>
<pre><code>ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name));
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)ftp.GetResponse();
</code></pre>
<p>Any clues on what I'm doing wrong or a better practice for larger files?</p>
|
[
{
"answer_id": 264122,
"author": "John Lemp",
"author_id": 12915,
"author_profile": "https://Stackoverflow.com/users/12915",
"pm_score": 3,
"selected": true,
"text": "<p>Do you receive the 503 after every attempt or only subsequent attempts?</p>\n\n<p>Have you tried setting the disabling KeepAlive?</p>\n\n<pre><code>ftp.KeepAlive = false;\n</code></pre>\n\n<p>I would try a more rubust ftp client library, a basic free one can be at <a href=\"http://sourceforge.net/projects/dotnetftpclient/\" rel=\"nofollow noreferrer\">sourceforge</a>.</p>\n"
},
{
"answer_id": 2409998,
"author": "adzm",
"author_id": 43784,
"author_profile": "https://Stackoverflow.com/users/43784",
"pm_score": 2,
"selected": false,
"text": "<p>For some reason, several people seem to have noticed some success with using only one instance of a NetworkCredential object rather than using a new one for each FtpWebRequest. This worked for me, at least.</p>\n"
},
{
"answer_id": 2774451,
"author": "bmacadam",
"author_id": 333582,
"author_profile": "https://Stackoverflow.com/users/333582",
"pm_score": 2,
"selected": false,
"text": "<p>I'd concur that minimizing the number of NetworkCredential objects solves the problem. I experienced this problem and created a single CredentialCache and added each credential once. No more ftp errors.</p>\n"
},
{
"answer_id": 21861475,
"author": "Mike Miller",
"author_id": 3324662,
"author_profile": "https://Stackoverflow.com/users/3324662",
"pm_score": 1,
"selected": false,
"text": "<p>The error is due to not allowing time for the server to log out. Use a try statement and when this error occurs, createa short time delay and have it start over. This will allow the server to logout from the last rrequest.</p>\n"
},
{
"answer_id": 39368278,
"author": "mrrrk",
"author_id": 155791,
"author_profile": "https://Stackoverflow.com/users/155791",
"pm_score": 0,
"selected": false,
"text": "<p>In my case, the server (belonging to a client) had been changed to only accept TLS (SSL) requests. They didn't tell us this of course and the 503 error message was not helpful!</p>\n\n<p>So we needed to use <code>.EnableSsl</code> like this:</p>\n\n<pre><code> var ftp = WebRequest.Create(uri) as FtpWebRequest;\n if (ftp != null) {\n ftp.EnableSsl = true; // <- the new bit\n ftp.Credentials = myCredentials;\n ftp.KeepAlive = false; // <- you may or may not want this\n }\n return ftp;\n</code></pre>\n\n<p>In order to ignore certificate errors, I also needed to add this: </p>\n\n<pre><code>System.Net.ServicePointManager.ServerCertificateValidationCallback +=\n (sender, certificate, chain, sslPolicyErrors) => true;\n</code></pre>\n\n<p>It's my understanding that this line has a global effect, so just need to call it when your application starts.</p>\n\n<p>:o)</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4068/"
] |
On large files (~200+ MB), I get the 503 error when I read the stream.
```
ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name));
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)ftp.GetResponse();
```
Any clues on what I'm doing wrong or a better practice for larger files?
|
Do you receive the 503 after every attempt or only subsequent attempts?
Have you tried setting the disabling KeepAlive?
```
ftp.KeepAlive = false;
```
I would try a more rubust ftp client library, a basic free one can be at [sourceforge](http://sourceforge.net/projects/dotnetftpclient/).
|
252,611 |
<p>I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as </p>
<blockquote>
<p>[A-Za-z]</p>
</blockquote>
<p>would lock down to just Alpha characters. </p>
<pre><code>protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
base.OnKeyPress(e);
return;
}
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
base.OnKeyPress(e);
}
else
{
bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
if (isValidChar)
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
}
</code></pre>
<p>I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.</p>
<p>As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.</p>
<p>What is the best way to handle this situation?</p>
|
[
{
"answer_id": 252693,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you put the check for valid characters in the OnTextChanged event</p>\n\n<p>and then deal with the Ctrl+C, Ctrl+V in the on key down</p>\n\n<p>Also you can use the e.ModifierKeys == Keys.Control to test for control keys</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.keypresseventargs.aspx</a></p>\n"
},
{
"answer_id": 252747,
"author": "Jimmy",
"author_id": 25071,
"author_profile": "https://Stackoverflow.com/users/25071",
"pm_score": 2,
"selected": false,
"text": "<p>What if you put the validation in OnTextChanged instead of OnKeyPress, but each time it passes validation you save the value to a variable? Then you can revert if the user pastes or types an incorrect string, as well as give some other UI hint that something was invalid (e.g. set a Label's text).</p>\n"
},
{
"answer_id": 252805,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(VS.80).aspx\" rel=\"nofollow noreferrer\">MaskedTextBox</a> may be right for you.</p>\n\n<p>You can also look at the <a href=\"http://www.codeproject.com/KB/miscctrl/FilterTextBox.aspx\" rel=\"nofollow noreferrer\">FilterTextBox</a> over at CodeProjct. You can use it (or the approach described) to do what you intend. The basic idea is to cancel the change before it is becoming visible (via an OnTextChanging event).</p>\n"
},
{
"answer_id": 252839,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 1,
"selected": true,
"text": "<p>You can use one of the OnKeyPress / OnKeyUp / OkKeyDown events and then use the Char.IsLetter method to check that the entered key is a letter.</p>\n"
},
{
"answer_id": 304014,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "<p>The solution that I have come up with is to check the keys in the OnKeyDown event and then setting a flag if the keypress should be handled, which is then check in the OnKeyPress event.</p>\n\n<pre><code>protected override void OnKeyDown(KeyEventArgs e)\n {\n Keys keyCode = (Keys)e.KeyValue;\n base.OnKeyDown(e);\n if ((e.Modifiers == Keys.Control) ||\n (e.Modifiers == Keys.Control) ||\n (keyCode == Keys.Back) ||\n (keyCode == Keys.Delete))\n {\n this._handleKey = true;\n }\n else\n {\n // check if the key is valid and set the flag\n this._handleKey = Regex.Match(key.ToString(), this._ValidCharExpression).Success;\n }\n }\n\n\n\n\nprotected override void OnKeyPress(KeyPressEventArgs e)\n {\n if (this._handleKey)\n {\n base.OnKeyPress(e);\n this._handleKey = false;\n }\n else\n {\n e.Handled = true;\n }\n }\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4490/"
] |
I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as
>
> [A-Za-z]
>
>
>
would lock down to just Alpha characters.
```
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
base.OnKeyPress(e);
return;
}
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
base.OnKeyPress(e);
}
else
{
bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
if (isValidChar)
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
}
```
I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.
As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.
What is the best way to handle this situation?
|
You can use one of the OnKeyPress / OnKeyUp / OkKeyDown events and then use the Char.IsLetter method to check that the entered key is a letter.
|
252,615 |
<p>I have got the following problem since the server has safe mode turned on, and directories are being created under different users:</p>
<ol>
<li>I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.</li>
<li>New directory is created, but it belongs to 'apache' user.</li>
<li>'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.</li>
<li>Now I have a problem!</li>
</ol>
<p>One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.</p>
<p>But I have to ask. Is there a programatical solution for my problem?</p>
<p>I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.</p>
|
[
{
"answer_id": 252645,
"author": "mlambie",
"author_id": 17453,
"author_profile": "https://Stackoverflow.com/users/17453",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to turn safe mode off for a specific directory via a .htaccess file (if on Apache). </p>\n\n<pre><code>php_value safe_mode = Off\n</code></pre>\n\n<p>You might need to get your hosting provider to make this change for you though in the httpd.conf.</p>\n"
},
{
"answer_id": 252646,
"author": "Luis Melgratti",
"author_id": 17032,
"author_profile": "https://Stackoverflow.com/users/17032",
"pm_score": 3,
"selected": true,
"text": "<p>I've used this workaround:</p>\n\n<p>instead of php mkdir you can create directories by FTP with proper rights.</p>\n\n<pre><code> function FtpMkdir($path, $newDir) {\n $path = 'mainwebsite_html/'.$path;\n $server='ftp.myserver.com'; // ftp server\n $connection = ftp_connect($server); // connection\n\n\n // login to ftp server\n $user = \"[email protected]\";\n $pass = \"password\";\n $result = ftp_login($connection, $user, $pass);\n\n // check if connection was made\n if ((!$connection) || (!$result)) {\n return false;\n exit();\n } else {\n ftp_chdir($connection, $path); // go to destination dir\n if(ftp_mkdir($connection, $newDir)) { // create directory\n ftp_site($connection, \"CHMOD 777 $newDir\") or die(\"FTP SITE CMD failed.\");\n return $newDir;\n } else {\n return false;\n }\n\n ftp_close($connection); // close connection\n }\n\n } \n</code></pre>\n"
},
{
"answer_id": 8946618,
"author": "GDmac",
"author_id": 25286,
"author_profile": "https://Stackoverflow.com/users/25286",
"pm_score": 0,
"selected": false,
"text": "<p>I have had some success with setting the group bit of the upload directory to sticky.\nPHP can then create directories inside it and write to it.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Setuid#setuid_and_setgid_on_directories\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Setuid#setuid_and_setgid_on_directories</a> </p>\n\n<p>chmod g+s <em>directory</em></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
] |
I have got the following problem since the server has safe mode turned on, and directories are being created under different users:
1. I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.
2. New directory is created, but it belongs to 'apache' user.
3. 'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.
4. Now I have a problem!
One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.
But I have to ask. Is there a programatical solution for my problem?
I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.
|
I've used this workaround:
instead of php mkdir you can create directories by FTP with proper rights.
```
function FtpMkdir($path, $newDir) {
$path = 'mainwebsite_html/'.$path;
$server='ftp.myserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp server
$user = "[email protected]";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
```
|
252,626 |
<p>I've got the following url route and i'm wanting to make sure that a segment of the route will only accept numbers. as such, i can provide some regex which checks the word.</p>
<p>/page/{currentPage}</p>
<p>so.. can someone give me a regex which matches when the word is a number (any int) greater than 0 (ie. 1 <-> int.max).</p>
|
[
{
"answer_id": 252634,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>If you want it greater than 0, use this regex:</p>\n\n<pre><code>/([1-9][0-9]*)/\n</code></pre>\n\n<p>This'll work as long as the number doesn't have leading zeros (like '03').</p>\n\n<p>However, I recommend just using a simple <code>[0-9]+</code> regex, and validating the number in your actual site code.</p>\n"
},
{
"answer_id": 252641,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string testString = @\"/page/100\";\nstring pageNumber = Regex.Match(testString, \"/page/([1-9][0-9]*)\").Groups[1].Value;\n</code></pre>\n\n<p>If not matched pageNumber will be \"\"</p>\n"
},
{
"answer_id": 252688,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 6,
"selected": true,
"text": "<pre><code>/^[1-9][0-9]*$/\n</code></pre>\n\n<p>Problems with other answers:</p>\n\n<pre><code>/([1-9][0-9]*)/ // Will match -1 and foo1bar\n#[1-9]+# // Will not match 10, same problems as the first\n[1-9] // Will only match one digit, same problems as first\n</code></pre>\n"
},
{
"answer_id": 252730,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>While Jeremy's regex isn't perfect (should be tested in context, against leading characters and such), his advice is good: go for a generic, simple regex (eg. if you must use it in Apache's mod_rewrite) but by any means, handle the final redirect in server's code (if you can) and do a real check of parameter's validity there.</p>\n\n<p>Otherwise, I would improve Jeremy's expression with bounds: <code>/\\b([1-9][0-9]*)$/</code><br>\nOf course, a regex cannot provide a check against <em>any</em> max int, at best you can control the number of digits: <code>/\\b([1-9][0-9]{0,2})$/</code> for example.</p>\n"
},
{
"answer_id": 253592,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 0,
"selected": false,
"text": "<p>This will match any string such that, if it contains <code>/page/</code>, it <em>must</em> be followed by a number, not consisting of <em>only</em> zeros.</p>\n\n<pre><code>^(?!.*?/page/([0-9]*[^0-9/]|0*/))\n</code></pre>\n\n<p><code>(?! )</code> is a negative look-ahead. It will match an empty string, only if it's contained pattern does <em>not</em> match from the current position.</p>\n"
},
{
"answer_id": 253604,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 1,
"selected": false,
"text": "<p>This one would address your specific problem. This expression</p>\n\n<pre><code>/\\/page\\/(0*[1-9][0-9]*)/ or \"Perl-compatible\" /\\/page\\/(0*[1-9]\\d*)/\n</code></pre>\n\n<p>should capture any non-zero number, even 0-filled. And because it doesn't even <em>look</em> for a sign, <code>-</code> after the slash will not fit the pattern.</p>\n\n<p>The problem that I have with eyelidlessness' expression is that, likely you do not already have the number isolated so that <code>^</code> and <code>$</code> would work. You're going to have to do some work <em>to isolate</em> it. But a general solution would not be to assume that the number is all that a string contains, as below.</p>\n\n<pre><code>/(^|[^0-9-])(0*[1-9][0-9]*)([^0-9]|$)/\n</code></pre>\n\n<p>And the two tail-end groups, you could replace with <em>word boundary</em> marks (<code>\\b</code>), if the RE language had those. Failing that you would put them into non-capturing groups, if the language had them, or even lookarounds if it had those--but it would more likely have word boundaries before lookarounds. </p>\n\n<p>Full <em>Perl-compatible</em> version: </p>\n\n<pre><code>/(?<![\\d-])(0*[1-9]\\d*)\\b/\n</code></pre>\n\n<p>I chose a negative lookbehind instead of a word boundary, because '-' is not a word-character, and so -1 will have a \"word boundary\" between the '-' and the '1'. And a negative lookbehind will match the beginning of the string--there just can't be a digit character or '-' in front. </p>\n\n<p>You could say that the zero-width assumption <code>^</code> is just one of the cases that satisfies the zero-width assumption <code>(?<![\\d-])</code>. </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
I've got the following url route and i'm wanting to make sure that a segment of the route will only accept numbers. as such, i can provide some regex which checks the word.
/page/{currentPage}
so.. can someone give me a regex which matches when the word is a number (any int) greater than 0 (ie. 1 <-> int.max).
|
```
/^[1-9][0-9]*$/
```
Problems with other answers:
```
/([1-9][0-9]*)/ // Will match -1 and foo1bar
#[1-9]+# // Will not match 10, same problems as the first
[1-9] // Will only match one digit, same problems as first
```
|
252,644 |
<p>Here is one of my header file which consists of a union template with 4 different structures.</p>
<pre><code>#define MAX 3
union family
{
struct name /*for taking the name and gender of original member*/
{
unsigned char *namess;
unsigned int gender;
union family *ptr_ancestor; /*this is a pointer to his ancestors details*/
}names;
struct male /*for taking the above person's 3 male ancestors details if he is male*/
{
unsigned char husb_names[3][20];
unsigned char wife_names[3][20];
unsigned int wife_status[3];
}male_ancestor;
struct unmarry /*for taking the above person's 3 female parental ancestors if she is female and unmarried*/
{
unsigned int mar;
unsigned char parental_fem[3][20];
unsigned int marit_status[3];
}fem_un;
struct marry /*for taking 3 parental-in-laws details if she is female and married*/
{
unsigned int mar;
unsigned char in_law_fem[3][20];
unsigned int in_marit_status[3];
}fem_marr;
};
extern union family original[MAX]; /*for original person*/
extern union family ancestor_male[MAX]; /*used if he is male for storing his male ancestor details*/
extern union family ancestor_female[MAX]; /*used if she is female*/
extern int x;
</code></pre>
<p>My aim is to get a person name and gender and store the person's any 3 male/female ancestors according to the person's gender and marital status as follows..</p>
<p>I mean that <code>MAX</code> will have 3 members and each will be having 3 ancestors. These ancestors will be determined by the gender the corresponding member like the following conditions:</p>
<ul>
<li>if male then use <code>struct male</code></li>
<li>if female unmarried use <code>struct unmarry</code></li>
<li>if female married use <code>struct marry</code></li>
</ul>
<p><code>struct name</code> is for the member name and gender for whom we have to take ancestors and point the <code>*ptr_ancestor</code> to that corresponding ancestor array (ancestormale or ancestorfemale).</p>
<p>The object in memory is a union. Ok. My program will have an array of unions, in fact. Each element of the array may be using a different structure in the union.
Here we should be careful in assigning the pointer or else we may loose our older person records at run time.</p>
<p>If possible please tell me how to get the details of 1st element ie. <code>original[0]</code> even after taking the <code>original[1]</code>. Here I am just getting the last element of the array, and all previous records are gone at run time. I am not using any other data structures or files.</p>
<p>My environment is Turbo C on Windows.</p>
|
[
{
"answer_id": 252657,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>Do you know what union means in C? Your union doesn't have 3 members. Your union has 4 members. Among those 4 members, how many do you want to store values in?</p>\n\n<p>Why didn't you ask your TA?</p>\n"
},
{
"answer_id": 252667,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>You may be misunderstanding the purpose of a union.</p>\n\n<p>A union is typically used to store <strong>one</strong> item that may be in one of several forms. For example:</p>\n\n<pre><code>// Define an array of 20 employees, each identified either by name or ID.\nunion ID {\n char name[10]; // ID may be a name up to 10 chars...\n int serialNum; // ... or it may be a serial number.\n} employees[20];\n\n// Store some data.\nemployees[0].serialNum = 123;\nstrcpy(employees[1].name, \"Manoj\");\n</code></pre>\n\n<p>The critical difference between a <code>struct</code> and a <code>union</code> is that a <code>struct</code> is an aggregate of many pieces of data, but a <code>union</code> is an <em>overlayment</em>: you may store only <em>one</em> of the elements because they all share the same memory. In the example above, each element in the <code>employees[]</code> array consists of 10 bytes, which is the smallest amount of memory that can hold <em>either</em> 10 <code>char</code>s <em>or</em> 1 <code>int</code>. If you reference the <code>name</code> element, you can store 10 <code>char</code>s. If you reference the <code>serialNum</code> element, you can store 1 <code>int</code> (say 4 bytes) and cannot access the remaining 6 bytes.</p>\n\n<p>So I think you want to use different, separate structures to represent the family members. What you've done appears to be cramming several square pegs into one round homework assignment. :-)</p>\n\n<p><em>Note for advanced readers: please don't mention padding and word alignment. They're probably covered next semester. :-)</em></p>\n"
},
{
"answer_id": 252720,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": 3,
"selected": true,
"text": "<p>You need to read this <a href=\"https://stackoverflow.com/questions/252552/unions-in-c\">question about unions</a>. You want something more like:</p>\n\n<pre><code>struct family {\n struct name { \n int gender;\n int married;\n blah\n } names;\n union {\n struct male { blah } male_ancestor;\n struct female_unmarried { blah } female_unmarried_ancestor;\n struct female_married { blah } female_married_ancestor;\n };\n}\n</code></pre>\n\n<p>then you can test family.names.gender and family.names.married to determine which member of the union to use.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
Here is one of my header file which consists of a union template with 4 different structures.
```
#define MAX 3
union family
{
struct name /*for taking the name and gender of original member*/
{
unsigned char *namess;
unsigned int gender;
union family *ptr_ancestor; /*this is a pointer to his ancestors details*/
}names;
struct male /*for taking the above person's 3 male ancestors details if he is male*/
{
unsigned char husb_names[3][20];
unsigned char wife_names[3][20];
unsigned int wife_status[3];
}male_ancestor;
struct unmarry /*for taking the above person's 3 female parental ancestors if she is female and unmarried*/
{
unsigned int mar;
unsigned char parental_fem[3][20];
unsigned int marit_status[3];
}fem_un;
struct marry /*for taking 3 parental-in-laws details if she is female and married*/
{
unsigned int mar;
unsigned char in_law_fem[3][20];
unsigned int in_marit_status[3];
}fem_marr;
};
extern union family original[MAX]; /*for original person*/
extern union family ancestor_male[MAX]; /*used if he is male for storing his male ancestor details*/
extern union family ancestor_female[MAX]; /*used if she is female*/
extern int x;
```
My aim is to get a person name and gender and store the person's any 3 male/female ancestors according to the person's gender and marital status as follows..
I mean that `MAX` will have 3 members and each will be having 3 ancestors. These ancestors will be determined by the gender the corresponding member like the following conditions:
* if male then use `struct male`
* if female unmarried use `struct unmarry`
* if female married use `struct marry`
`struct name` is for the member name and gender for whom we have to take ancestors and point the `*ptr_ancestor` to that corresponding ancestor array (ancestormale or ancestorfemale).
The object in memory is a union. Ok. My program will have an array of unions, in fact. Each element of the array may be using a different structure in the union.
Here we should be careful in assigning the pointer or else we may loose our older person records at run time.
If possible please tell me how to get the details of 1st element ie. `original[0]` even after taking the `original[1]`. Here I am just getting the last element of the array, and all previous records are gone at run time. I am not using any other data structures or files.
My environment is Turbo C on Windows.
|
You need to read this [question about unions](https://stackoverflow.com/questions/252552/unions-in-c). You want something more like:
```
struct family {
struct name {
int gender;
int married;
blah
} names;
union {
struct male { blah } male_ancestor;
struct female_unmarried { blah } female_unmarried_ancestor;
struct female_married { blah } female_married_ancestor;
};
}
```
then you can test family.names.gender and family.names.married to determine which member of the union to use.
|
252,660 |
<p>How can I delete the session information from my browser by using javascript? Is it possible to do?</p>
|
[
{
"answer_id": 252675,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 1,
"selected": false,
"text": "<p>Session information is usually stored on the server. An HTTP request to a page that destroys the session would normally do the trick (using AJAX if you wish).</p>\n\n<p>For cookies you can set the cookie expiry date to the current date, this will expire the cookie and remove it.</p>\n\n<pre><code>var d = new Date();\ndocument.cookie = \"cookiename=1;expires=\" + d.toGMTString() + \";\" + \";\";\n</code></pre>\n"
},
{
"answer_id": 252697,
"author": "andyk",
"author_id": 26721,
"author_profile": "https://Stackoverflow.com/users/26721",
"pm_score": 1,
"selected": false,
"text": "<p>Basically all that you need is to set cookie's expiry date to some date in the past.</p>\n\n<pre><code>var cookie_date = new Date ( ); // now\ncookie_date.setTime ( cookie_date.getTime() - 1 ); // one second before now.\n// empty cookie's value and set the expiry date to a time in the past.\ndocument.cookie = \"logged_in=;\n expires=\" + cookie_date.toGMTString();\n</code></pre>\n\n<p>Click <a href=\"http://techpatterns.com/downloads/javascript_cookies.php\" rel=\"nofollow noreferrer\">here</a> or <a href=\"http://www.elated.com/articles/javascript-and-cookies/\" rel=\"nofollow noreferrer\">here</a> for more informations.</p>\n"
},
{
"answer_id": 252719,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't set an expiry date to a cookie, by definition it is only session lived. Ie. it will be deleted when the user will close his browser. Thus, no need for clean up.</p>\n"
},
{
"answer_id": 252912,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to the expiration we have been writing a value \"deleted\" or similar to the cookie. In some cases we've discovered that the cookies don't expire immediately and accessing them from js might give false results for a short while.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I delete the session information from my browser by using javascript? Is it possible to do?
|
Session information is usually stored on the server. An HTTP request to a page that destroys the session would normally do the trick (using AJAX if you wish).
For cookies you can set the cookie expiry date to the current date, this will expire the cookie and remove it.
```
var d = new Date();
document.cookie = "cookiename=1;expires=" + d.toGMTString() + ";" + ";";
```
|
252,665 |
<p>I need to get all the <em>cookies</em> stored in my browser using JavaScript. How can it be done? </p>
|
[
{
"answer_id": 252684,
"author": "Codeslayer",
"author_id": 4021,
"author_profile": "https://Stackoverflow.com/users/4021",
"pm_score": 4,
"selected": false,
"text": "<p>To retrieve all cookies for the current document open in the browser, you again use the <code>document.cookie</code> property.</p>\n"
},
{
"answer_id": 252710,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": false,
"text": "<p>You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.</p>\n"
},
{
"answer_id": 252727,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 6,
"selected": false,
"text": "<ol>\n<li>You can't see cookies for other sites.</li>\n<li>You can't see <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies\" rel=\"noreferrer\"><code>HttpOnly</code></a> cookies.</li>\n<li>All the cookies you can see are in the <a href=\"http://msdn.microsoft.com/en-us/magazine/ms533693.aspx\" rel=\"noreferrer\"><code>document.cookie</code></a> property, which contains a <em>semicolon</em> separated list of <code>name=value</code> pairs.</li>\n</ol>\n"
},
{
"answer_id": 252959,
"author": "aemkei",
"author_id": 28150,
"author_profile": "https://Stackoverflow.com/users/28150",
"pm_score": 7,
"selected": false,
"text": "<p>You can only access cookies for a specific site. Using <strong><code>document.cookie</code></strong> you will get a list of escaped key=value pairs seperated by a semicolon.</p>\n\n<pre><code>secret=do%20not%20tell%you;last_visit=1225445171794\n</code></pre>\n\n<p>To simplify the access, you have to parse the string and unescape all entries:</p>\n\n<pre><code>var getCookies = function(){\n var pairs = document.cookie.split(\";\");\n var cookies = {};\n for (var i=0; i<pairs.length; i++){\n var pair = pairs[i].split(\"=\");\n cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));\n }\n return cookies;\n}\n</code></pre>\n\n<p>So you might later write: </p>\n\n<pre><code>var myCookies = getCookies();\nalert(myCookies.secret); // \"do not tell you\"\n</code></pre>\n"
},
{
"answer_id": 15129669,
"author": "ZXX",
"author_id": 374835,
"author_profile": "https://Stackoverflow.com/users/374835",
"pm_score": 2,
"selected": false,
"text": "<p>Since the title didn't specify that it has to be programmatic I'll assume that it was a genuine debugging/privacy management issue and solution is browser dependent and requires a browser with built in detailed cookie management toll and/or a debugging module or a plug-in/extension. I'm going to list one and ask other people to write up on browsers they know in detail and please be precise with versions.</p>\n\n<p><strong>Chromium, Iron build (SRWare Iron 4.0.280)</strong></p>\n\n<blockquote>\n <p>The wrench(tool) menu: Options / Under The Hood / [Show cookies and website permissions]\n For related domains/sites type the suffix into the search box (like .foo.tv). Caveat: when you have a node (site or cookie) click-highlighted only use [Remove] to kill specific subtrees. Using [Remove All] will still delete cookies for all sites selected by search and waste your debugging session.</p>\n</blockquote>\n"
},
{
"answer_id": 56052470,
"author": "Prabu samvel",
"author_id": 7194437,
"author_profile": "https://Stackoverflow.com/users/7194437",
"pm_score": 2,
"selected": false,
"text": "<p>Modern approach. </p>\n\n<pre><code>let c = document.cookie.split(\";\").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});\n\nconsole.log(c);\n</code></pre>\n\n<p>;)</p>\n"
},
{
"answer_id": 56071867,
"author": "Netanel R",
"author_id": 7323168,
"author_profile": "https://Stackoverflow.com/users/7323168",
"pm_score": 2,
"selected": false,
"text": "<p>Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.</p>\n\n<pre><code>export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});\n</code></pre>\n"
},
{
"answer_id": 58957023,
"author": "zemil",
"author_id": 8410290,
"author_profile": "https://Stackoverflow.com/users/8410290",
"pm_score": 1,
"selected": false,
"text": "<p>If you develop <a href=\"https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions\" rel=\"nofollow noreferrer\">browser extensions</a> you can try <a href=\"https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/getAll\" rel=\"nofollow noreferrer\">browser.cookies.getAll()</a></p>\n"
},
{
"answer_id": 63145220,
"author": "Emeka Augustine",
"author_id": 9615156,
"author_profile": "https://Stackoverflow.com/users/9615156",
"pm_score": 0,
"selected": false,
"text": "<p>What you are asking is possible; but that will only work on a specific browser. You have to develop a browser extension app to achieve this. You can read more about chrome api to understand better. <a href=\"https://developer.chrome.com/extensions/cookies\" rel=\"nofollow noreferrer\">https://developer.chrome.com/extensions/cookies</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to get all the *cookies* stored in my browser using JavaScript. How can it be done?
|
You can only access cookies for a specific site. Using **`document.cookie`** you will get a list of escaped key=value pairs seperated by a semicolon.
```
secret=do%20not%20tell%you;last_visit=1225445171794
```
To simplify the access, you have to parse the string and unescape all entries:
```
var getCookies = function(){
var pairs = document.cookie.split(";");
var cookies = {};
for (var i=0; i<pairs.length; i++){
var pair = pairs[i].split("=");
cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
}
return cookies;
}
```
So you might later write:
```
var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"
```
|
252,689 |
<p>We had a performance issue with DataGridViews where the redraw was horridly slow and found the solution <a href="https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens">Here</a> to create a derived type and enable double buffering on the control.
(Derived type is necessary since the DoubleBuffered property is protected)</p>
<p>It doesn't seem like there's any drawback to having the DoubleBuffered property set to true.</p>
|
[
{
"answer_id": 252863,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 3,
"selected": false,
"text": "<p>Double buffering by definition uses two buffers and twice the memory for rendering the view of the control into. So, there is some drawback there, however, with the amount of memory you get in a PC now, not many people probably would notice the sacrifice.</p>\n\n<p>No idea why its protected. Maybe the function wasn't available in an early version of the control, and when it was introduced the designers didn't want to change the public interface of the control. Or perhaps they considered it to be an advanced feature and wanted to limit the number of methods someone new to the control would have to grok to be able to make it do something useful.</p>\n"
},
{
"answer_id": 254874,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 4,
"selected": false,
"text": "<p>It is protected because DGV inherits the property from Control. And Control.DoubleBuffered is protected. Which makes sense because each derived control should decide for itself to turn that on. And it doesn't make sense for the control user to arbitrarily turn it on or off. The DGV designers decided for off.</p>\n\n<p>One reason they might have decided that is that double buffering actually makes painting slower. The extra step to render the buffer bitmap costs time. It just looks faster to the human eye, you observe the bitmap suddenly appearing. You can't see the time it takes to draw into the bitmap. Unless other controls need to be painted and they get their turn after the DGV, then it is quite visible.</p>\n\n<p>What you see is the form getting drawn first, with holes where the controls go. Those holes have a white background. Black when you use the TransparencyKey or Opacity property. Each control then gets the Paint event and the holes are filled one-by-one. That effect is perceived as flicker too by the user, although it is a different kind of flicker from the one that DoubleBuffered solves. It is especially noticeable when the background is black.</p>\n\n<p>What's needed to solve this problem is that the entire form, with all its controls, is double-buffered. That's not available in Windows Forms. However, Windows XP and later actually support this. Check <a href=\"http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c\" rel=\"noreferrer\">this thread</a> to see how that's done. Beware that it can have side-effects as documented in that thread.</p>\n"
},
{
"answer_id": 1665995,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Inheritance is not needed to <a href=\"http://bitmatic.com/csharp/fixing-a-slow-scrolling-datagridview\" rel=\"nofollow noreferrer\">turn on doublebuffering on a datagridview</a>. You can do it with reflection on an existing datagridview.</p>\n"
},
{
"answer_id": 10277205,
"author": "Dawid Moś",
"author_id": 665695,
"author_profile": "https://Stackoverflow.com/users/665695",
"pm_score": 5,
"selected": false,
"text": "<p>I think its best solution:</p>\n\n<pre><code>typeof(DataGridView).InvokeMember(\n \"DoubleBuffered\", \n BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,\n null, \n myDataGridViewObject, \n new object[] { true });\n</code></pre>\n\n<p>found <a href=\"https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens\">here</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252689",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12685/"
] |
We had a performance issue with DataGridViews where the redraw was horridly slow and found the solution [Here](https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens) to create a derived type and enable double buffering on the control.
(Derived type is necessary since the DoubleBuffered property is protected)
It doesn't seem like there's any drawback to having the DoubleBuffered property set to true.
|
I think its best solution:
```
typeof(DataGridView).InvokeMember(
"DoubleBuffered",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty,
null,
myDataGridViewObject,
new object[] { true });
```
found [here](https://stackoverflow.com/questions/118528/horrible-redraw-performance-of-the-datagridview-on-one-of-my-two-screens)
|
252,703 |
<p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p>
|
[
{
"answer_id": 252704,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 7,
"selected": false,
"text": "<p><code>append</code> appends a single element. <code>extend</code> appends a list of elements.</p>\n\n<p>Note that if you pass a list to append, it still adds one element:</p>\n\n<pre><code>>>> a = [1, 2, 3]\n>>> a.append([4, 5, 6])\n>>> a\n[1, 2, 3, [4, 5, 6]]\n</code></pre>\n"
},
{
"answer_id": 252705,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 9,
"selected": false,
"text": "<p><code>append</code> adds an element to a list. <code>extend</code> concatenates the first list with another list/iterable.</p>\n<pre><code>>>> xs = ['A', 'B']\n>>> xs\n['A', 'B']\n\n>>> xs.append("D")\n>>> xs\n['A', 'B', 'D']\n\n>>> xs.append(["E", "F"])\n>>> xs\n['A', 'B', 'D', ['E', 'F']]\n\n>>> xs.insert(2, "C")\n>>> xs\n['A', 'B', 'C', 'D', ['E', 'F']]\n\n>>> xs.extend(["G", "H"])\n>>> xs\n['A', 'B', 'C', 'D', ['E', 'F'], 'G', 'H']\n</code></pre>\n"
},
{
"answer_id": 252711,
"author": "kender",
"author_id": 4172,
"author_profile": "https://Stackoverflow.com/users/4172",
"pm_score": 13,
"selected": true,
"text": "<p><a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"noreferrer\"><code>append</code></a> appends a specified object at the end of the list:</p>\n<pre><code>>>> x = [1, 2, 3]\n>>> x.append([4, 5])\n>>> print(x)\n[1, 2, 3, [4, 5]]\n</code></pre>\n<p><a href=\"https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types\" rel=\"noreferrer\"><code>extend</code></a> extends the list by appending elements from the specified iterable:</p>\n<pre><code>>>> x = [1, 2, 3]\n>>> x.extend([4, 5])\n>>> print(x)\n[1, 2, 3, 4, 5]\n</code></pre>\n"
},
{
"answer_id": 12045242,
"author": "Erik",
"author_id": 1080125,
"author_profile": "https://Stackoverflow.com/users/1080125",
"pm_score": 6,
"selected": false,
"text": "<p>The following two snippets are semantically equivalent:</p>\n\n<pre><code>for item in iterator:\n a_list.append(item)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>a_list.extend(iterator)\n</code></pre>\n\n<p>The latter may be faster as the loop is implemented in C.</p>\n"
},
{
"answer_id": 16510635,
"author": "kiriloff",
"author_id": 1141493,
"author_profile": "https://Stackoverflow.com/users/1141493",
"pm_score": 5,
"selected": false,
"text": "<p><code>extend()</code> can be used with an iterator argument. Here is an example. You wish to make a list out of a list of lists this way:</p>\n\n<p>From</p>\n\n<pre><code>list2d = [[1,2,3],[4,5,6], [7], [8,9]]\n</code></pre>\n\n<p>you want</p>\n\n<pre><code>>>>\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n</code></pre>\n\n<p>You may use <code>itertools.chain.from_iterable()</code> to do so. This method's output is an iterator. Its implementation is equivalent to</p>\n\n<pre><code>def from_iterable(iterables):\n # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F\n for it in iterables:\n for element in it:\n yield element\n</code></pre>\n\n<p>Back to our example, we can do</p>\n\n<pre><code>import itertools\nlist2d = [[1,2,3],[4,5,6], [7], [8,9]]\nmerged = list(itertools.chain.from_iterable(list2d))\n</code></pre>\n\n<p>and get the wanted list.</p>\n\n<p>Here is how equivalently <code>extend()</code> can be used with an iterator argument:</p>\n\n<pre><code>merged = []\nmerged.extend(itertools.chain.from_iterable(list2d))\nprint(merged)\n>>>\n[1, 2, 3, 4, 5, 6, 7, 8, 9]\n</code></pre>\n"
},
{
"answer_id": 16511403,
"author": "Chaitanya",
"author_id": 202507,
"author_profile": "https://Stackoverflow.com/users/202507",
"pm_score": 5,
"selected": false,
"text": "<p><code>append(object)</code> updates the list by adding the object to the list.</p>\n<pre><code>x = [20]\n# List passed to the append(object) method is treated as a single object.\nx.append([21, 22, 23])\n# Hence the resultant list length will be 2\nprint(x)\n--> [20, [21, 22, 23]]\n</code></pre>\n<p><code>extend(list)</code> concatenates the two lists essentially.</p>\n<pre><code>x = [20]\n# The parameter passed to extend(list) method is treated as a list.\n# Eventually it is two lists being concatenated.\nx.extend([21, 22, 23])\n# Here the resultant list's length is 4\nprint(x)\n--> [20, 21, 22, 23]\n</code></pre>\n"
},
{
"answer_id": 18442908,
"author": "denfromufa",
"author_id": 2230844,
"author_profile": "https://Stackoverflow.com/users/2230844",
"pm_score": 5,
"selected": false,
"text": "<p>You can use \"+\" for returning extend, instead of extending in place.</p>\n\n<pre><code>l1=range(10)\n\nl1+[11]\n\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]\n\nl2=range(10,1,-1)\n\nl1+l2\n\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2]\n</code></pre>\n\n<p>Similarly <code>+=</code> for in place behavior, but with slight differences from <code>append</code> & <code>extend</code>. One of the biggest differences of <code>+=</code> from <code>append</code> and <code>extend</code> is when it is used in function scopes, see <a href=\"https://www.toptal.com/python/top-10-mistakes-that-python-programmers-make?utm_medium=referral&utm_source=zeef.com&utm_campaign=ZEEF\" rel=\"noreferrer\">this blog post</a>.</p>\n"
},
{
"answer_id": 19707477,
"author": "CodyChan",
"author_id": 1528712,
"author_profile": "https://Stackoverflow.com/users/1528712",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>append()</code> method adds a single item to the end of the list.</p>\n\n<pre><code>x = [1, 2, 3]\nx.append([4, 5])\nx.append('abc')\nprint(x)\n# gives you\n[1, 2, 3, [4, 5], 'abc']\n</code></pre>\n\n<p>The <code>extend()</code> method takes one argument, a list, and appends each of the items of the argument to the original list. (Lists are implemented as classes. “Creating” a list is really instantiating a class. As such, a list has methods that operate on it.)</p>\n\n<pre><code>x = [1, 2, 3]\nx.extend([4, 5])\nx.extend('abc')\nprint(x)\n# gives you\n[1, 2, 3, 4, 5, 'a', 'b', 'c']\n</code></pre>\n\n<p>From <em><a href=\"https://rads.stackoverflow.com/amzn/click/com/1430224150\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Dive Into Python</a></em>.</p>\n"
},
{
"answer_id": 24632188,
"author": "skdev75",
"author_id": 3138785,
"author_profile": "https://Stackoverflow.com/users/3138785",
"pm_score": 5,
"selected": false,
"text": "<p>This is the equivalent of <code>append</code> and <code>extend</code> using the <code>+</code> operator:</p>\n\n<pre><code>>>> x = [1,2,3]\n>>> x\n[1, 2, 3]\n>>> x = x + [4,5,6] # Extend\n>>> x\n[1, 2, 3, 4, 5, 6]\n>>> x = x + [[7,8]] # Append\n>>> x\n[1, 2, 3, 4, 5, 6, [7, 8]]\n</code></pre>\n"
},
{
"answer_id": 25144368,
"author": "bconstanzo",
"author_id": 3594441,
"author_profile": "https://Stackoverflow.com/users/3594441",
"pm_score": 4,
"selected": false,
"text": "<p>An interesting point that has been hinted, but not explained, is that extend is faster than append. For any loop that has append inside should be considered to be replaced by list.extend(processed_elements).</p>\n\n<p>Bear in mind that apprending new elements might result in the realloaction of the whole list to a better location in memory. If this is done several times because we are appending 1 element at a time, overall performance suffers. In this sense, list.extend is analogous to \"\".join(stringlist).</p>\n"
},
{
"answer_id": 26397913,
"author": "Shiv",
"author_id": 4144205,
"author_profile": "https://Stackoverflow.com/users/4144205",
"pm_score": 4,
"selected": false,
"text": "<p>Append adds the entire data at once. The whole data will be added to the newly created index. On the other hand, <code>extend</code>, as it name suggests, extends the current array. </p>\n\n<p>For example</p>\n\n<pre><code>list1 = [123, 456, 678]\nlist2 = [111, 222]\n</code></pre>\n\n<p>With <code>append</code> we get:</p>\n\n<pre><code>result = [123, 456, 678, [111, 222]]\n</code></pre>\n\n<p>While on <code>extend</code> we get:</p>\n\n<pre><code>result = [123, 456, 678, 111, 222]\n</code></pre>\n"
},
{
"answer_id": 28119966,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 9,
"selected": false,
"text": "<blockquote>\n<h2>What is the difference between the list methods append and extend?</h2>\n</blockquote>\n<ul>\n<li><code>append</code> adds its argument as a single element to the end of a list. The length of the list itself will increase by one.</li>\n<li><code>extend</code> iterates over its argument adding each element to the list, extending the list. The length of the list will increase by however many elements were in the iterable argument.</li>\n</ul>\n<h2><code>append</code></h2>\n<p>The <code>list.append</code> method appends an object to the end of the list.</p>\n<pre><code>my_list.append(object) \n</code></pre>\n<p>Whatever the object is, whether a number, a string, another list, or something else, it gets added onto the end of <code>my_list</code> as a single entry on the list.</p>\n<pre><code>>>> my_list\n['foo', 'bar']\n>>> my_list.append('baz')\n>>> my_list\n['foo', 'bar', 'baz']\n</code></pre>\n<p>So keep in mind that a list is an object. If you append another list onto a list, the first list will be a single object at the end of the list (which may not be what you want):</p>\n<pre><code>>>> another_list = [1, 2, 3]\n>>> my_list.append(another_list)\n>>> my_list\n['foo', 'bar', 'baz', [1, 2, 3]]\n #^^^^^^^^^--- single item at the end of the list.\n</code></pre>\n<h2><code>extend</code></h2>\n<p>The <code>list.extend</code> method extends a list by appending elements from an iterable:</p>\n<pre><code>my_list.extend(iterable)\n</code></pre>\n<p>So with extend, each element of the iterable gets appended onto the list. For example:</p>\n<pre><code>>>> my_list\n['foo', 'bar']\n>>> another_list = [1, 2, 3]\n>>> my_list.extend(another_list)\n>>> my_list\n['foo', 'bar', 1, 2, 3]\n</code></pre>\n<p>Keep in mind that a string is an iterable, so if you extend a list with a string, you'll append each character as you iterate over the string (which may not be what you want):</p>\n<pre><code>>>> my_list.extend('baz')\n>>> my_list\n['foo', 'bar', 1, 2, 3, 'b', 'a', 'z']\n</code></pre>\n<h2>Operator Overload, <code>__add__</code> (<code>+</code>) and <code>__iadd__</code> (<code>+=</code>)</h2>\n<p>Both <code>+</code> and <code>+=</code> operators are defined for <code>list</code>. They are semantically similar to extend.</p>\n<p><code>my_list + another_list</code> creates a third list in memory, so you can return the result of it, but it requires that the second iterable be a list.</p>\n<p><code>my_list += another_list</code> modifies the list in-place (it <em>is</em> the in-place operator, and lists are mutable objects, as we've seen) so it does not create a new list. It also works like extend, in that the second iterable can be any kind of iterable.</p>\n<p>Don't get confused - <code>my_list = my_list + another_list</code> is not equivalent to <code>+=</code> - it gives you a brand new list assigned to my_list.</p>\n<h2>Time Complexity</h2>\n<p>Append has (<a href=\"https://stackoverflow.com/a/33045038/541136\">amortized</a>) <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"noreferrer\">constant time complexity</a>, O(1).</p>\n<p>Extend has time complexity, O(k).</p>\n<p>Iterating through the multiple calls to <code>append</code> adds to the complexity, making it equivalent to that of extend, and since extend's iteration is implemented in C, it will always be faster if you intend to append successive items from an iterable onto a list.</p>\n<p>Regarding "amortized" - from the <a href=\"https://github.com/python/cpython/blob/3.9/Objects/listobject.c#L52\" rel=\"noreferrer\">list object implementation source</a>:</p>\n<pre class=\"lang-none prettyprint-override\"><code> /* This over-allocates proportional to the list size, making room\n * for additional growth. The over-allocation is mild, but is\n * enough to give linear-time amortized behavior over a long\n * sequence of appends() in the presence of a poorly-performing\n * system realloc().\n</code></pre>\n<p>This means that we get the benefits of a larger than needed memory reallocation up front, but we may pay for it on the next marginal reallocation with an even larger one. Total time for all appends is linear at O(n), and that time allocated per append, becomes O(1).</p>\n<h2>Performance</h2>\n<p>You may wonder what is more performant, since append can be used to achieve the same outcome as extend. The following functions do the same thing:</p>\n<pre><code>def append(alist, iterable):\n for item in iterable:\n alist.append(item)\n \ndef extend(alist, iterable):\n alist.extend(iterable)\n</code></pre>\n<p>So let's time them:</p>\n<pre><code>import timeit\n\n>>> min(timeit.repeat(lambda: append([], "abcdefghijklmnopqrstuvwxyz")))\n2.867846965789795\n>>> min(timeit.repeat(lambda: extend([], "abcdefghijklmnopqrstuvwxyz")))\n0.8060121536254883\n</code></pre>\n<h3>Addressing a comment on timings</h3>\n<p>A commenter said:</p>\n<blockquote>\n<p>Perfect answer, I just miss the timing of comparing adding only one element</p>\n</blockquote>\n<p>Do the semantically correct thing. If you want to append all elements in an iterable, use <code>extend</code>. If you're just adding one element, use <code>append</code>.</p>\n<p>Ok, so let's create an experiment to see how this works out in time:</p>\n<pre><code>def append_one(a_list, element):\n a_list.append(element)\n\ndef extend_one(a_list, element):\n """creating a new list is semantically the most direct\n way to create an iterable to give to extend"""\n a_list.extend([element])\n\nimport timeit\n</code></pre>\n<p>And we see that going out of our way to create an iterable just to use extend is a (minor) waste of time:</p>\n<pre><code>>>> min(timeit.repeat(lambda: append_one([], 0)))\n0.2082819009956438\n>>> min(timeit.repeat(lambda: extend_one([], 0)))\n0.2397019260097295\n</code></pre>\n<p>We learn from this that there's nothing gained from using <code>extend</code> when we have only <em>one</em> element to append.</p>\n<p>Also, these timings are not that important. I am just showing them to make the point that, in Python, doing the semantically correct thing is doing things the <em>Right</em> Way™.</p>\n<p>It's conceivable that you might test timings on two comparable operations and get an ambiguous or inverse result. Just focus on doing the semantically correct thing.</p>\n<h2>Conclusion</h2>\n<p>We see that <code>extend</code> is semantically clearer, and that it can run much faster than <code>append</code>, <em>when you intend to append each element in an iterable to a list.</em></p>\n<p>If you only have a single element (not in an iterable) to add to the list, use <code>append</code>.</p>\n"
},
{
"answer_id": 37787163,
"author": "The Gr8 Adakron",
"author_id": 5866942,
"author_profile": "https://Stackoverflow.com/users/5866942",
"pm_score": 4,
"selected": false,
"text": "<p><strong><em>append()</em></strong>: It is basically used in Python to add one element.</p>\n\n<blockquote>\n <p>Example 1:</p>\n</blockquote>\n\n<pre><code>>> a = [1, 2, 3, 4]\n>> a.append(5)\n>> print(a)\n>> a = [1, 2, 3, 4, 5]\n</code></pre>\n\n<blockquote>\n <p>Example 2:</p>\n</blockquote>\n\n<pre><code>>> a = [1, 2, 3, 4]\n>> a.append([5, 6])\n>> print(a)\n>> a = [1, 2, 3, 4, [5, 6]]\n</code></pre>\n\n<p><strong><em>extend()</em></strong>: Where extend(), is used to merge two lists or insert multiple elements in one list.</p>\n\n<blockquote>\n <p>Example 1:</p>\n</blockquote>\n\n<pre><code>>> a = [1, 2, 3, 4]\n>> b = [5, 6, 7, 8]\n>> a.extend(b)\n>> print(a)\n>> a = [1, 2, 3, 4, 5, 6, 7, 8]\n</code></pre>\n\n<blockquote>\n <p>Example 2:</p>\n</blockquote>\n\n<pre><code>>> a = [1, 2, 3, 4]\n>> a.extend([5, 6])\n>> print(a)\n>> a = [1, 2, 3, 4, 5, 6]\n</code></pre>\n"
},
{
"answer_id": 39256397,
"author": "tessie",
"author_id": 2813483,
"author_profile": "https://Stackoverflow.com/users/2813483",
"pm_score": 2,
"selected": false,
"text": "<p><code>extend(L)</code> extends the list by appending all the items in the given list <code>L</code>.</p>\n\n<pre><code>>>> a\n[1, 2, 3]\na.extend([4]) #is eqivalent of a[len(a):] = [4]\n>>> a\n[1, 2, 3, 4]\na = [1, 2, 3]\n>>> a\n[1, 2, 3]\n>>> a[len(a):] = [4]\n>>> a\n[1, 2, 3, 4]\n</code></pre>\n"
},
{
"answer_id": 42171373,
"author": "Crabime",
"author_id": 5531783,
"author_profile": "https://Stackoverflow.com/users/5531783",
"pm_score": 3,
"selected": false,
"text": "<p>I hope I can make a useful supplement to this question. If your list stores a specific type object, for example <code>Info</code>, here is a situation that <code>extend</code> method is not suitable: In a <code>for</code> loop and and generating an <code>Info</code> object every time and using <code>extend</code> to store it into your list, it will fail. The exception is like below:</p>\n\n<blockquote>\n <p>TypeError: 'Info' object is not iterable</p>\n</blockquote>\n\n<p>But if you use the <code>append</code> method, the result is OK. Because every time using the <code>extend</code> method, it will always treat it as a list or any other collection type, iterate it, and place it after the previous list. A specific object can not be iterated, obviously.</p>\n"
},
{
"answer_id": 46804939,
"author": "PythonProgrammi",
"author_id": 6464947,
"author_profile": "https://Stackoverflow.com/users/6464947",
"pm_score": 6,
"selected": false,
"text": "<h1> Append vs Extend</h1>\n\n<h2><a href=\"https://i.stack.imgur.com/KH5jB.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/KH5jB.png\" alt=\"enter image description here\"></a></h2>\n\n<p>With append you can append a single element that will extend the list:</p>\n\n<pre><code>>>> a = [1,2]\n>>> a.append(3)\n>>> a\n[1,2,3]\n</code></pre>\n\n<p>If you want to extend more than one element you should use extend, because you can only append one elment or one list of element:</p>\n\n<pre><code>>>> a.append([4,5])\n>>> a\n>>> [1,2,3,[4,5]]\n</code></pre>\n\n<p>So that you get a nested list</p>\n\n<p>Instead with extend, you can extend a single element like this</p>\n\n<pre><code>>>> a = [1,2]\n>>> a.extend([3])\n>>> a\n[1,2,3]\n</code></pre>\n\n<p>Or, differently, from append, extend more elements in one time without nesting the list into the original one (that's the reason of the name extend)</p>\n\n<pre><code>>>> a.extend([4,5,6])\n>>> a\n[1,2,3,4,5,6]\n</code></pre>\n\n<h1> Adding one element with both methods</h1>\n\n<h2><a href=\"https://i.stack.imgur.com/lGF2k.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lGF2k.png\" alt=\"enter image description here\"></a></h2>\n\n<p>Both append and extend can add one element to the end of the list, though append is simpler.</p>\n\n<h2> append 1 element </h2>\n\n<pre><code>>>> x = [1,2]\n>>> x.append(3)\n>>> x\n[1,2,3]\n</code></pre>\n\n<h2> extend one element </h2>\n\n<pre><code>>>> x = [1,2]\n>>> x.extend([3])\n>>> x\n[1,2,3]\n</code></pre>\n\n<h1> Adding more elements... with different results </h1>\n\n<p>If you use append for more than one element, you have to pass a list of elements as arguments and you will obtain a NESTED list!</p>\n\n<pre><code>>>> x = [1,2]\n>>> x.append([3,4])\n>>> x\n[1,2,[3,4]]\n</code></pre>\n\n<p>With extend, instead, you pass a list as an argument, but you will obtain a list with the new element that is not nested in the old one.</p>\n\n<pre><code>>>> z = [1,2] \n>>> z.extend([3,4])\n>>> z\n[1,2,3,4]\n</code></pre>\n\n<p>So, with more elements, you will use extend to get a list with more items.\nHowever, appending a list will not add more elements to the list, but one element that is a nested list as you can clearly see in the output of the code.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lJK1M.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lJK1M.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/KC2Ji.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/KC2Ji.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 47631056,
"author": "AbstProcDo",
"author_id": 7301792,
"author_profile": "https://Stackoverflow.com/users/7301792",
"pm_score": 3,
"selected": false,
"text": "<p>To distinguish them intuitively</p>\n\n<pre><code>l1 = ['a', 'b', 'c']\nl2 = ['d', 'e', 'f']\nl1.append(l2)\nl1\n['a', 'b', 'c', ['d', 'e', 'f']]\n</code></pre>\n\n<p>It's like <code>l1</code> reproduce a body inside her body(nested).</p>\n\n<pre><code># Reset l1 = ['a', 'b', 'c']\nl1.extend(l2)\nl1\n['a', 'b', 'c', 'd', 'e', 'f']\n</code></pre>\n\n<p>It's like that two separated individuals get married and construct an united family.</p>\n\n<p>Besides I make an exhaustive cheatsheet of all list's methods for your reference.</p>\n\n<pre><code>list_methods = {'Add': {'extend', 'append', 'insert'},\n 'Remove': {'pop', 'remove', 'clear'}\n 'Sort': {'reverse', 'sort'},\n 'Search': {'count', 'index'},\n 'Copy': {'copy'},\n }\n</code></pre>\n"
},
{
"answer_id": 48036819,
"author": "kmario23",
"author_id": 2956066,
"author_profile": "https://Stackoverflow.com/users/2956066",
"pm_score": 4,
"selected": false,
"text": "<p>An English dictionary defines the words <code>append</code> and <code>extend</code> as:</p>\n\n<p><strong>append</strong>: add (something) to the end of a written document. <br/>\n<strong>extend</strong>: make larger. Enlarge or expand</p>\n\n<hr>\n\n<p>With that knowledge, now let's understand</p>\n\n<p>1) <strong>The difference between <code>append</code> and <code>extend</code></strong></p>\n\n<p><strong><code>append</code></strong>:</p>\n\n<ul>\n<li>Appends <em>any Python object as-is</em> to the end of the list (i.e. as a\nthe last element in the list).</li>\n<li>The resulting list may be nested and contain heterogeneous elements (i.e. list, string, tuple, dictionary, set, etc.)</li>\n</ul>\n\n<p><strong><code>extend</code></strong>:</p>\n\n<ul>\n<li>Accepts any <em>iterable</em> as its argument and makes the list <em>larger</em>.</li>\n<li>The resulting list is always one-dimensional list (i.e. no nesting) and it may contain heterogeneous elements in it (e.g. characters, integers, float) as a result of applying <code>list(iterable)</code>.</li>\n</ul>\n\n<p>2) <strong>Similarity between <code>append</code> and <code>extend</code></strong></p>\n\n<ul>\n<li>Both take exactly one argument.</li>\n<li>Both modify the list <em>in-place</em>.</li>\n<li>As a result, both returns <code>None</code>.</li>\n</ul>\n\n<hr>\n\n<p><strong>Example</strong></p>\n\n<pre><code>lis = [1, 2, 3]\n\n# 'extend' is equivalent to this\nlis = lis + list(iterable)\n\n# 'append' simply appends its argument as the last element to the list\n# as long as the argument is a valid Python object\nlist.append(object)\n</code></pre>\n"
},
{
"answer_id": 49591233,
"author": "ilias iliadis",
"author_id": 2362556,
"author_profile": "https://Stackoverflow.com/users/2362556",
"pm_score": 0,
"selected": false,
"text": "<p><code>append</code> \"extends\" the list (in place) by <strong>only one item</strong>, the single object passed (as argument).</p>\n\n<p><code>extend</code> \"extends\" the list (in place) by <strong>as many items as</strong> the object passed (as argument) contains.</p>\n\n<p>This may be slightly confusing for <code>str</code> objects.</p>\n\n<ol>\n<li>If you pass a string as argument:\n<code>append</code> will add a single string item at the end but\n<code>extend</code> will add as many \"single\" 'str' items as the length of that string.</li>\n<li>If you pass a list of strings as argument:\n<code>append</code> will still add a single 'list' item at the end and\n<code>extend</code> will add as many 'list' items as the length of the passed list.</li>\n</ol>\n\n<blockquote>\n<pre><code>def append_o(a_list, element):\n a_list.append(element)\n print('append:', end = ' ')\n for item in a_list:\n print(item, end = ',')\n print()\n\ndef extend_o(a_list, element):\n a_list.extend(element)\n print('extend:', end = ' ')\n for item in a_list:\n print(item, end = ',')\n print()\nappend_o(['ab'],'cd')\n\nextend_o(['ab'],'cd')\nappend_o(['ab'],['cd', 'ef'])\nextend_o(['ab'],['cd', 'ef'])\nappend_o(['ab'],['cd'])\nextend_o(['ab'],['cd'])\n</code></pre>\n</blockquote>\n\n<p>produces:</p>\n\n<pre><code>append: ab,cd,\nextend: ab,c,d,\nappend: ab,['cd', 'ef'],\nextend: ab,cd,ef,\nappend: ab,['cd'],\nextend: ab,cd,\n</code></pre>\n"
},
{
"answer_id": 51375427,
"author": "vivek",
"author_id": 3257783,
"author_profile": "https://Stackoverflow.com/users/3257783",
"pm_score": 0,
"selected": false,
"text": "<p>Append and extend are one of the extensibility mechanisms in python. </p>\n\n<p>Append: Adds an element to the end of the list. </p>\n\n<pre><code>my_list = [1,2,3,4]\n</code></pre>\n\n<p>To add a new element to the list, we can use append method in the following way.</p>\n\n<pre><code>my_list.append(5)\n</code></pre>\n\n<p>The default location that the new element will be added is always in the (length+1) position. </p>\n\n<p>Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at. </p>\n\n<p>Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself. </p>\n\n<pre><code>Example: my_list = [1,2,3,4]\nmy_list[4, 'a']\nmy_list\n[1,2,3,4,'a']\n</code></pre>\n\n<p>Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists. </p>\n\n<pre><code>a = [1,2]\nb = [3]\na.append(b)\nprint (a)\n[1,2,[3]]\n</code></pre>\n\n<p>If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we'll have to use append. </p>\n\n<pre><code>a = [1,2]\nb = [3]\na.extend(b)\nprint (a)\n[1,2,3]\n</code></pre>\n\n<p>To join multiple lists</p>\n\n<pre><code>a = [1]\nb = [2]\nc = [3]\na.extend(b+c)\nprint (a)\n[1,2,3]\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
What's the difference between the list methods `append()` and `extend()`?
|
[`append`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) appends a specified object at the end of the list:
```
>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]
```
[`extend`](https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types) extends the list by appending elements from the specified iterable:
```
>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]
```
|
252,729 |
<p>i'm trying to make the following routes .. and currently i'm going about this in a <em>really</em> long way.. ie. one route instance for EACH route.</p>
<p>this is what i'm after... (assuming i'm doing a 'stackoverflow website')</p>
<pre><code>/ <-- root site
/page/{page} <-- root site, but to the page of questions.
/tag/{tag}/page/{page} <-- as above, but the questions are filtered by tag
/question/ask <-- this page :P
/question/{subject} <-- reading about a question
</code></pre>
<p>(and no.. i'm most definitely not doing a stackoverflow website :) )</p>
<p>cheers!</p>
<p>(gawd i find dis all so confusing at times).</p>
|
[
{
"answer_id": 252849,
"author": "Norbert B.",
"author_id": 2605840,
"author_profile": "https://Stackoverflow.com/users/2605840",
"pm_score": 0,
"selected": false,
"text": "<p>I would change the last url to /question/view/{subject}.\nFuther Create 3 controllers:</p>\n\n<ul>\n<li>PageController</li>\n<li>TagController</li>\n<li>QuestionController</li>\n</ul>\n\n<p>in Global.asax create those routes,(take example at the default route)</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 260131,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 3,
"selected": true,
"text": "<p>For your third one, I'd do something like this:</p>\n\n<pre><code>routes.MapRoute(\"page-tag\", \"tag/{tag}/page/{page}\", new {controller=\"question\", action=\"FilterByTag\"});\n</code></pre>\n\n<p>Your action method then could look like this:</p>\n\n<pre><code>public class QuestionController : Controller {\n public ActionResult FilterByTag(string tag, int page) {\n //...\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
i'm trying to make the following routes .. and currently i'm going about this in a *really* long way.. ie. one route instance for EACH route.
this is what i'm after... (assuming i'm doing a 'stackoverflow website')
```
/ <-- root site
/page/{page} <-- root site, but to the page of questions.
/tag/{tag}/page/{page} <-- as above, but the questions are filtered by tag
/question/ask <-- this page :P
/question/{subject} <-- reading about a question
```
(and no.. i'm most definitely not doing a stackoverflow website :) )
cheers!
(gawd i find dis all so confusing at times).
|
For your third one, I'd do something like this:
```
routes.MapRoute("page-tag", "tag/{tag}/page/{page}", new {controller="question", action="FilterByTag"});
```
Your action method then could look like this:
```
public class QuestionController : Controller {
public ActionResult FilterByTag(string tag, int page) {
//...
}
}
```
|
252,735 |
<p>I have made a bunch of changes to a number of files in a project. Every commit (usually at the file level) was accompanied by a comment of what was changed. </p>
<p>Is there a way to get a list from CVS of these comments on changes since the last tagged version?</p>
<p>Bonus if I can do this via the eclipse CVS plugin.</p>
<p><strong>UPDATE</strong>: I'd love to accept an answer here, but unfortunately none of the answers are what I am looking for. Frankly I don' think it is actually possible, which is a pity really as this could be a great way to create a change list between versions (Assuming all commits are made at a sensible granularity and contain meaningful comments).</p>
|
[
{
"answer_id": 252801,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 3,
"selected": false,
"text": "<p>The options for the cvs log command are available <a href=\"http://www.cvsnt.org/manual/html/log.html\" rel=\"noreferrer\">here</a>. Specifically, to get all the commits since a specific tag (lets call it VERSION_1_0)</p>\n\n<pre><code>cvs log -rVERSION_1_0:\n</code></pre>\n\n<p>If your goal is to have a command that works without having to know the name of the last tag I believe you will need to write a script that grabs the log for the current branch, parses through to find the tag, then issues the log command against that tag, but I migrated everything off of CVS quite a while ago, so my memory might be a bit rusty.</p>\n"
},
{
"answer_id": 254100,
"author": "Alex B",
"author_id": 6180,
"author_profile": "https://Stackoverflow.com/users/6180",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to get a quick result on a single file, the <code>cvs log</code> command is good. If you want something more comprehensive, the best tool I've found for this is a perl script called <a href=\"http://www.red-bean.com/cvs2cl/\" rel=\"noreferrer\">cvs2cl.pl</a>. This can generate a change list in several different formats. It has many different options, but I've used the tag-to-tag options like this:</p>\n\n<pre><code>cvs2cl.pl --delta dev_release_1_2_3:dev_release_1_6_8\n</code></pre>\n\n<p>or</p>\n\n<pre><code>cvs2cl.pl --delta dev_release_1_2_3:HEAD\n</code></pre>\n\n<p>I have also done comparisons using dates with the same tool.</p>\n"
},
{
"answer_id": 4609959,
"author": "Vernon",
"author_id": 294773,
"author_profile": "https://Stackoverflow.com/users/294773",
"pm_score": 2,
"selected": false,
"text": "<p>I know you have already \"solved\" your problem, but I had the same problem and here is how I quickly got all of the comments out of cvs from a given revision until the latest:</p>\n\n<pre>$ mkdir ~/repo\n$ cd ~/repo\n$ mkdir cvs\n$ cd cvs\n$ scp -pr [email protected]:/cvs/CVSROOT .\n$ mkdir -p my/favorite\n$ cd my/favorite\n$ scp -pr [email protected]:/cvs/my/favorite/project .\n$ cd ~/repo\n$ mkdir -p ~/repo/svn/my/favorite/project\n$ cvs2svn -s ~/repo/svn/my/favorite/project/src ~/repo/cvs/my/favorite/project/src\n$ mkdir ~/work\n$ cd ~/work\n$ svn checkout file:///home/geek/repo/svn/my/favorite/project/src/trunk ./src\n$ cd src\n$ # get the comments made from revision 5 until today\n$ svn log -r 5:HEAD\n$ # get the comments made from 2010-07-03 until today\n$ svn log -r {2010-07-03}:HEAD</pre>\n\n<p>The basic idea is to just use svn or git instead of cvs :-)\nAnd that can be done by converting the cvs repo to svn or git using cvs2svn or cvs2git, which we should be doing anyway. It got my my answer within about three minutes because I had a small repository.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 5271307,
"author": "Nate",
"author_id": 119114,
"author_profile": "https://Stackoverflow.com/users/119114",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this</p>\n\n<pre><code>cvs -q log -NS -rVERSION_3_0::HEAD\n</code></pre>\n\n<p>Where you probably want to pipe the output into egrep to filter out the stuff you don't want to see. I've used this:</p>\n\n<pre><code>cvs -q log -NS -rVERSION_3_0::HEAD | egrep -v \"RCS file: |revision |date:|Working file:|head:|branch:|locks:|access list:|keyword substitution:|total revisions: |============|-------------\"\n</code></pre>\n"
},
{
"answer_id": 9982491,
"author": "ag_choc",
"author_id": 1308855,
"author_profile": "https://Stackoverflow.com/users/1308855",
"pm_score": 3,
"selected": false,
"text": "<p>I think </p>\n\n<pre><code>cvs -q log -SN -rtag1:::tag2 \n</code></pre>\n\n<p>or</p>\n\n<pre><code> cvs -q log -SN -dfromdate<todate \n</code></pre>\n\n<p>will do what you want. This lists all the versions and comments for all changes made between the two tags or dates, only for files that have changed. In the tag case, the three colons exclude the comments for the first tag. See <code>cvs -H</code> log for more information.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/939/"
] |
I have made a bunch of changes to a number of files in a project. Every commit (usually at the file level) was accompanied by a comment of what was changed.
Is there a way to get a list from CVS of these comments on changes since the last tagged version?
Bonus if I can do this via the eclipse CVS plugin.
**UPDATE**: I'd love to accept an answer here, but unfortunately none of the answers are what I am looking for. Frankly I don' think it is actually possible, which is a pity really as this could be a great way to create a change list between versions (Assuming all commits are made at a sensible granularity and contain meaningful comments).
|
The options for the cvs log command are available [here](http://www.cvsnt.org/manual/html/log.html). Specifically, to get all the commits since a specific tag (lets call it VERSION\_1\_0)
```
cvs log -rVERSION_1_0:
```
If your goal is to have a command that works without having to know the name of the last tag I believe you will need to write a script that grabs the log for the current branch, parses through to find the tag, then issues the log command against that tag, but I migrated everything off of CVS quite a while ago, so my memory might be a bit rusty.
|
252,748 |
<p>How should I use array of function pointers in C?</p>
<p>How can I initialize them?</p>
|
[
{
"answer_id": 252750,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": false,
"text": "<p>You have a good example <a href=\"http://www.java2s.com/Code/C/Function/Arrayoffunctionpointer.htm\" rel=\"noreferrer\">here (Array of Function pointers)</a>, with the <a href=\"http://www.newty.de/fpt/fpt.html#chapter2\" rel=\"noreferrer\">syntax detailed</a>.</p>\n\n<pre><code>int sum(int a, int b);\nint subtract(int a, int b);\nint mul(int a, int b);\nint div(int a, int b);\n\nint (*p[4]) (int x, int y);\n\nint main(void)\n{\n int result;\n int i, j, op;\n\n p[0] = sum; /* address of sum() */\n p[1] = subtract; /* address of subtract() */\n p[2] = mul; /* address of mul() */\n p[3] = div; /* address of div() */\n[...]\n</code></pre>\n\n<p>To call one of those function pointers:</p>\n\n<pre><code>result = (*p[op]) (i, j); // op being the index of one of the four functions\n</code></pre>\n"
},
{
"answer_id": 252752,
"author": "Manoj Doubts",
"author_id": 31116,
"author_profile": "https://Stackoverflow.com/users/31116",
"pm_score": 6,
"selected": false,
"text": "<p>The above answers may help you but you may also want to know how to use array of function pointers.</p>\n\n<pre><code>void fun1()\n{\n\n}\n\nvoid fun2()\n{\n\n}\n\nvoid fun3()\n{\n\n}\n\nvoid (*func_ptr[3])() = {fun1, fun2, fun3};\n\nmain()\n{\n int option;\n\n\n printf(\"\\nEnter function number you want\");\n printf(\"\\nYou should not enter other than 0 , 1, 2\"); /* because we have only 3 functions */\n scanf(\"%d\",&option);\n\n if((option>=0)&&(option<=2))\n { \n (*func_ptr[option])();\n }\n\n return 0;\n}\n</code></pre>\n\n<p>You can only assign the addresses of functions with the same return type and same argument types and no of arguments to a single function pointer array.</p>\n\n<p>You can also pass arguments like below if all the above functions are having the same number of arguments of same type.</p>\n\n<pre><code> (*func_ptr[option])(argu1);\n</code></pre>\n\n<p>Note: here in the array the numbering of the function pointers will be starting from 0 same as in general arrays. So in above example <code>fun1</code> can be called if option=0, <code>fun2</code> can be called if option=1 and <code>fun3</code> can be called if option=2.</p>\n"
},
{
"answer_id": 252755,
"author": "Friedrich",
"author_id": 15068,
"author_profile": "https://Stackoverflow.com/users/15068",
"pm_score": 2,
"selected": false,
"text": "<p>Oh, there are tons of example. Just have a look at anything within glib or gtk.\nYou can see the work of function pointers in work there all the way. </p>\n\n<p>Here e.g the initialization of the gtk_button stuff.</p>\n\n<pre><code>\nstatic void\ngtk_button_class_init (GtkButtonClass *klass)\n{\n GObjectClass *gobject_class;\n GtkObjectClass *object_class;\n GtkWidgetClass *widget_class;\n GtkContainerClass *container_class;\n\n gobject_class = G_OBJECT_CLASS (klass);\n object_class = (GtkObjectClass*) klass;\n widget_class = (GtkWidgetClass*) klass;\n container_class = (GtkContainerClass*) klass;\n\n gobject_class->constructor = gtk_button_constructor;\n gobject_class->set_property = gtk_button_set_property;\n gobject_class->get_property = gtk_button_get_property;\n\n</code></pre>\n\n<p>And in gtkobject.h you find the following declarations:</p>\n\n<pre><code>\nstruct _GtkObjectClass\n{\n GInitiallyUnownedClass parent_class;\n\n /* Non overridable class methods to set and get per class arguments */\n void (*set_arg) (GtkObject *object,\n GtkArg *arg,\n guint arg_id);\n void (*get_arg) (GtkObject *object,\n GtkArg *arg,\n guint arg_id);\n\n /* Default signal handler for the ::destroy signal, which is\n * invoked to request that references to the widget be dropped.\n * If an object class overrides destroy() in order to perform class\n * specific destruction then it must still invoke its superclass'\n * implementation of the method after it is finished with its\n * own cleanup. (See gtk_widget_real_destroy() for an example of\n * how to do this).\n */\n void (*destroy) (GtkObject *object);\n};\n</code></pre>\n\n<p>The (*set_arg) stuff is a pointer to function and this can e.g be assigned another implementation in some derived class.</p>\n\n<p>Often you see something like this</p>\n\n<pre><code>struct function_table {\n char *name;\n void (*some_fun)(int arg1, double arg2);\n};\n\nvoid function1(int arg1, double arg2)....\n\n\nstruct function_table my_table [] = {\n {\"function1\", function1},\n...\n</code></pre>\n\n<p>So you can reach into the table by name and call the \"associated\" function. </p>\n\n<p>Or maybe you use a hash table in which you put the function and call it \"by name\".</p>\n\n<p>Regards\n<br>\nFriedrich</p>\n"
},
{
"answer_id": 10700827,
"author": "Rasmi Ranjan Nayak",
"author_id": 1105805,
"author_profile": "https://Stackoverflow.com/users/1105805",
"pm_score": 4,
"selected": false,
"text": "<p>Here's how you can use it:</p>\n\n<h3>New_Fun.h</h3>\n\n<pre><code>#ifndef NEW_FUN_H_\n#define NEW_FUN_H_\n\n#include <stdio.h>\n\ntypedef int speed;\nspeed fun(int x);\n\nenum fp {\n f1, f2, f3, f4, f5\n};\n\nvoid F1();\nvoid F2();\nvoid F3();\nvoid F4();\nvoid F5();\n#endif\n</code></pre>\n\n<h3>New_Fun.c</h3>\n\n<pre><code>#include \"New_Fun.h\"\n\nspeed fun(int x)\n{\n int Vel;\n Vel = x;\n return Vel;\n}\n\nvoid F1()\n{\n printf(\"From F1\\n\");\n}\n\nvoid F2()\n{\n printf(\"From F2\\n\");\n}\n\nvoid F3()\n{\n printf(\"From F3\\n\");\n}\n\nvoid F4()\n{\n printf(\"From F4\\n\");\n}\n\nvoid F5()\n{\n printf(\"From F5\\n\");\n}\n</code></pre>\n\n<h3>Main.c</h3>\n\n<pre><code>#include <stdio.h>\n#include \"New_Fun.h\"\n\nint main()\n{\n int (*F_P)(int y);\n void (*F_A[5])() = { F1, F2, F3, F4, F5 }; // if it is int the pointer incompatible is bound to happen\n int xyz, i;\n\n printf(\"Hello Function Pointer!\\n\");\n F_P = fun;\n xyz = F_P(5);\n printf(\"The Value is %d\\n\", xyz);\n //(*F_A[5]) = { F1, F2, F3, F4, F5 };\n for (i = 0; i < 5; i++)\n {\n F_A[i]();\n }\n printf(\"\\n\\n\");\n F_A[f1]();\n F_A[f2]();\n F_A[f3]();\n F_A[f4]();\n return 0;\n}\n</code></pre>\n\n<p>I hope this helps in understanding <code>Function Pointer.</code></p>\n"
},
{
"answer_id": 23903167,
"author": "M.M",
"author_id": 1505939,
"author_profile": "https://Stackoverflow.com/users/1505939",
"pm_score": 3,
"selected": false,
"text": "<p>This \"answer\" is more of an addendum to VonC's answer; just noting that the syntax can be simplified via a typedef, and aggregate initialization can be used:</p>\n\n<pre><code>typedef int FUNC(int, int);\n\nFUNC sum, subtract, mul, div;\nFUNC *p[4] = { sum, subtract, mul, div };\n\nint main(void)\n{\n int result;\n int i = 2, j = 3, op = 2; // 2: mul\n\n result = p[op](i, j); // = 6\n}\n\n// maybe even in another file\nint sum(int a, int b) { return a+b; }\nint subtract(int a, int b) { return a-b; }\nint mul(int a, int b) { return a*b; }\nint div(int a, int b) { return a/b; }\n</code></pre>\n"
},
{
"answer_id": 37553002,
"author": "Jay Medina",
"author_id": 5166605,
"author_profile": "https://Stackoverflow.com/users/5166605",
"pm_score": 0,
"selected": false,
"text": "<p>This question has been already answered with very good examples. The only example that might be missing is one where the functions return pointers. I wrote another example with this, and added lots of comments, in case someone finds it helpful:</p>\n\n<pre><code>#include <stdio.h>\n\nchar * func1(char *a) {\n *a = 'b';\n return a;\n}\n\nchar * func2(char *a) {\n *a = 'c';\n return a;\n}\n\nint main() {\n char a = 'a';\n /* declare array of function pointers\n * the function pointer types are char * name(char *)\n * A pointer to this type of function would be just\n * put * before name, and parenthesis around *name:\n * char * (*name)(char *)\n * An array of these pointers is the same with [x]\n */\n char * (*functions[2])(char *) = {func1, func2};\n printf(\"%c, \", a);\n /* the functions return a pointer, so I need to deference pointer\n * Thats why the * in front of the parenthesis (in case it confused you)\n */\n printf(\"%c, \", *(*functions[0])(&a)); \n printf(\"%c\\n\", *(*functions[1])(&a));\n\n a = 'a';\n /* creating 'name' for a function pointer type\n * funcp is equivalent to type char *(*funcname)(char *)\n */\n typedef char *(*funcp)(char *);\n /* Now the declaration of the array of function pointers\n * becomes easier\n */\n funcp functions2[2] = {func1, func2};\n\n printf(\"%c, \", a);\n printf(\"%c, \", *(*functions2[0])(&a));\n printf(\"%c\\n\", *(*functions2[1])(&a));\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 38639669,
"author": "nimig18",
"author_id": 3398381,
"author_profile": "https://Stackoverflow.com/users/3398381",
"pm_score": 1,
"selected": false,
"text": "<p>This should be a short & simple copy & paste piece of code example of the above responses. Hopefully this helps.</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\n#define DBG_PRINT(x) do { std::printf(\"Line:%-4d\" \" %15s = %-10d\\n\", __LINE__, #x, x); } while(0);\n\nvoid F0(){ printf(\"Print F%d\\n\", 0); }\nvoid F1(){ printf(\"Print F%d\\n\", 1); }\nvoid F2(){ printf(\"Print F%d\\n\", 2); }\nvoid F3(){ printf(\"Print F%d\\n\", 3); }\nvoid F4(){ printf(\"Print F%d\\n\", 4); }\nvoid (*fArrVoid[N_FUNC])() = {F0, F1, F2, F3, F4};\n\nint Sum(int a, int b){ return(a+b); }\nint Sub(int a, int b){ return(a-b); }\nint Mul(int a, int b){ return(a*b); }\nint Div(int a, int b){ return(a/b); }\nint (*fArrArgs[4])(int a, int b) = {Sum, Sub, Mul, Div};\n\nint main(){\n for(int i = 0; i < 5; i++) (*fArrVoid[i])();\n printf(\"\\n\");\n\n DBG_PRINT((*fArrArgs[0])(3,2))\n DBG_PRINT((*fArrArgs[1])(3,2))\n DBG_PRINT((*fArrArgs[2])(3,2))\n DBG_PRINT((*fArrArgs[3])(3,2))\n\n return(0);\n}\n</code></pre>\n"
},
{
"answer_id": 41374829,
"author": "arun kumar",
"author_id": 6164885,
"author_profile": "https://Stackoverflow.com/users/6164885",
"pm_score": 0,
"selected": false,
"text": "<p>This simple example for multidimensional array with function pointers\":</p>\n\n<pre><code>void one( int a, int b){ printf(\" \\n[ ONE ] a = %d b = %d\",a,b);}\nvoid two( int a, int b){ printf(\" \\n[ TWO ] a = %d b = %d\",a,b);}\nvoid three( int a, int b){ printf(\"\\n [ THREE ] a = %d b = %d\",a,b);}\nvoid four( int a, int b){ printf(\" \\n[ FOUR ] a = %d b = %d\",a,b);}\nvoid five( int a, int b){ printf(\" \\n [ FIVE ] a = %d b = %d\",a,b);}\nvoid(*p[2][2])(int,int) ;\nint main()\n{\n int i,j;\n printf(\"multidimensional array with function pointers\\n\");\n\n p[0][0] = one; p[0][1] = two; p[1][0] = three; p[1][1] = four;\n for ( i = 1 ; i >=0; i--)\n for ( j = 0 ; j <2; j++)\n (*p[i][j])( (i, i*j);\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 42070849,
"author": "Leonardo",
"author_id": 7523957,
"author_profile": "https://Stackoverflow.com/users/7523957",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest solution is to give the address of the final vector you want , and modify it inside the function. </p>\n\n<pre><code>void calculation(double result[] ){ //do the calculation on result\n\n result[0] = 10+5;\n result[1] = 10 +6;\n .....\n}\n\nint main(){\n\n double result[10] = {0}; //this is the vector of the results\n\n calculation(result); //this will modify result\n}\n</code></pre>\n"
},
{
"answer_id": 50664636,
"author": "Peter Hirt",
"author_id": 9863121,
"author_profile": "https://Stackoverflow.com/users/9863121",
"pm_score": 2,
"selected": false,
"text": "<p>Can use it in the way like this:</p>\n\n<pre><code>//! Define:\n#define F_NUM 3\nint (*pFunctions[F_NUM])(void * arg);\n\n//! Initialise:\nint someFunction(void * arg) {\n int a= *((int*)arg);\n return a*a;\n}\n\npFunctions[0]= someFunction;\n\n//! Use:\nint someMethod(int idx, void * arg, int * result) {\n int done= 0;\n if (idx < F_NUM && pFunctions[idx] != NULL) {\n *result= pFunctions[idx](arg);\n done= 1;\n }\n return done;\n}\n\nint x= 2;\nint z= 0;\nsomeMethod(0, (void*)&x, &z);\nassert(z == 4);\n</code></pre>\n"
},
{
"answer_id": 66448238,
"author": "Alex Hajnal",
"author_id": 13481837,
"author_profile": "https://Stackoverflow.com/users/13481837",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a simpler example of how to do it:</p>\n<p><strong>jump_table.c</strong></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int func1(int arg) { return arg + 1; }\nint func2(int arg) { return arg + 2; }\nint func3(int arg) { return arg + 3; }\nint func4(int arg) { return arg + 4; }\nint func5(int arg) { return arg + 5; }\nint func6(int arg) { return arg + 6; }\nint func7(int arg) { return arg + 7; }\nint func8(int arg) { return arg + 8; }\nint func9(int arg) { return arg + 9; }\nint func10(int arg) { return arg + 10; }\n\nint (*jump_table[10])(int) = { func1, func2, func3, func4, func5, \n func6, func7, func8, func9, func10 };\n \nint main(void) {\n int index = 2;\n int argument = 42;\n int result = (*jump_table[index])(argument);\n // result is 45\n}\n</code></pre>\n<p>All functions stored in the array must have the same signature. This simply means that they must return the same type (e.g. <code>int</code>) and have the same arguments (a single <code>int</code> in the example above).</p>\n<hr />\n<p>In C++, you can do the same with <em>static</em> class methods (but not instance methods). For example you could use <code>MyClass::myStaticMethod</code> in the array above but not <code>MyClass::myInstanceMethod</code> nor <code>instance.myInstanceMethod</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class MyClass {\npublic:\n static int myStaticMethod(int foo) { return foo + 17; }\n int myInstanceMethod(int bar) { return bar + 17; }\n}\n\nMyClass instance;\n</code></pre>\n"
},
{
"answer_id": 68300143,
"author": "sra js",
"author_id": 15193066,
"author_profile": "https://Stackoverflow.com/users/15193066",
"pm_score": -1,
"selected": false,
"text": "<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\nusing namespace std;\n \nint sum (int , int);\nint prod (int , int);\n \nint main()\n{\n int (*p[2])(int , int ) = {sum,prod};\n \n cout << (*p[0])(2,3) << endl;\n cout << (*p[1])(2,3) << endl;\n}\n \nint sum (int a , int b)\n{\n return a+b;\n}\n \nint prod (int a, int b)\n{\n return a*b;\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How should I use array of function pointers in C?
How can I initialize them?
|
You have a good example [here (Array of Function pointers)](http://www.java2s.com/Code/C/Function/Arrayoffunctionpointer.htm), with the [syntax detailed](http://www.newty.de/fpt/fpt.html#chapter2).
```
int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);
int (*p[4]) (int x, int y);
int main(void)
{
int result;
int i, j, op;
p[0] = sum; /* address of sum() */
p[1] = subtract; /* address of subtract() */
p[2] = mul; /* address of mul() */
p[3] = div; /* address of div() */
[...]
```
To call one of those function pointers:
```
result = (*p[op]) (i, j); // op being the index of one of the four functions
```
|
252,766 |
<p>How can I add line numbers to a range of lines in a file opened in Vim? Not as in <code>:set nu</code>—this just <em>displays</em> line numbers—but actually have them be prepended to each line in the file?</p>
|
[
{
"answer_id": 252770,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 5,
"selected": false,
"text": "<p><code>cat -n</code> adds line numbers to its input. You can pipe the current file to <code>cat -n</code> and replace the current buffer with what it prints to stdout. Fortunately this convoluted solution is less than 10 characters in vim:</p>\n\n<pre><code> :%!cat -n\n</code></pre>\n\n<p>Or, if you want just a subselection, visually select the area, and type this:</p>\n\n<pre><code> :!cat -n\n</code></pre>\n\n<p>That will automatically put the visual selection markers in, and will look like this after you've typed it:</p>\n\n<pre><code> :'<,'>!cat -n\n</code></pre>\n\n<p>In order to erase the line numbers, I recommend using <code>control-v</code>, which will allow you to visually select a rectangle, you can then delete that rectangle with <code>x</code>.</p>\n"
},
{
"answer_id": 252774,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>With Unix-like environment, you can use cat or awk to generate a line number easily, because vim has a friendly interface with shell, so everything work in vim as well as it does in shell.<br>\nFrom <a href=\"http://neuron.tuke.sk/~hudecm/VimTips-OFFLINE-nov02.txt\" rel=\"nofollow noreferrer\">Vim Tip28</a>:</p>\n\n<pre><code>:%!cat -n\n</code></pre>\n\n<p>or</p>\n\n<pre><code>:%!awk '{print NR,$0}'\n</code></pre>\n\n<p>But, if you use vim in MS-DOS, of win9x, win2000, you loss these toolkit.\nhere is a very simple way to archive this only by vim:</p>\n\n<pre><code>fu! LineIt()\n exe \":s/^/\".line(\".\").\"/\"\nendf\n</code></pre>\n\n<p>Or, a sequence composed with alphabet is as easy as above:</p>\n\n<pre><code>exe \"s/^/\".nr2char(line(\".\")).\"/\" \n</code></pre>\n\n<p>You can also use a subst:</p>\n\n<pre><code>:g/^/exe \":s/^/\".line(\".\").\"^I/\"\n</code></pre>\n\n<hr>\n\n<p>You can also only want to print the lines without adding them to the file:</p>\n\n<blockquote>\n <p>\"Sometimes it could be useful especially be editing large source files to print the line numbers out on paper.<br>\n To do so you can use the option <code>:set printoptions=number:y</code> to activate and <code>:set printoptions=number:n</code> to deactivate this feature.<br>\n If the line number should be printed always, place the line <code>set printoptions=number:y</code> in the <code>vimrc</code>.\" </p>\n</blockquote>\n"
},
{
"answer_id": 252777,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 5,
"selected": false,
"text": "<p>On a GNU system: with the external <code>nl</code> binary:</p>\n\n<pre><code>:%!nl\n</code></pre>\n"
},
{
"answer_id": 253041,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 8,
"selected": true,
"text": "<p>With</p>\n\n<pre><code>:%s/^/\\=line('.')/\n</code></pre>\n\n<p>EDIT: to sum up the comments. </p>\n\n<p>This command can be tweaked as much as you want.</p>\n\n<hr>\n\n<p>Let's say you want to add numbers in front of lines from a visual selection (<code>V</code> + move), and you want the numbering to start at 42.</p>\n\n<pre><code>:'<,'>s/^/\\=(line('.')-line(\"'<\")+42)/\n</code></pre>\n\n<hr>\n\n<p>If you want to add a string between the number and the old text from the line, just concatenate (with <code>.</code> in VimL) it to the number-expression:</p>\n\n<pre><code>:'<,'>s/^/\\=(line('.')-line(\"'<\")+42).' --> '/\n</code></pre>\n\n<hr>\n\n<p>If you need this to sort as text, you may want to zero pad the results, which can be done using <code>printf</code> for <code>0001, 0002</code> ... instead of <code>1, 2</code>... eg:</p>\n\n<pre><code>:%s/^/\\=printf('%04d', line('.'))/\n</code></pre>\n\n<hr>\n\n<p>Anyway, if you want more information, just open vim help: <code>:h :s</code> and follow the links (<code>|subreplace-special|</code>, ..., <code>|submatch()|</code>)</p>\n"
},
{
"answer_id": 256296,
"author": "Brian Carper",
"author_id": 23070,
"author_profile": "https://Stackoverflow.com/users/23070",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"http://www.vim.org/scripts/script.php?script_id=670\" rel=\"nofollow noreferrer\">\"VisIncr\"</a> plugin is good for inserting columns of incrementing numbers in general (or letters, dates, roman numerals etc.). You can control the number format, padding, and so on. So insert a \"1\" in front of every line (via <code>:s</code> or <code>:g</code> or visual-block insert), highlight that column in visual-block mode, and run one of the commands from the plugin.</p>\n"
},
{
"answer_id": 4674574,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 2,
"selected": false,
"text": "<p>First, you can remove the existing line numbers if you need to:</p>\n\n<pre><code>:%s/^[0-9]*//\n</code></pre>\n\n<p>Then, you can add line numbers. <code>NR</code> refers to the current line number starting at one, so you can do some math on it to get the numbering you want. The following command gives you four digit line numbers:</p>\n\n<pre><code>:%!awk '{print 1000+NR*10,$0}'\n</code></pre>\n"
},
{
"answer_id": 52234354,
"author": "kmario23",
"author_id": 2956066,
"author_profile": "https://Stackoverflow.com/users/2956066",
"pm_score": 0,
"selected": false,
"text": "<p>If someone wants to put a tab (or some spaces) after inserting the line numbers using the <a href=\"https://stackoverflow.com/a/253041/2956066\">this excellent answer</a>, here's a way. After going into the escape mode, do:</p>\n\n<pre><code>:%s/^/\\=line('.').' '/\n</code></pre>\n\n<p><code>^</code> means beginning of a line and <code>%s</code> is the directive for substitution. So, we say that put a line number at the beginning of each line and add 4 spaces to it and then put whatever was the contents of the line before the substitution, and do this for all lines in the file.</p>\n\n<p>This will automatically substitute it. Alternatively, if you want the command to ask for confirmation from you, then do:</p>\n\n<pre><code>:%s/^/\\=line('.').' '/igc\n</code></pre>\n\n<p>P.S: power of <strong>vim</strong> :)</p>\n"
},
{
"answer_id": 72854071,
"author": "Antonio",
"author_id": 6266107,
"author_profile": "https://Stackoverflow.com/users/6266107",
"pm_score": 0,
"selected": false,
"text": "<p>The best reply is done in a <a href=\"https://stackoverflow.com/a/70209677/6266107\">duplicate question</a>.</p>\n<p>In summary:<br />\nwith <code>CTRL-V</code> then <code>G</code> <code>I</code> <code>0 </code> You can insert a column of zero.</p>\n<p>Then select the whole column and increment:<br />\n<code>CTRL-V</code> <code>g CTRL-A</code></p>\n<p>See also: <a href=\"https://vim.fandom.com/wiki/Making_a_list_of_numbers#Incrementing_selected_numbers\" rel=\"nofollow noreferrer\">https://vim.fandom.com/wiki/Making_a_list_of_numbers#Incrementing_selected_numbers</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31641/"
] |
How can I add line numbers to a range of lines in a file opened in Vim? Not as in `:set nu`—this just *displays* line numbers—but actually have them be prepended to each line in the file?
|
With
```
:%s/^/\=line('.')/
```
EDIT: to sum up the comments.
This command can be tweaked as much as you want.
---
Let's say you want to add numbers in front of lines from a visual selection (`V` + move), and you want the numbering to start at 42.
```
:'<,'>s/^/\=(line('.')-line("'<")+42)/
```
---
If you want to add a string between the number and the old text from the line, just concatenate (with `.` in VimL) it to the number-expression:
```
:'<,'>s/^/\=(line('.')-line("'<")+42).' --> '/
```
---
If you need this to sort as text, you may want to zero pad the results, which can be done using `printf` for `0001, 0002` ... instead of `1, 2`... eg:
```
:%s/^/\=printf('%04d', line('.'))/
```
---
Anyway, if you want more information, just open vim help: `:h :s` and follow the links (`|subreplace-special|`, ..., `|submatch()|`)
|
252,780 |
<p>I have seen many programs consisting of structures like the one below</p>
<pre><code>typedef struct
{
int i;
char k;
} elem;
elem user;
</code></pre>
<p>Why is it needed so often? Any specific reason or applicable area?</p>
|
[
{
"answer_id": 252783,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "<p>Using a <code>typedef</code> avoids having to write <code>struct</code> every time you declare a variable of that type:</p>\n\n<pre><code>struct elem\n{\n int i;\n char k;\n};\nelem user; // compile error!\nstruct elem user; // this is correct\n</code></pre>\n"
},
{
"answer_id": 252810,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 10,
"selected": true,
"text": "<p>As Greg Hewgill said, the typedef means you no longer have to write <code>struct</code> all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.</p>\n\n<p>Stuff like</p>\n\n<pre><code>typedef struct {\n int x, y;\n} Point;\n\nPoint point_new(int x, int y)\n{\n Point a;\n a.x = x;\n a.y = y;\n return a;\n}\n</code></pre>\n\n<p>becomes cleaner when you don't need to see the \"struct\" keyword all over the place, it looks more as if there really is a type called \"Point\" in your language. Which, after the <code>typedef</code>, is the case I guess.</p>\n\n<p>Also note that while your example (and mine) omitted naming the <code>struct</code> itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:</p>\n\n<pre><code>typedef struct Point Point;\n\nPoint * point_new(int x, int y);\n</code></pre>\n\n<p>and then provide the <code>struct</code> definition in the implementation file:</p>\n\n<pre><code>struct Point\n{\n int x, y;\n};\n\nPoint * point_new(int x, int y)\n{\n Point *p;\n if((p = malloc(sizeof *p)) != NULL)\n {\n p->x = x;\n p->y = y;\n }\n return p;\n}\n</code></pre>\n\n<p>In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in <a href=\"http://www.gtk.org/\" rel=\"noreferrer\">GTK+</a>, for instance.</p>\n\n<p><strong>UPDATE</strong> Note that there are also highly-regarded C projects where this use of <code>typedef</code> to hide <code>struct</code> is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of <a href=\"https://www.kernel.org/doc/html/latest/process/coding-style.html#typedefs\" rel=\"noreferrer\">The Linux Kernel CodingStyle document</a> for Linus' angry words. :) My point is that the \"should\" in the question is perhaps not set in stone, after all.</p>\n"
},
{
"answer_id": 252867,
"author": "philsquared",
"author_id": 32136,
"author_profile": "https://Stackoverflow.com/users/32136",
"pm_score": 3,
"selected": false,
"text": "<p>The name you (optionally) give the struct is called the <em>tag name</em> and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.</p>\n<p>GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:</p>\n<pre><code>struct MyStruct\n{\n int i;\n};\n\n// The following is legal in C++:\nMyStruct obj;\nobj.i = 7;\n</code></pre>\n"
},
{
"answer_id": 254250,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 7,
"selected": false,
"text": "<p>From an old article by Dan Saks (<a href=\"http://www.ddj.com/cpp/184403396?pgno=3\" rel=\"noreferrer\">http://www.ddj.com/cpp/184403396?pgno=3</a>):</p>\n\n<hr>\n\n<blockquote>\n <p>The C language rules for naming\n structs are a little eccentric, but\n they're pretty harmless. However, when\n extended to classes in C++, those same\n rules open little cracks for bugs to\n crawl through.</p>\n \n <p>In C, the name s appearing in</p>\n\n<pre><code>struct s\n {\n ...\n };\n</code></pre>\n \n <p>is a tag. A tag name is not a type\n name. Given the definition above,\n declarations such as</p>\n\n<pre><code>s x; /* error in C */\ns *p; /* error in C */\n</code></pre>\n \n <p>are errors in C. You must write them\n as</p>\n\n<pre><code>struct s x; /* OK */\nstruct s *p; /* OK */\n</code></pre>\n \n <p>The names of unions and enumerations\n are also tags rather than types.</p>\n \n <p>In C, tags are distinct from all other\n names (for functions, types,\n variables, and enumeration constants).\n C compilers maintain tags in a symbol\n table that's conceptually if not\n physically separate from the table\n that holds all other names. Thus, it\n is possible for a C program to have\n both a tag and an another name with\n the same spelling in the same scope.\n For example,</p>\n\n<pre><code>struct s s;\n</code></pre>\n \n <p>is a valid declaration which declares\n variable s of type struct s. It may\n not be good practice, but C compilers\n must accept it. I have never seen a\n rationale for why C was designed this\n way. I have always thought it was a\n mistake, but there it is.</p>\n \n <p>Many programmers (including yours\n truly) prefer to think of struct names\n as type names, so they define an alias\n for the tag using a typedef. For\n example, defining</p>\n\n<pre><code>struct s\n {\n ...\n };\ntypedef struct s S;\n</code></pre>\n \n <p>lets you use S in place of struct s,\n as in</p>\n\n<pre><code>S x;\nS *p;\n</code></pre>\n \n <p>A program cannot use S as the name of\n both a type and a variable (or\n function or enumeration constant):</p>\n\n<pre><code>S S; // error\n</code></pre>\n \n <p>This is good.</p>\n \n <p>The tag name in a struct, union, or\n enum definition is optional. Many\n programmers fold the struct definition\n into the typedef and dispense with the\n tag altogether, as in:</p>\n\n<pre><code>typedef struct\n {\n ...\n } S;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The linked article also has a discussion about how the C++ behavior of not requireing a <code>typedef</code> can cause subtle name hiding problems. To prevent these problems, it's a good idea to <code>typedef</code> your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the <code>typedef</code> the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.</p>\n"
},
{
"answer_id": 699528,
"author": "cschol",
"author_id": 2386,
"author_profile": "https://Stackoverflow.com/users/2386",
"pm_score": 6,
"selected": false,
"text": "<p>One other good reason to always typedef enums and structs results from this problem:</p>\n\n<pre><code>enum EnumDef\n{\n FIRST_ITEM,\n SECOND_ITEM\n};\n\nstruct StructDef\n{\n enum EnuumDef MyEnum;\n unsigned int MyVar;\n} MyStruct;\n</code></pre>\n\n<p>Notice the typo in EnumDef in the struct (Enu<strong>u</strong>mDef)? This compiles without error (or warning) and is (depending on the literal interpretation of the C Standard) correct. The problem is that I just created an new (empty) enumeration definition within my struct. I am not (as intended) using the previous definition EnumDef.</p>\n\n<p>With a typdef similar kind of typos would have resulted in a compiler errors for using an unknown type:</p>\n\n<pre><code>typedef \n{\n FIRST_ITEM,\n SECOND_ITEM\n} EnumDef;\n\ntypedef struct\n{\n EnuumDef MyEnum; /* compiler error (unknown type) */\n unsigned int MyVar;\n} StructDef;\nStrructDef MyStruct; /* compiler error (unknown type) */\n</code></pre>\n\n<p>I would advocate ALWAYS typedef'ing structs and enumerations. </p>\n\n<p>Not only to save some typing (no pun intended ;)), but because it is safer.</p>\n"
},
{
"answer_id": 2392856,
"author": "doccpu",
"author_id": 287771,
"author_profile": "https://Stackoverflow.com/users/287771",
"pm_score": -1,
"selected": false,
"text": "<p>At all, in C language, struct/union/enum are macro instruction processed by the C language preprocessor (do not mistake with the preprocessor that treat \"#include\" and other)</p>\n\n<p>so :</p>\n\n<pre><code>struct a\n{\n int i;\n};\n\nstruct b\n{\n struct a;\n int i;\n int j;\n};\n</code></pre>\n\n<p>struct b is expended as something like this :</p>\n\n<pre><code>struct b\n{\n struct a\n {\n int i;\n };\n int i;\n int j;\n}\n</code></pre>\n\n<p>and so, at compile time it evolve on stack as something like:\nb:\nint ai\nint i\nint j</p>\n\n<p>that also why it's dificult to have selfreferent structs, C preprocessor round in a déclaration loop that can't terminate.</p>\n\n<p>typedef are type specifier, that means only C compiler process it and it can do like he want for optimise assembler code implementation. It also dont expend member of type par stupidly like préprocessor do with structs but use more complex reference construction algorithm, so construction like :</p>\n\n<pre><code>typedef struct a A; //anticipated declaration for member declaration\n\ntypedef struct a //Implemented declaration\n{\n A* b; // member declaration\n}A;\n</code></pre>\n\n<p>is permited and fully functional. This implementation give also access to compilator type conversion and remove some bugging effects when execution thread leave the application field of initialisation functions. </p>\n\n<p>This mean that in C typedefs are more near as C++ class than lonely structs.</p>\n"
},
{
"answer_id": 2934163,
"author": "natersoz",
"author_id": 138264,
"author_profile": "https://Stackoverflow.com/users/138264",
"pm_score": 4,
"selected": false,
"text": "<p>I don't think forward declarations are even possible with typedef. Use of struct, enum, and union allow for forwarding declarations when dependencies (knows about) is bidirectional.</p>\n\n<p>Style:\nUse of typedef in C++ makes quite a bit of sense. It can almost be necessary when dealing with templates that require multiple and/or variable parameters. The typedef helps keep the naming straight.</p>\n\n<p>Not so in the C programming language. The use of typedef most often serves no purpose but to obfuscate the data structure usage. Since only { struct (6), enum (4), union (5) } number of keystrokes are used to declare a data type there is almost no use for the aliasing of the struct. Is that data type a union or a struct? Using the straightforward non-typdefed declaration lets you know right away what type it is. </p>\n\n<p>Notice how Linux is written with strict avoidance of this aliasing nonsense typedef brings. The result is a minimalist and clean style.</p>\n"
},
{
"answer_id": 4566358,
"author": "Jerry Hicks",
"author_id": 558731,
"author_profile": "https://Stackoverflow.com/users/558731",
"pm_score": 8,
"selected": false,
"text": "<p>It's amazing how many people get this wrong. PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs.</p>\n\n<p>Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.</p>\n\n<p>Consider:</p>\n\n<pre><code>#ifndef FOO_H\n#define FOO_H 1\n\n#define FOO_DEF (0xDEADBABE)\n\nstruct bar; /* forward declaration, defined in bar.h*/\n\nstruct foo {\n struct bar *bar;\n};\n\n#endif\n</code></pre>\n\n<p>With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the <code>FOO_DEF</code> definition. If it doesn't attempt to dereference the 'bar' member of the <code>foo</code> struct then there will be no need to include the \"bar.h\" file.</p>\n\n<p>Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:</p>\n\n<pre><code>struct foo *foo;\n\nprintf(\"foo->bar = %p\", foo->bar);\n</code></pre>\n\n<p>Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.</p>\n\n<p>If I have to maintain your code, I will remove your typedef'd structs.</p>\n"
},
{
"answer_id": 18105888,
"author": "Yu Hao",
"author_id": 1009479,
"author_profile": "https://Stackoverflow.com/users/1009479",
"pm_score": 5,
"selected": false,
"text": "<p><a href=\"https://www.kernel.org/doc/Documentation/process/coding-style.rst\" rel=\"nofollow noreferrer\">Linux kernel coding style</a> Chapter 5 gives great pros and cons (mostly cons) of using <code>typedef</code>.</p>\n<blockquote>\n<p>Please don't use things like "vps_t".</p>\n<p>It's a <em>mistake</em> to use typedef for structures and pointers. When you see a</p>\n<pre><code>vps_t a;\n</code></pre>\n<p>in the source, what does it mean?</p>\n<p>In contrast, if it says</p>\n<pre><code>struct virtual_container *a;\n</code></pre>\n<p>you can actually tell what "a" is.</p>\n<p>Lots of people think that typedefs "help readability". Not so. They are useful only for:</p>\n<p>(a) totally opaque objects (where the typedef is actively used to <em>hide</em> what the object is).</p>\n<p>Example: "pte_t" etc. opaque objects that you can only access using the proper accessor functions.</p>\n<p>NOTE! Opaqueness and "accessor functions" are not good in themselves. The reason we have them for things like pte_t etc. is that there really is absolutely <em>zero</em> portably accessible information there.</p>\n<p>(b) Clear integer types, where the abstraction <em>helps</em> avoid confusion whether it is "int" or "long".</p>\n<p>u8/u16/u32 are perfectly fine typedefs, although they fit into category (d) better than here.</p>\n<p>NOTE! Again - there needs to be a <em>reason</em> for this. If something is "unsigned long", then there's no reason to do</p>\n<pre><code>typedef unsigned long myflags_t;\n</code></pre>\n<p>but if there is a clear reason for why it under certain circumstances might be an "unsigned int" and under other configurations might be "unsigned long", then by all means go ahead and use a typedef.</p>\n<p>(c) when you use sparse to literally create a <em>new</em> type for type-checking.</p>\n<p>(d) New types which are identical to standard C99 types, in certain exceptional circumstances.</p>\n<p>Although it would only take a short amount of time for the eyes and brain to become accustomed to the standard types like 'uint32_t', some people object to their use anyway.</p>\n<p>Therefore, the Linux-specific 'u8/u16/u32/u64' types and their signed equivalents which are identical to standard types are permitted -- although they are not mandatory in new code of your own.</p>\n<p>When editing existing code which already uses one or the other set of types, you should conform to the existing choices in that code.</p>\n<p>(e) Types safe for use in userspace.</p>\n<p>In certain structures which are visible to userspace, we cannot require C99 types and cannot use the 'u32' form above. Thus, we use __u32 and similar types in all structures which are shared with userspace.</p>\n<p>Maybe there are other cases too, but the rule should basically be to NEVER EVER use a typedef unless you can clearly match one of those rules.</p>\n<p>In general, a pointer, or a struct that has elements that can reasonably be directly accessed should <em>never</em> be a typedef.</p>\n</blockquote>\n"
},
{
"answer_id": 18173698,
"author": "user1533288",
"author_id": 1533288,
"author_profile": "https://Stackoverflow.com/users/1533288",
"pm_score": 4,
"selected": false,
"text": "<p>It turns out that there are pros and cons. A useful source of information is the seminal book "Expert C Programming" (<a href=\"http://www.e-reading-lib.com/bookreader.php/138815/Expert_C_Programming:_Deep_C_Secrets.pdf\" rel=\"nofollow noreferrer\">Chapter 3</a>). Briefly, in C you have multiple namespaces: <strong>tags, types, member names and identifiers</strong>. <code>typedef</code> introduces an alias for a type and locates it in the tag namespace. Namely,</p>\n<pre><code>typedef struct Tag{\n...members...\n}Type;\n</code></pre>\n<p>defines two things. 1) Tag in the tag namespace and 2) Type in the type namespace. So you can do both <code>Type myType</code> and <code>struct Tag myTagType</code>. Declarations like <code>struct Type myType</code> or <code>Tag myTagType</code> are illegal. In addition, in a declaration like this:</p>\n<pre><code>typedef Type *Type_ptr;\n</code></pre>\n<p>we define a pointer to our Type. So if we declare:</p>\n<pre><code>Type_ptr var1, var2;\nstruct Tag *myTagType1, myTagType2;\n</code></pre>\n<p>then <code>var1</code>,<code>var2</code> and <code>myTagType1</code> are pointers to Type but <code>myTagType2</code> not.</p>\n<p>In the above-mentioned book, it mentions that typedefing structs are not very useful as it only saves the programmer from writing the word struct. However, I have an objection, like many other C programmers. Although it sometimes turns to obfuscate some names (that's why it is not advisable in large code bases like the kernel) when you want to implement polymorphism in C it helps a lot <a href=\"http://modal-echoes.blogspot.com/2007/03/implementing-polymorphism-in-c.html\" rel=\"nofollow noreferrer\">look here for details</a>. Example:</p>\n<pre><code>typedef struct MyWriter_t{\n MyPipe super;\n MyQueue relative;\n uint32_t flags;\n...\n}MyWriter;\n</code></pre>\n<p>you can do:</p>\n<pre><code>void my_writer_func(MyPipe *s)\n{\n MyWriter *self = (MyWriter *) s;\n uint32_t myFlags = self->flags;\n...\n}\n</code></pre>\n<p>So you can access an outer member (<code>flags</code>) by the inner struct (<code>MyPipe</code>) through casting. For me it is less confusing to cast the whole type than doing <code>(struct MyWriter_ *) s;</code> every time you want to perform such functionality. In these cases brief referencing is a big deal especially if you heavily employ the technique in your code.</p>\n<p>Finally, the last aspect with <code>typedef</code>ed types is the inability to extend them, in contrast to macros. If for example, you have:</p>\n<pre><code>#define X char[10] or\ntypedef char Y[10]\n</code></pre>\n<p>you can then declare</p>\n<pre><code>unsigned X x; but not\nunsigned Y y;\n</code></pre>\n<p>We do not really care for this for structs because it does not apply to storage specifiers (<code>volatile</code> and <code>const</code>).</p>\n"
},
{
"answer_id": 35103707,
"author": "natersoz",
"author_id": 138264,
"author_profile": "https://Stackoverflow.com/users/138264",
"pm_score": 1,
"selected": false,
"text": "<p>typedef will not provide a co-dependent set of data structures. This you cannot do with typdef:</p>\n\n<pre><code>struct bar;\nstruct foo;\n\nstruct foo {\n struct bar *b;\n};\n\nstruct bar {\n struct foo *f;\n};\n</code></pre>\n\n<p>Of course you can always add:</p>\n\n<pre><code>typedef struct foo foo_t;\ntypedef struct bar bar_t;\n</code></pre>\n\n<p>What exactly is the point of that?</p>\n"
},
{
"answer_id": 37758915,
"author": "RichardGeerify",
"author_id": 6449990,
"author_profile": "https://Stackoverflow.com/users/6449990",
"pm_score": 1,
"selected": false,
"text": "<p>In 'C' programming language the keyword 'typedef' is used to declare a new name for some object(struct, array, function..enum type). For example, I will use a 'struct-s'.\nIn 'C' we often declare a 'struct' outside of the 'main' function. For example:</p>\n\n<pre><code>struct complex{ int real_part, img_part }COMPLEX;\n\nmain(){\n\n struct KOMPLEKS number; // number type is now a struct type\n number.real_part = 3;\n number.img_part = -1;\n printf(\"Number: %d.%d i \\n\",number.real_part, number.img_part);\n\n}\n</code></pre>\n\n<p>Each time I decide to use a struct type I will need this keyword 'struct 'something' 'name'.'typedef' will simply rename that type and I can use that new name in my program every time I want. So our code will be:</p>\n\n<pre><code>typedef struct complex{int real_part, img_part; }COMPLEX;\n//now COMPLEX is the new name for this structure and if I want to use it without\n// a keyword like in the first example 'struct complex number'.\n\nmain(){\n\nCOMPLEX number; // number is now the same type as in the first example\nnumber.real_part = 1;\nnumber.img)part = 5;\nprintf(\"%d %d \\n\", number.real_part, number.img_part);\n\n}\n</code></pre>\n\n<p>If you have some local object(struct, array, valuable) that will be used in your entire program you can simply give it a name using a 'typedef'. </p>\n"
},
{
"answer_id": 40376541,
"author": "Matthew Corey Brown",
"author_id": 7103828,
"author_profile": "https://Stackoverflow.com/users/7103828",
"pm_score": 0,
"selected": false,
"text": "<p>Turns out in C99 typedef is required. It is outdated, but a lot of tools (ala HackRank) use c99 as its pure C implementation. And typedef is required there.</p>\n\n<p>I'm not saying they should change (maybe have two C options) if the requirement changed, those of us studing for interviews on the site would be SOL. </p>\n"
},
{
"answer_id": 44915443,
"author": "JamesAD-0",
"author_id": 4718990,
"author_profile": "https://Stackoverflow.com/users/4718990",
"pm_score": 1,
"selected": false,
"text": "<p>A>\na typdef aids in the meaning and documentation of a program by allowing <strong>creation of more meaningful synonyms for data types</strong>. In addition, they help parameterize a program against portability problems (K&R, pg147, C prog lang).</p>\n\n<p>B>\n<strong>a structure defines a type</strong>. Structs allows convenient grouping of a collection of vars for convenience of handling (K&R, pg127, C prog lang.) as a single unit</p>\n\n<p>C>\ntypedef'ing a struct is explained in A above.</p>\n\n<p>D> To me, structs are custom types or containers or collections or namespaces or complex types, whereas a typdef is just a means to create more nicknames. </p>\n"
},
{
"answer_id": 49199821,
"author": "Asif",
"author_id": 8638742,
"author_profile": "https://Stackoverflow.com/users/8638742",
"pm_score": 3,
"selected": false,
"text": "<p>Let's start with the basics and work our way up.</p>\n\n<p>Here is an example of Structure definition:</p>\n\n<pre><code>struct point\n {\n int x, y;\n };\n</code></pre>\n\n<p>Here the name <code>point</code> is optional.</p>\n\n<p>A Structure can be declared during its definition or after.</p>\n\n<p>Declaring during definition</p>\n\n<pre><code>struct point\n {\n int x, y;\n } first_point, second_point;\n</code></pre>\n\n<p>Declaring after definition</p>\n\n<pre><code>struct point\n {\n int x, y;\n };\nstruct point first_point, second_point;\n</code></pre>\n\n<p>Now, carefully note the last case above; you need to write <code>struct point</code> to declare Structures of that type if you decide to create that type at a later point in your code.</p>\n\n<p>Enter <code>typedef</code>. If you intend to create new Structure ( Structure is a custom data-type) at a later time in your program using the same blueprint, using <code>typedef</code> during its definition might be a good idea since you can save some typing moving forward.</p>\n\n<pre><code>typedef struct point\n {\n int x, y;\n } Points;\n\nPoints first_point, second_point;\n</code></pre>\n\n<h1>A word of caution while naming your custom type</h1>\n\n<p>Nothing prevents you from using _t suffix at the end of your custom type name but POSIX standard reserves the use of suffix _t to denote standard library type names.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
I have seen many programs consisting of structures like the one below
```
typedef struct
{
int i;
char k;
} elem;
elem user;
```
Why is it needed so often? Any specific reason or applicable area?
|
As Greg Hewgill said, the typedef means you no longer have to write `struct` all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.
Stuff like
```
typedef struct {
int x, y;
} Point;
Point point_new(int x, int y)
{
Point a;
a.x = x;
a.y = y;
return a;
}
```
becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the `typedef`, is the case I guess.
Also note that while your example (and mine) omitted naming the `struct` itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:
```
typedef struct Point Point;
Point * point_new(int x, int y);
```
and then provide the `struct` definition in the implementation file:
```
struct Point
{
int x, y;
};
Point * point_new(int x, int y)
{
Point *p;
if((p = malloc(sizeof *p)) != NULL)
{
p->x = x;
p->y = y;
}
return p;
}
```
In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in [GTK+](http://www.gtk.org/), for instance.
**UPDATE** Note that there are also highly-regarded C projects where this use of `typedef` to hide `struct` is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of [The Linux Kernel CodingStyle document](https://www.kernel.org/doc/html/latest/process/coding-style.html#typedefs) for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.
|
252,782 |
<p>What is the purpose of the <code>strdup()</code> function in C?</p>
|
[
{
"answer_id": 252786,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": false,
"text": "<p>From <a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/strdup.html\" rel=\"noreferrer\">strdup man</a>:</p>\n\n<p>The <code>strdup()</code> function shall return a pointer to a new string, which is a duplicate of the string pointed to by <code>s1</code>. The returned pointer can be passed to <code>free()</code>. A null pointer is returned if the new string cannot be created.</p>\n"
},
{
"answer_id": 252792,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 2,
"selected": false,
"text": "<p>It makes a duplicate copy of the string passed in by running a <strong>malloc</strong> and <strong>strcpy</strong> of the string passed in. The malloc'ed buffer is returned to the caller, hence the need to run <strong>free</strong> on the return value.</p>\n"
},
{
"answer_id": 252797,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 1,
"selected": false,
"text": "<p>The most valuable thing it does is give you another string identical to the first, without requiring you to allocate memory (location and size) yourself. But, as noted, you still need to free it (but which doesn't require a quantity calculation, either.)</p>\n"
},
{
"answer_id": 252802,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 10,
"selected": true,
"text": "<p>Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it <em><strong>duplicates strings</strong></em> :-)</p>\n<p>Keeping in mind it's actually not part of the current (C17) ISO C standard itself<sup>(a)</sup> (it's a POSIX thing), it's effectively doing the same as the following code:</p>\n<pre><code>char *strdup(const char *src) {\n char *dst = malloc(strlen (src) + 1); // Space for length plus nul\n if (dst == NULL) return NULL; // No memory\n strcpy(dst, src); // Copy the characters\n return dst; // Return the new string\n}\n</code></pre>\n<p>In other words:</p>\n<ol>\n<li><p>It tries to allocate enough memory to hold the old string (plus a '\\0' character to mark the end of the string).</p>\n</li>\n<li><p>If the allocation failed, it sets <code>errno</code> to <code>ENOMEM</code> and returns <code>NULL</code> immediately. Setting of <code>errno</code> to <code>ENOMEM</code> is something <code>malloc</code> does in POSIX so we don't need to explicitly do it in our <code>strdup</code>. If you're <em>not</em> POSIX compliant, ISO C doesn't actually mandate the existence of <code>ENOMEM</code> so I haven't included that here<sup>(b)</sup>.</p>\n</li>\n<li><p>Otherwise the allocation worked so we copy the old string to the new string<sup>(c)</sup> and return the new address (which the caller is responsible for freeing at some point).</p>\n</li>\n</ol>\n<p>Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.</p>\n<p>One other thing to keep in mind, it looks like this <em>is</em> currently slated to be in the C2x iteration of the standard, along with <code>strndup</code>, as per draft <code>N2912</code> of the document.</p>\n<hr />\n<p><sup>(a)</sup> However, functions starting with <code>str</code> and a lower case letter are reserved by the standard for future directions. From <code>C11 7.1.3 Reserved identifiers</code>:</p>\n<blockquote>\n<p>Each header declares or defines all identifiers listed in its associated sub-clause, and <em>optionally declares or defines identifiers listed in its associated future library directions sub-clause.</em>*</p>\n</blockquote>\n<p>The future directions for <code>string.h</code> can be found in <code>C11 7.31.13 String handling <string.h></code>:</p>\n<blockquote>\n<p>Function names that begin with <code>str</code>, <code>mem</code>, or <code>wcs</code> and a lowercase letter may be added to the declarations in the <code><string.h></code> header.</p>\n</blockquote>\n<p>So you should probably call it something else if you want to be safe.</p>\n<hr />\n<p><sup>(b)</sup> The change would basically be replacing <code>if (d == NULL) return NULL;</code> with:</p>\n<pre><code>if (d == NULL) {\n errno = ENOMEM;\n return NULL;\n}\n</code></pre>\n<hr />\n<p><sup>(c)</sup> Note that I use <code>strcpy</code> for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use <code>memcpy</code>, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".</p>\n<p>In any case, should you decide to go that route, you would do something like:</p>\n<pre><code>char *strdup(const char *src) {\n size_t len = strlen(src) + 1; // String plus '\\0'\n char *dst = malloc(len); // Allocate space\n if (dst == NULL) return NULL; // No memory\n memcpy (dst, src, len); // Copy the block\n return dst; // Return the new string\n}\n</code></pre>\n"
},
{
"answer_id": 252977,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 6,
"selected": false,
"text": "<p>No point repeating the other answers, but please note that <code>strdup()</code> can do anything it wants from a C perspective, since it is not part of any C standard. It is however defined by POSIX.1-2001.</p>\n"
},
{
"answer_id": 1809465,
"author": "Patrick Schlüter",
"author_id": 146377,
"author_profile": "https://Stackoverflow.com/users/146377",
"pm_score": 6,
"selected": false,
"text": "<pre><code>char * strdup(const char * s)\n{\n size_t len = 1+strlen(s);\n char *p = malloc(len);\n\n return p ? memcpy(p, s, len) : NULL;\n}\n</code></pre>\n\n<p>Maybe the code is a bit faster than with <code>strcpy()</code> as the <code>\\0</code> char doesn't need to be searched again (It already was with <code>strlen()</code>).</p>\n"
},
{
"answer_id": 17339998,
"author": "Karshit",
"author_id": 2527523,
"author_profile": "https://Stackoverflow.com/users/2527523",
"pm_score": 2,
"selected": false,
"text": "<p>strdup() does dynamic memory allocation for the character array including the end character '\\0' and returns the address of the heap memory:</p>\n\n<pre><code>char *strdup (const char *s)\n{\n char *p = malloc (strlen (s) + 1); // allocate memory\n if (p != NULL)\n strcpy (p,s); // copy string\n return p; // return the memory\n}\n</code></pre>\n\n<p>So, what it does is give us another string identical to the string given by its argument, without requiring us to allocate memory. But we still need to free it, later.</p>\n"
},
{
"answer_id": 24719941,
"author": "AnkitSablok",
"author_id": 862962,
"author_profile": "https://Stackoverflow.com/users/862962",
"pm_score": 0,
"selected": false,
"text": "<p>The strdup() function is a shorthand for string duplicate, it takes in a parameter as a string constant or a string literal and allocates just enough space for the string and writes the corresponding characters in the space allocated and finally returns the address of the allocated space to the calling routine.</p>\n"
},
{
"answer_id": 27525141,
"author": "Sujay Kumar",
"author_id": 2895956,
"author_profile": "https://Stackoverflow.com/users/2895956",
"pm_score": 2,
"selected": false,
"text": "<p><code>strdup</code> and <code>strndup</code> are defined in POSIX compliant systems as:</p>\n\n<pre><code>char *strdup(const char *str);\nchar *strndup(const char *str, size_t len);\n</code></pre>\n\n<p>The <strong>strdup()</strong> function allocates sufficient memory for a copy of the\nstring <code>str</code>, does the copy, and returns a pointer to it.</p>\n\n<p>The pointer may subsequently be used as an argument to the function <code>free</code>.</p>\n\n<p>If insufficient memory is available, <code>NULL</code> is returned and <code>errno</code> is set to\n<code>ENOMEM</code>.</p>\n\n<p>The <strong>strndup()</strong> function copies at most <code>len</code> characters from the string <code>str</code> always null terminating the copied string.</p>\n"
},
{
"answer_id": 34061716,
"author": "Md. Al Amin Bhuiyan",
"author_id": 4636819,
"author_profile": "https://Stackoverflow.com/users/4636819",
"pm_score": 1,
"selected": false,
"text": "<p>The statement:</p>\n\n<pre><code>strcpy(ptr2, ptr1);\n</code></pre>\n\n<p>is equivalent to (other than the fact this changes the pointers):</p>\n\n<pre><code>while(*ptr2++ = *ptr1++);\n</code></pre>\n\n<p>Whereas:</p>\n\n<pre><code>ptr2 = strdup(ptr1);\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>ptr2 = malloc(strlen(ptr1) + 1);\nif (ptr2 != NULL) strcpy(ptr2, ptr1);\n</code></pre>\n\n<p>So, if you want the string which you have copied to be used in another function (as it is created in heap section), you can use <code>strdup</code>, else <code>strcpy</code> is enough,</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
What is the purpose of the `strdup()` function in C?
|
Exactly what it sounds like, assuming you're used to the abbreviated way in which C and UNIX assigns words, it ***duplicates strings*** :-)
Keeping in mind it's actually not part of the current (C17) ISO C standard itself(a) (it's a POSIX thing), it's effectively doing the same as the following code:
```
char *strdup(const char *src) {
char *dst = malloc(strlen (src) + 1); // Space for length plus nul
if (dst == NULL) return NULL; // No memory
strcpy(dst, src); // Copy the characters
return dst; // Return the new string
}
```
In other words:
1. It tries to allocate enough memory to hold the old string (plus a '\0' character to mark the end of the string).
2. If the allocation failed, it sets `errno` to `ENOMEM` and returns `NULL` immediately. Setting of `errno` to `ENOMEM` is something `malloc` does in POSIX so we don't need to explicitly do it in our `strdup`. If you're *not* POSIX compliant, ISO C doesn't actually mandate the existence of `ENOMEM` so I haven't included that here(b).
3. Otherwise the allocation worked so we copy the old string to the new string(c) and return the new address (which the caller is responsible for freeing at some point).
Keep in mind that's the conceptual definition. Any library writer worth their salary may have provided heavily optimised code targeting the particular processor being used.
One other thing to keep in mind, it looks like this *is* currently slated to be in the C2x iteration of the standard, along with `strndup`, as per draft `N2912` of the document.
---
(a) However, functions starting with `str` and a lower case letter are reserved by the standard for future directions. From `C11 7.1.3 Reserved identifiers`:
>
> Each header declares or defines all identifiers listed in its associated sub-clause, and *optionally declares or defines identifiers listed in its associated future library directions sub-clause.*\*
>
>
>
The future directions for `string.h` can be found in `C11 7.31.13 String handling <string.h>`:
>
> Function names that begin with `str`, `mem`, or `wcs` and a lowercase letter may be added to the declarations in the `<string.h>` header.
>
>
>
So you should probably call it something else if you want to be safe.
---
(b) The change would basically be replacing `if (d == NULL) return NULL;` with:
```
if (d == NULL) {
errno = ENOMEM;
return NULL;
}
```
---
(c) Note that I use `strcpy` for that since that clearly shows the intent. In some implementations, it may be faster (since you already know the length) to use `memcpy`, as they may allow for transferring the data in larger chunks, or in parallel. Or it may not :-) Optimisation mantra #1: "measure, don't guess".
In any case, should you decide to go that route, you would do something like:
```
char *strdup(const char *src) {
size_t len = strlen(src) + 1; // String plus '\0'
char *dst = malloc(len); // Allocate space
if (dst == NULL) return NULL; // No memory
memcpy (dst, src, len); // Copy the block
return dst; // Return the new string
}
```
|
252,800 |
<p>I have the need to display a nested set structure in HTML. I am doing it with the following partial:</p>
<pre><code><ul<%= ' id="tree"' if depth == 0 %>>
<% items.each do |item| %>
<li id="node_<%= item.id %>"><a><%= item.name %></a>
<% if item.has_children? %>
<%= render :partial => 'tree_level', :locals => {:items => item.children, :depth => depth + 1} %>
<% end %>
</li>
<% end %>
</ul>
</code></pre>
<p>Is this the best place to have the code? I "feel" like there should be a <code>to_html</code> method on the object which dumps the entire tree structure for me, though this works.</p>
|
[
{
"answer_id": 252829,
"author": "Jarek",
"author_id": 33013,
"author_profile": "https://Stackoverflow.com/users/33013",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure whether it is best practice but I used similar code for rendering project tree. </p>\n\n<p>Faster alternative is to create helper method doing the same job (recursively traversing tree and adding partial strings into result string). It is a little bit PHP style :( but for such a small amount of HTML is it OK, I guess :) </p>\n\n<p>Helper looks like:</p>\n\n<pre><code>def render_node(node)\n res = \"<ul>\"\n ...\n node.items.each {|n| res << render_node(n)}\n ...\n res << \"</ul>\"\n res\nend\n</code></pre>\n\n<p>Then it is used like this:</p>\n\n<pre><code><%=render_node ProjectTree.new%>\n</code></pre>\n"
},
{
"answer_id": 252876,
"author": "Jeroen Heijmans",
"author_id": 30748,
"author_profile": "https://Stackoverflow.com/users/30748",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you should realize there's a (small) overhead for using partials, so if performance is an issue, you may not want to use them this much. Otherwise I see little problem with using this. </p>\n\n<p>However, you might want to use the collection-variant of partials (see \"Rendering a collection of partials\" <a href=\"http://api.rubyonrails.org/classes/ActionView/Partials.html\" rel=\"nofollow noreferrer\">on this API page</a>, it could clean up your code a bit.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17453/"
] |
I have the need to display a nested set structure in HTML. I am doing it with the following partial:
```
<ul<%= ' id="tree"' if depth == 0 %>>
<% items.each do |item| %>
<li id="node_<%= item.id %>"><a><%= item.name %></a>
<% if item.has_children? %>
<%= render :partial => 'tree_level', :locals => {:items => item.children, :depth => depth + 1} %>
<% end %>
</li>
<% end %>
</ul>
```
Is this the best place to have the code? I "feel" like there should be a `to_html` method on the object which dumps the entire tree structure for me, though this works.
|
I am not sure whether it is best practice but I used similar code for rendering project tree.
Faster alternative is to create helper method doing the same job (recursively traversing tree and adding partial strings into result string). It is a little bit PHP style :( but for such a small amount of HTML is it OK, I guess :)
Helper looks like:
```
def render_node(node)
res = "<ul>"
...
node.items.each {|n| res << render_node(n)}
...
res << "</ul>"
res
end
```
Then it is used like this:
```
<%=render_node ProjectTree.new%>
```
|
252,811 |
<p>Does anyone know of a simple method for solving this?</p>
<p>I have a table which consists of start times for events and the associated durations. I need to be able to split the event durations into thirty minute intervals. So for example if an event starts at 10:45:00 and the duration is 00:17:00 then the returned set should allocate 15 minutes to the 10:30:00 interval and 00:02:00 minutes to the 11:00:00 interval.</p>
<p>I'm sure I can figure out a clumsy approach but would like something a little simpler. This must come up quite often I'd imagine but Google is being unhelpful today.</p>
<p>Thanks,</p>
<p>Steve</p>
|
[
{
"answer_id": 252854,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 2,
"selected": false,
"text": "<p>You could create a lookup table with just the times (over 24 hours), and join to that table. You would need to rebase the date to that used in the lookup. Then perform a datediff on the upper and lower intervals to work out their durations. Each middle interval would be 30 minutes.</p>\n\n<pre><code>create table #interval_lookup (\n from_date datetime,\n to_date datetime\n)\n\ndeclare @time datetime\nset @time = '00:00:00'\n\nwhile @time < '2 Jan 1900'\n begin\n insert into #interval_lookup values (@time, dateadd(minute, 30, @time))\n set @time = dateadd(minute, 30, @time)\n end\n\ndeclare @search_from datetime\ndeclare @search_to datetime\n\nset @search_from = '10:45:00'\nset @search_to = dateadd(minute, 17, @search_from) \n\nselect\n from_date as interval,\n case\n when from_date <= @search_from and \n @search_from < to_date and \n from_date <= @search_to and \n @search_to < to_date \n then datediff(minute, @search_from, @search_to)\n when from_date <= @search_from and \n @search_from < to_date \n then datediff(minute, @search_from, to_date)\n when from_date <= @search_to and \n @search_to < to_date then \n datediff(minute, from_date, @search_to)\n else 30\n end as duration\nfrom\n #interval_lookup\nwhere\n to_date > @search_from\n and from_date <= @search_to\n</code></pre>\n"
},
{
"answer_id": 252887,
"author": "Bartek Szabat",
"author_id": 23774,
"author_profile": "https://Stackoverflow.com/users/23774",
"pm_score": 2,
"selected": false,
"text": "<h2>Create TVF that splits single event:</h2>\n\n<pre><code>ALTER FUNCTION dbo.TVF_TimeRange_Split_To_Grid\n(\n @eventStartTime datetime\n , @eventDurationMins float\n , @intervalMins int\n)\nRETURNS @retTable table\n(\n intervalStartTime datetime\n ,intervalEndTime datetime\n ,eventDurationInIntervalMins float\n)\nAS\nBEGIN\n\n declare @eventMinuteOfDay int\n set @eventMinuteOfDay = datepart(hour,@eventStartTime)*60+datepart(minute,@eventStartTime)\n\n declare @intervalStartMinute int\n set @intervalStartMinute = @eventMinuteOfDay - @eventMinuteOfDay % @intervalMins\n\n declare @intervalStartTime datetime\n set @intervalStartTime = dateadd(minute,@intervalStartMinute,cast(floor(cast(@eventStartTime as float)) as datetime))\n\n declare @intervalEndTime datetime\n set @intervalEndTime = dateadd(minute,@intervalMins,@intervalStartTime)\n\n declare @eventDurationInIntervalMins float\n\n while (@eventDurationMins>0)\n begin\n\n set @eventDurationInIntervalMins = cast(@intervalEndTime-@eventStartTime as float)*24*60\n if @eventDurationMins<@eventDurationInIntervalMins \n set @eventDurationInIntervalMins = @eventDurationMins\n\n insert into @retTable\n select @intervalStartTime,@intervalEndTime,@eventDurationInIntervalMins\n\n set @eventDurationMins = @eventDurationMins - @eventDurationInIntervalMins\n set @eventStartTime = @intervalEndTime\n\n set @intervalStartTime = @intervalEndTime\n set @intervalEndTime = dateadd(minute,@intervalMins,@intervalEndTime)\n end\n\n RETURN \nEND\nGO\n</code></pre>\n\n<h2>Test:</h2>\n\n<pre><code>select getdate()\nselect * from dbo.TVF_TimeRange_Split_To_Grid(getdate(),23,30)\n</code></pre>\n\n<h2>Test Result:</h2>\n\n<pre><code>2008-10-31 11:28:12.377\n\nintervalStartTime intervalEndTime eventDurationInIntervalMins\n----------------------- ----------------------- ---------------------------\n2008-10-31 11:00:00.000 2008-10-31 11:30:00.000 1,79372222222222\n2008-10-31 11:30:00.000 2008-10-31 12:00:00.000 21,2062777777778\n</code></pre>\n\n<h2>Sample usage:</h2>\n\n<pre><code>select input.eventName, result.* from\n(\n select \n 'first' as eventName\n ,cast('2008-10-03 10:45' as datetime) as startTime\n ,17 as durationMins\n union all\n select \n 'second' as eventName\n ,cast('2008-10-05 11:00' as datetime) as startTime\n ,17 as durationMins\n union all\n select \n 'third' as eventName\n ,cast('2008-10-05 12:00' as datetime) as startTime\n ,100 as durationMins\n) input\ncross apply dbo.TVF_TimeRange_Split_To_Grid(input.startTime,input.durationMins,30) result\n</code></pre>\n\n<h2>Sample usage result:</h2>\n\n<pre><code>eventName intervalStartTime intervalEndTime eventDurationInIntervalMins\n--------- ----------------------- ----------------------- ---------------------------\nfirst 2008-10-03 10:30:00.000 2008-10-03 11:00:00.000 15\nfirst 2008-10-03 11:00:00.000 2008-10-03 11:30:00.000 2\nsecond 2008-10-05 11:00:00.000 2008-10-05 11:30:00.000 17\nthird 2008-10-05 12:00:00.000 2008-10-05 12:30:00.000 30\nthird 2008-10-05 12:30:00.000 2008-10-05 13:00:00.000 30\nthird 2008-10-05 13:00:00.000 2008-10-05 13:30:00.000 30\nthird 2008-10-05 13:30:00.000 2008-10-05 14:00:00.000 10\n\n(7 row(s) affected)\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Does anyone know of a simple method for solving this?
I have a table which consists of start times for events and the associated durations. I need to be able to split the event durations into thirty minute intervals. So for example if an event starts at 10:45:00 and the duration is 00:17:00 then the returned set should allocate 15 minutes to the 10:30:00 interval and 00:02:00 minutes to the 11:00:00 interval.
I'm sure I can figure out a clumsy approach but would like something a little simpler. This must come up quite often I'd imagine but Google is being unhelpful today.
Thanks,
Steve
|
You could create a lookup table with just the times (over 24 hours), and join to that table. You would need to rebase the date to that used in the lookup. Then perform a datediff on the upper and lower intervals to work out their durations. Each middle interval would be 30 minutes.
```
create table #interval_lookup (
from_date datetime,
to_date datetime
)
declare @time datetime
set @time = '00:00:00'
while @time < '2 Jan 1900'
begin
insert into #interval_lookup values (@time, dateadd(minute, 30, @time))
set @time = dateadd(minute, 30, @time)
end
declare @search_from datetime
declare @search_to datetime
set @search_from = '10:45:00'
set @search_to = dateadd(minute, 17, @search_from)
select
from_date as interval,
case
when from_date <= @search_from and
@search_from < to_date and
from_date <= @search_to and
@search_to < to_date
then datediff(minute, @search_from, @search_to)
when from_date <= @search_from and
@search_from < to_date
then datediff(minute, @search_from, to_date)
when from_date <= @search_to and
@search_to < to_date then
datediff(minute, from_date, @search_to)
else 30
end as duration
from
#interval_lookup
where
to_date > @search_from
and from_date <= @search_to
```
|
252,817 |
<p>Just out of curiosity:</p>
<p>I know I can tell the compiler if I want a value to be interpreted as a certain numeric type, e.g. as Integer (32 bit signed), this way appending an "I" (type character) to the constant value:</p>
<pre><code>Private Function GetTheAnswerAsInteger() As Integer
Return 42I
End Function
</code></pre>
<p>There's also "S" for Short, "D" for Decimal, etc.</p>
<p>But what is the <strong>suffix for Byte</strong>? Hint: it's not the obvious one "B"...</p>
|
[
{
"answer_id": 252826,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 2,
"selected": false,
"text": "<p>There's no byte literal in .NET.</p>\n"
},
{
"answer_id": 252831,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "<p>There isn't one. If you need to distinguish between an integer and a byte (e.g. to call an appropriate overload) for a constant, you need to cast.</p>\n\n<p>(The same is true in C#, by the way.)</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/e2ayt412.aspx\" rel=\"noreferrer\">MSDN provides confirmation:</a></p>\n\n<blockquote>\n <p>Byte has no literal type character or\n identifier type character.</p>\n</blockquote>\n\n<p>There's also a <a href=\"http://msdn.microsoft.com/en-us/library/s9cz43ek.aspx\" rel=\"noreferrer\">list of type characters and literal suffixes</a>.</p>\n"
},
{
"answer_id": 20710408,
"author": "Yuriy Galanter",
"author_id": 961695,
"author_profile": "https://Stackoverflow.com/users/961695",
"pm_score": 3,
"selected": false,
"text": "<p>This answer does not really provide a suffix, but it's as close as it gets.</p>\n\n<p>If you define an extension method as</p>\n\n<pre><code>Imports System.Runtime.CompilerServices\n\nModule IntegerExtensions\n\n <Extension()> _\n Public Function B(ByVal iNumber As Integer) As Byte\n Return Convert.ToByte(iNumber)\n End Function\n\nEnd Module\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>Private Function GetTheAnswerAsByte() As Byte\n\n Return 42.B\n\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 27761006,
"author": "Erti-Chris Eelmaa",
"author_id": 1936622,
"author_profile": "https://Stackoverflow.com/users/1936622",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>So, we added binary literals in VB last fall and got similar feedback\n from early testers. We did decide to add a suffix for byte for VB. We\n settled on SB (for signed byte) and UB (for unsigned byte). The reason\n it's not just B and SB is two-fold. </p>\n \n <p>One, the B suffix is ambiguous if you're writing in hexadecimal (what\n does 0xFFB mean?) and even if we had a solution for that, or another\n character than 'B' ('Y' was considered, F# uses this) no one could\n remember whether the default was signed or unsigned - .NET bytes are\n unsigned by default so it would make sense to pick B and SB but all\n the other suffixes are signed by default so it would be consistent\n with other type suffixes to pick B and UB. In the end we went for\n unambiguous SB and UB.\n -- Anthony D. Green,</p>\n</blockquote>\n\n<p><a href=\"https://roslyn.codeplex.com/discussions/542111\" rel=\"noreferrer\">https://roslyn.codeplex.com/discussions/542111</a></p>\n\n<p>It has been integrated to the upcoming VB.NET release, and this is the way it will work:</p>\n\n<pre><code>Public Const MyByte As Byte = 4UB;\nPublic Const MyByte2 As SByte = 4SB;\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6461/"
] |
Just out of curiosity:
I know I can tell the compiler if I want a value to be interpreted as a certain numeric type, e.g. as Integer (32 bit signed), this way appending an "I" (type character) to the constant value:
```
Private Function GetTheAnswerAsInteger() As Integer
Return 42I
End Function
```
There's also "S" for Short, "D" for Decimal, etc.
But what is the **suffix for Byte**? Hint: it's not the obvious one "B"...
|
There isn't one. If you need to distinguish between an integer and a byte (e.g. to call an appropriate overload) for a constant, you need to cast.
(The same is true in C#, by the way.)
[MSDN provides confirmation:](http://msdn.microsoft.com/en-us/library/e2ayt412.aspx)
>
> Byte has no literal type character or
> identifier type character.
>
>
>
There's also a [list of type characters and literal suffixes](http://msdn.microsoft.com/en-us/library/s9cz43ek.aspx).
|
252,819 |
<p>I have a library A, that I develop. When I deploy it on a machine, the corresponding <em>libA.so</em> and <em>libA-X.Y.Z.so</em> are put in /usr/lib (X.Y.Z being the version number). </p>
<p>Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "<em>ldd libB.so</em>" gives me : </p>
<pre><code>(...)
libA-X.Y.Z.so => /usr/lib/libA-X.Y.Z.so
(...)
</code></pre>
<p>My problem is that when I release a new version of A (X.Y.ZZ), I also have to release a new version of B. Otherwise, someone installing the latest A won't be able to install B which will be looking for the version X.Y.Z which doesn't exist.</p>
<p>How do I solve this problem ? How can I tell B to look for libA.so and not libA-X.Y.Z.so ? Or is it wrong to do so ? even unsafe ? </p>
<p><strong>Update 1</strong> : library A (that I inherited from someone else) uses autotools. </p>
<p><strong>Update 2</strong> : when I build library A, I can see : <em>"-Wl,-soname -Wl,libA-0.6.1.so"</em>. If I understand properly that means that we are forcing the soname to be <em>libA-0.6.1.so</em>. Is that right ? Now my problem is that I have no clue how to modify this behaviour in a project which uses autotools. I googled for a while but can't find any useful information. Should I modify configure.in or a Makefile.am ? </p>
|
[
{
"answer_id": 252841,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 0,
"selected": false,
"text": "<p>This also works in Windows as \"DLL hell\" :).</p>\n\n<p>If B needs a specific version of A and you would link to libA not libA-X.Y.Z then only substituting libA with newer version might cause B not to load or crash.</p>\n\n<p>But of course you can do a symlink from libA-X.Y.Z to libA-X1.Y1.Z1. If no APIs changed and only implementations than you should be safe.</p>\n"
},
{
"answer_id": 253009,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 4,
"selected": true,
"text": "<p>When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See</p>\n\n<p><a href=\"http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html\" rel=\"noreferrer\">http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html</a></p>\n"
},
{
"answer_id": 253682,
"author": "Barth",
"author_id": 20986,
"author_profile": "https://Stackoverflow.com/users/20986",
"pm_score": 0,
"selected": false,
"text": "<p>Answering to my second update : \nIn the Makefile.am of libA, I modified _la_LDFLAGS from <em>-release</em> to <em>-avoid-version</em>. This created a shared library without version number and I then recompiled libB which successfully linked against this unversioned shared library.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
I have a library A, that I develop. When I deploy it on a machine, the corresponding *libA.so* and *libA-X.Y.Z.so* are put in /usr/lib (X.Y.Z being the version number).
Now I develop a library B, which uses A. When I link B, I use the flag -lA. Then "*ldd libB.so*" gives me :
```
(...)
libA-X.Y.Z.so => /usr/lib/libA-X.Y.Z.so
(...)
```
My problem is that when I release a new version of A (X.Y.ZZ), I also have to release a new version of B. Otherwise, someone installing the latest A won't be able to install B which will be looking for the version X.Y.Z which doesn't exist.
How do I solve this problem ? How can I tell B to look for libA.so and not libA-X.Y.Z.so ? Or is it wrong to do so ? even unsafe ?
**Update 1** : library A (that I inherited from someone else) uses autotools.
**Update 2** : when I build library A, I can see : *"-Wl,-soname -Wl,libA-0.6.1.so"*. If I understand properly that means that we are forcing the soname to be *libA-0.6.1.so*. Is that right ? Now my problem is that I have no clue how to modify this behaviour in a project which uses autotools. I googled for a while but can't find any useful information. Should I modify configure.in or a Makefile.am ?
|
When you create libA.so, pass the -soname option to the linker (if you linking through gcc, use -Wl,-soname). Then, when B gets linked, the linker refers to A through its soname, not through its filename. On the target system, make sure you have a link from the soname to the real file. See
<http://www.linux.org/docs/ldp/howto/Program-Library-HOWTO/shared-libraries.html>
|
252,848 |
<p>I tried this step:</p>
<p>Select the menu options "Project > New Build Phase > New Run Script Build Phase", and enter the following script (don't forget to replace /Users/youruser/bin by the correct path to gen_entitlements.py) :</p>
<pre><code>export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
/Users/youruser/bin/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent";
codesign -f -s "iPhone developer" --resource-rules "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/ResourceRules.plist" \
--entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/"
fi
</code></pre>
<p>(from <a href="http://www.246tnt.com/iPhone/#xcode" rel="noreferrer">link</a>)</p>
<p>Now I want to remove this script from my project. How do I remove the "Run Script Build Phase" build phase from Xcode?</p>
|
[
{
"answer_id": 253283,
"author": "Jesús A. Álvarez",
"author_id": 13186,
"author_profile": "https://Stackoverflow.com/users/13186",
"pm_score": 5,
"selected": false,
"text": "<p>Select the Run Script phase in your target and delete it.</p>\n\n<p><img src=\"https://i.stack.imgur.com/pQ9uu.png\" alt=\"Delete\"></p>\n"
},
{
"answer_id": 13162664,
"author": "iOSAndroidWindowsMobileAppsDev",
"author_id": 1611779,
"author_profile": "https://Stackoverflow.com/users/1611779",
"pm_score": 3,
"selected": false,
"text": "<p>for xcode 4.5.1, the appearance is slightly different, click once on the run script phase and simultaneously press function + backspace (on a mac) to delete. When the dialog box pops up, click delete.<img src=\"https://i.stack.imgur.com/SufzM.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 48738485,
"author": "Lance Samaria",
"author_id": 4833705,
"author_profile": "https://Stackoverflow.com/users/4833705",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>In the Project Navigator go to the upper left hand corner and select the blue icon</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/PGLfm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PGLfm.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>In the top center of the screen select <code>Build Phases</code></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/BVCzX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BVCzX.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"3\">\n<li>When you see the <code>Run Script</code> that you want to delete look all the way on the right hand corner of it and you'll see an <code>X</code></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/0Wtqi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0Wtqi.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"4\">\n<li>Press the <code>X</code> and you'll see a menu appear asking if you want to delete it</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/IkSX6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IkSX6.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"5\">\n<li>Choose <code>Delete</code></li>\n</ol>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16066/"
] |
I tried this step:
Select the menu options "Project > New Build Phase > New Run Script Build Phase", and enter the following script (don't forget to replace /Users/youruser/bin by the correct path to gen\_entitlements.py) :
```
export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
/Users/youruser/bin/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent";
codesign -f -s "iPhone developer" --resource-rules "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/ResourceRules.plist" \
--entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/"
fi
```
(from [link](http://www.246tnt.com/iPhone/#xcode))
Now I want to remove this script from my project. How do I remove the "Run Script Build Phase" build phase from Xcode?
|
Select the Run Script phase in your target and delete it.

|
252,856 |
<pre><code>div#thing {
position: absolute;
top: 0px;
z-index: 2;
margin: 0 auto;
}
<div id="thing">
<p>text text text with no fixed size, variable font</p>
</div>
</code></pre>
<p>The div is at the top, but I can't center it with <code><center></code> or <code>margin: 0 auto</code>;</p>
|
[
{
"answer_id": 252872,
"author": "JacobE",
"author_id": 30056,
"author_profile": "https://Stackoverflow.com/users/30056",
"pm_score": 8,
"selected": true,
"text": "<p>Your problem may be solved if you give your <code>div</code> a fixed width, as follows:</p>\n\n<pre><code>div#thing {\n position: absolute;\n top: 0px;\n z-index: 2;\n width:400px;\n margin-left:-200px;\n left:50%;\n}\n</code></pre>\n"
},
{
"answer_id": 447113,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Yes:</p>\n\n<pre><code>div#thing { text-align:center; }\n</code></pre>\n"
},
{
"answer_id": 13806288,
"author": "Matheus Oliveira",
"author_id": 1892416,
"author_profile": "https://Stackoverflow.com/users/1892416",
"pm_score": 7,
"selected": false,
"text": "<pre><code>div#thing\n{\n position: absolute;\n width:400px;\n right: 0;\n left: 0;\n margin: auto;\n}\n</code></pre>\n"
},
{
"answer_id": 37922145,
"author": "dalvallana",
"author_id": 1371913,
"author_profile": "https://Stackoverflow.com/users/1371913",
"pm_score": -1,
"selected": false,
"text": "<p>If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:</p>\n\n<pre><code>div#wrapper {\n position: absolute;\n width: 100%;\n text-align: center;\n}\n</code></pre>\n\n<p>Remember that in order to position an element absolutely, the parent element must be positioned relatively.</p>\n"
},
{
"answer_id": 38314913,
"author": "Usman Shaukat",
"author_id": 1121145,
"author_profile": "https://Stackoverflow.com/users/1121145",
"pm_score": 0,
"selected": false,
"text": "<p>I was having the same issue, and my limitation was that i cannot have a predefined width. If your element does not have a fixed width, then try this</p>\n\n<pre><code>div#thing \n{ \n position: absolute; \n top: 0px; \n z-index: 2; \n left:0;\n right:0;\n }\n\ndiv#thing-body\n{\n text-align:center;\n}\n</code></pre>\n\n<p>then modify your html to look like this</p>\n\n<pre><code><div id=\"thing\">\n <div id=\"thing-child\">\n <p>text text text with no fixed size, variable font</p>\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 38973078,
"author": "Michael Giovanni Pumo",
"author_id": 695749,
"author_profile": "https://Stackoverflow.com/users/695749",
"pm_score": 5,
"selected": false,
"text": "<p>I know I'm late to the party, but I thought I would provide an answer here for people who need to horizontally position an absolute item, when you don't know its exact width.</p>\n\n<p>Try this:</p>\n\n<pre><code>// Horizontal example.\ndiv#thing {\n position: absolute;\n left: 50%;\n transform: translateX(-50%);\n}\n</code></pre>\n\n<p>The same technique can also be applied, for when you might need vertical alignment, simply by adjusting the properties like so:</p>\n\n<pre><code>// Vertical example.\ndiv#thing {\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n</code></pre>\n"
},
{
"answer_id": 56915604,
"author": "Armin",
"author_id": 9683034,
"author_profile": "https://Stackoverflow.com/users/9683034",
"pm_score": 3,
"selected": false,
"text": "<p>To center it both vertically and horizontally do this:</p>\n\n<pre><code>div#thing {\n position: absolute;\n left: 50%;\n top: 50%;\n transform: translate(-50%, -50%);\n}\n</code></pre>\n"
},
{
"answer_id": 58612513,
"author": "Aliaksei",
"author_id": 7605505,
"author_profile": "https://Stackoverflow.com/users/7605505",
"pm_score": 0,
"selected": false,
"text": "<p>Or you can use relative units, e.g.</p>\n\n<pre><code>#thing {\n position: absolute;\n width: 50vw;\n right: 25vw;\n}\n</code></pre>\n"
},
{
"answer_id": 61340445,
"author": "panwar",
"author_id": 5259876,
"author_profile": "https://Stackoverflow.com/users/5259876",
"pm_score": 1,
"selected": false,
"text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.contentBlock {\r\n width: {define width}\r\n width: 400px;\r\n position: absolute;\r\n left: 0;\r\n right: 0;\r\n margin-left: auto;\r\n margin-right: auto;\r\n \r\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
div#thing {
position: absolute;
top: 0px;
z-index: 2;
margin: 0 auto;
}
<div id="thing">
<p>text text text with no fixed size, variable font</p>
</div>
```
The div is at the top, but I can't center it with `<center>` or `margin: 0 auto`;
|
Your problem may be solved if you give your `div` a fixed width, as follows:
```
div#thing {
position: absolute;
top: 0px;
z-index: 2;
width:400px;
margin-left:-200px;
left:50%;
}
```
|
252,862 |
<p>I've two tables TAB_A and TAB_B. TAB_A is master table and TAB_B is child / transaction table. TAB_A is having COL_A (Primary key) and TAB_B is having COL_B (Primary key) and also COL_A.</p>
<p>For some business reason, Foreign key is not defined between TAB_A and TAB_B on column COL_A.</p>
<p>There are four records in TAB_B with some values say 1, 2, 3 and 4 in COL_A which has got no corresponding matching values in COL_A of TAB_A. (They are orphan records, created by mistake)</p>
<p>When I issue the following SELECT query, I get four records</p>
<pre><code>SELECT B.COL_B,
B.COL_A
FROM TAB_A A,
TAB_B B
WHERE A.COL_A = B.COL_A
AND B.COL_A IN (1, 2, 3, 4)
</code></pre>
<p>But if I start referring A.COL_A in the <code>SELECT</code> query, no records are returned.</p>
<pre><code>SELECT B.COL_B,
B.COL_A,
A.COL_A
FROM TAB_A A,
TAB_B B
WHERE A.COL_A = B.COL_A
AND B.COL_A IN (1, 2, 3, 4)
</code></pre>
<p>Can someone please explain this weird behavior?</p>
<p>DB2 Version 9.5 in AIX</p>
|
[
{
"answer_id": 252956,
"author": "Martin Bøgelund",
"author_id": 18968,
"author_profile": "https://Stackoverflow.com/users/18968",
"pm_score": 0,
"selected": false,
"text": "<p>You should use an ON clause instead of a WHERE clause in your inner join. The ON clause relates to the actual join, whereas WHERE typically is used for extra conditions not relating to the join.</p>\n\n<p><a href=\"http://publib.boulder.ibm.com/iseries/v5r2/ic2924/index.htm?info/sqlp/rbafymstinj.htm\" rel=\"nofollow noreferrer\">IBM says</a>:\n\"The join condition is specified after the ON keyword and determines how the two tables are to be compared to each other to produce the join result [...] Any additional conditions that do not relate to the actual join are specified in either the WHERE clause or as part of the actual join in the ON clause. \"</p>\n\n<p>You seem to be doing the opposite in your examples, having your join condition in a WHERE clause. AFAIK, this is not illegal, but it could explain this weird behaviour, when used with a SELECT clause that only references columns from one of the tables.</p>\n"
},
{
"answer_id": 253679,
"author": "Murthy",
"author_id": 17187,
"author_profile": "https://Stackoverflow.com/users/17187",
"pm_score": 0,
"selected": false,
"text": "<p>I looked at the documentation in IBM site. Though they talk about using \"JOIN\", there is also a mention of using direct join using \"WHERE\" conditions (which I used) and mentioned that they should produce same result.</p>\n\n<p>Also, I've previously worked in Oracle and SQL Server. The above syntax just worked fine. Still not sure why output differs, just because there is an additional column added in SELECT clause</p>\n"
},
{
"answer_id": 259847,
"author": "Kevin Beck",
"author_id": 24734,
"author_profile": "https://Stackoverflow.com/users/24734",
"pm_score": 1,
"selected": false,
"text": "<p>Both queries should return the same rows. If this really behaves as you describe, you have found a bug in DB2.</p>\n\n<p>What are you trying to accomplish with this query? If the values (1,2,3,4) of B.COL_A are orphan records, then this query should return no rows. If you meant to be searching for the orphans, you probably need to do some sort of outer join.</p>\n"
},
{
"answer_id": 22142351,
"author": "James Anderson",
"author_id": 38207,
"author_profile": "https://Stackoverflow.com/users/38207",
"pm_score": 0,
"selected": false,
"text": "<p>Your second SQL is effectively an \"INNER JOIN\".</p>\n\n<p>Since table B rows 1,2,3,4 are orphans then the condition A.COL_A = B.COL_A will never be true.</p>\n\n<p>You would need to code an explicit \"LEFT OUTER JOIN\" to get the rows back, but A.COL_A would always return NULL.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17187/"
] |
I've two tables TAB\_A and TAB\_B. TAB\_A is master table and TAB\_B is child / transaction table. TAB\_A is having COL\_A (Primary key) and TAB\_B is having COL\_B (Primary key) and also COL\_A.
For some business reason, Foreign key is not defined between TAB\_A and TAB\_B on column COL\_A.
There are four records in TAB\_B with some values say 1, 2, 3 and 4 in COL\_A which has got no corresponding matching values in COL\_A of TAB\_A. (They are orphan records, created by mistake)
When I issue the following SELECT query, I get four records
```
SELECT B.COL_B,
B.COL_A
FROM TAB_A A,
TAB_B B
WHERE A.COL_A = B.COL_A
AND B.COL_A IN (1, 2, 3, 4)
```
But if I start referring A.COL\_A in the `SELECT` query, no records are returned.
```
SELECT B.COL_B,
B.COL_A,
A.COL_A
FROM TAB_A A,
TAB_B B
WHERE A.COL_A = B.COL_A
AND B.COL_A IN (1, 2, 3, 4)
```
Can someone please explain this weird behavior?
DB2 Version 9.5 in AIX
|
Both queries should return the same rows. If this really behaves as you describe, you have found a bug in DB2.
What are you trying to accomplish with this query? If the values (1,2,3,4) of B.COL\_A are orphan records, then this query should return no rows. If you meant to be searching for the orphans, you probably need to do some sort of outer join.
|
252,882 |
<p>There are a couple of questions similar to this on stack overflow but not quite the same.</p>
<p>I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.</p>
<p>So far I started using the DirectoryEntry object with the <code>WinNT://</code> provider. This is going ok but I'm stuck on how to get a list of members of a group?</p>
<p>Anyone know how to do this? Or provide a better solution than using DirectoryEntry?</p>
|
[
{
"answer_id": 252890,
"author": "Tim Robinson",
"author_id": 32133,
"author_profile": "https://Stackoverflow.com/users/32133",
"pm_score": 1,
"selected": false,
"text": "<p>You should be able to find this information inside the <a href=\"http://msdn.microsoft.com/en-us/library/ms677097(VS.85).aspx\" rel=\"nofollow noreferrer\"><code>\"member\"</code> attribute</a> on the <code>DirectoryEntry</code> that represents the group.</p>\n"
},
{
"answer_id": 252892,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "<p>Microsoft .NET Framework provides a standard library for working with Active Directory: <strong><a href=\"http://msdn.microsoft.com/en-us/library/ms682458(VS.85).aspx\" rel=\"noreferrer\">System.DirectoryServices namespace</a></strong> in the System.DirectoryServices.dll.</p>\n\n<p>Microsoft recommends using two main classes from the System.DirectoryServices namespace: <strong>DirectoryEntry</strong> and <strong>DirectorySearcher</strong>. In most cases, it is enough to use DirectorySearcher class only.</p>\n\n<blockquote>\n <p><em>UPDATE: I tested it on my machine - it works. But maybe I've misunderstood\n your question.</em></p>\n</blockquote>\n\n<p>Here is an example from an excellent <a href=\"http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx\" rel=\"noreferrer\">CodeProject article</a>: </p>\n\n<h2>Get a list of users belonging to a particular AD group</h2>\n\n<pre><code>using System.DirectoryServices;\n\nArrayList GetADGroupUsers(string groupName)\n{ \n SearchResult result;\n DirectorySearcher search = new DirectorySearcher();\n search.Filter = String.Format(\"(cn={0})\", groupName);\n search.PropertiesToLoad.Add(\"member\");\n result = search.FindOne();\n\n ArrayList userNames = new ArrayList();\n if (result != null)\n {\n for (int counter = 0; counter < \n result.Properties[\"member\"].Count; counter++)\n {\n string user = (string)result.Properties[\"member\"][counter];\n userNames.Add(user);\n }\n }\n return userNames;\n}\n</code></pre>\n"
},
{
"answer_id": 313799,
"author": "Kepboy",
"author_id": 21429,
"author_profile": "https://Stackoverflow.com/users/21429",
"pm_score": 6,
"selected": true,
"text": "<p>Okay, it's taken a while, messing around with different solutions but the one that fits best with my original question is given below. I can't get the DirectoryEntry object to access the members of a local group using the 'standard' methods, the only way I could get it to enumerate the members was by using the Invoke method to call the native objects Members method.</p>\n\n<pre>\nusing(DirectoryEntry groupEntry = new DirectoryEntry(\"WinNT://./Administrators,group\"))\n{\n foreach(object member in (IEnumerable) groupEntry.Invoke(\"Members\"))\n {\n using(DirectoryEntry memberEntry = new DirectoryEntry(member))\n {\n Console.WriteLine(memberEntry.Path);\n }\n }\n}\n</pre>\n\n<p>I also used a similar technique to add and remove members from the local group.</p>\n\n<p>Hopefully this helps someone else as well.\nKeith.</p>\n\n<p><strong>EDIT</strong> by Tim: added VB.Net version</p>\n\n<pre><code>Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)\n Dim members As New List(Of DirectoryEntry)\n Try\n Using search As New DirectoryEntry(\"WinNT://./\" & GroupName & \",group\")\n For Each member As Object In DirectCast(search.Invoke(\"Members\"), IEnumerable)\n Dim memberEntry As New DirectoryEntry(member)\n members.Add(memberEntry)\n Next\n End Using\n Catch ex As Exception\n MessageBox.Show(ex.ToString)\n End Try\n Return members\nEnd Function\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21429/"
] |
There are a couple of questions similar to this on stack overflow but not quite the same.
I want to open, or create, a local group on a win xp computer and add members to it, domain, local and well known accounts. I also want to check whether a user is already a member so that I don't add the same account twice, and presumably get an exception.
So far I started using the DirectoryEntry object with the `WinNT://` provider. This is going ok but I'm stuck on how to get a list of members of a group?
Anyone know how to do this? Or provide a better solution than using DirectoryEntry?
|
Okay, it's taken a while, messing around with different solutions but the one that fits best with my original question is given below. I can't get the DirectoryEntry object to access the members of a local group using the 'standard' methods, the only way I could get it to enumerate the members was by using the Invoke method to call the native objects Members method.
```
using(DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
{
foreach(object member in (IEnumerable) groupEntry.Invoke("Members"))
{
using(DirectoryEntry memberEntry = new DirectoryEntry(member))
{
Console.WriteLine(memberEntry.Path);
}
}
}
```
I also used a similar technique to add and remove members from the local group.
Hopefully this helps someone else as well.
Keith.
**EDIT** by Tim: added VB.Net version
```
Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)
Dim members As New List(Of DirectoryEntry)
Try
Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group")
For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable)
Dim memberEntry As New DirectoryEntry(member)
members.Add(memberEntry)
Next
End Using
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return members
End Function
```
|
252,893 |
<p>How do you change the CLASSPATH of a Java process from within the Java process?</p>
<hr>
<p>Before you ask me "Why would you want to do that?" I'll explain it shortly. </p>
<blockquote>
<p>When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a <a href="http://clojure.org" rel="noreferrer">Clojure</a> source file, and I'd like to do it without having to restart Clojure itself (which is not really an option when using it on Slime on Emacs).</p>
</blockquote>
<p>That's the reason but I don't want this question tagged as some-weird-language some-weird-editor and be disregarded by the majority of Java developers that may have the answer.</p>
|
[
{
"answer_id": 252903,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>I don't believe you can - the right thing to do (I believe) is create a new classloader with the new path. Alternatively, you could write your own classloader which allows you to change the classpath (for that loader) dynamically.</p>\n"
},
{
"answer_id": 252964,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 1,
"selected": false,
"text": "<p>You may want to look into using <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/net/URLClassLoader.html\" rel=\"nofollow noreferrer\">java.net.URLClassLoader</a>. It allows you to programmatically load classes that weren't originally in your classpath, though I'm not sure if that's exactly what you need.</p>\n"
},
{
"answer_id": 252967,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": true,
"text": "<p>Update Q4 2017: as <a href=\"https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java/252967#comment82290481_252967\">commented</a> below by <a href=\"https://stackoverflow.com/users/1974520/vda8888\">vda8888</a>, in Java 9, the System <a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ClassLoader.html\" rel=\"noreferrer\"><code>java.lang.ClassLoader</code></a> is no longer a <a href=\"https://docs.oracle.com/javase/9/docs/api/java/net/URLClassLoader.html\" rel=\"noreferrer\"><code>java.net.URLClassLoader</code></a>.</p>\n\n<p>See \"<a href=\"https://blog.codefx.org/java/java-9-migration-guide/\" rel=\"noreferrer\">Java 9 Migration Guide: The Seven Most Common Challenges</a>\"</p>\n\n<blockquote>\n <p>The class loading strategy that I just described is implemented in a new type and in Java 9 the application class loader is of that type.<br>\n That means it is not a <code>URLClassLoader</code> anymore, so the occasional <code>(URLClassLoader) getClass().getClassLoader()</code> or <code>(URLClassLoader) ClassLoader.getSystemClassLoader()</code> sequences will no longer execute.</p>\n</blockquote>\n\n<p><a href=\"https://docs.oracle.com/javase/9/docs/api/java/lang/ModuleLayer.html\" rel=\"noreferrer\">java.lang.ModuleLayer</a> would be an alternative approach used in order to influence the <em>modulepath</em> (instead of the classpath). See for instance \"<a href=\"http://blog.joda.org/2017/04/java-9-modules-jpms-basics.html\" rel=\"noreferrer\">Java 9 modules - JPMS basics</a>\".</p>\n\n<hr>\n\n<p>For Java 8 or below:</p>\n\n<p>Some general comments:</p>\n\n<p>you cannot (in a portable way that's guaranteed to work, see below) change the system classpath. Instead, you need to define a new ClassLoader.</p>\n\n<p>ClassLoaders work in a hierarchical manner... so any class that makes a static reference to class X needs to be loaded in the same ClassLoader as X, or in a child ClassLoader. You can NOT use any custom ClassLoader to make code loaded by the system ClassLoader link properly, if it wouldn't have done so before. So you need to arrange for your main application code to be run in the custom ClassLoader in addition to the extra code that you locate.<br>\n(That being said, <a href=\"https://stackoverflow.com/users/188524/cracked-all\">cracked-all</a> mentions in the comments this example of <a href=\"http://snippets.dzone.com/posts/show/3574\" rel=\"noreferrer\">extending the <code>URLClassLoader</code></a>)</p>\n\n<p>And you might consider not writing your own ClassLoader, but just use URLClassLoader instead. Create a URLClassLoader with a url that are <em>not</em> in the parent classloaders url's.</p>\n\n<pre><code>URL[] url={new URL(\"file://foo\")};\nURLClassLoader loader = new URLClassLoader(url);\n</code></pre>\n\n<p>A <a href=\"http://robertmaldon.blogspot.com/2007/11/dynamically-add-to-eclipse-junit.html\" rel=\"noreferrer\">more complete solution</a> would be:</p>\n\n<pre><code>ClassLoader currentThreadClassLoader\n = Thread.currentThread().getContextClassLoader();\n\n// Add the conf dir to the classpath\n// Chain the current thread classloader\nURLClassLoader urlClassLoader\n = new URLClassLoader(new URL[]{new File(\"mtFile\").toURL()},\n currentThreadClassLoader);\n\n// Replace the thread classloader - assumes\n// you have permissions to do so\nThread.currentThread().setContextClassLoader(urlClassLoader);\n</code></pre>\n\n<p>If you assume the JVMs system classloader is a URLClassLoader (which may not be true for all JVMs), you can use reflection as well to actually modify the system classpath... (but that's a hack;)):</p>\n\n<pre><code>public void addURL(URL url) throws Exception {\n URLClassLoader classLoader\n = (URLClassLoader) ClassLoader.getSystemClassLoader();\n Class clazz= URLClassLoader.class;\n\n // Use reflection\n Method method= clazz.getDeclaredMethod(\"addURL\", new Class[] { URL.class });\n method.setAccessible(true);\n method.invoke(classLoader, new Object[] { url });\n}\n\naddURL(new File(\"conf\").toURL());\n\n// This should work now!\nThread.currentThread().getContextClassLoader().getResourceAsStream(\"context.xml\");\n</code></pre>\n"
},
{
"answer_id": 253059,
"author": "Henry B",
"author_id": 6414,
"author_profile": "https://Stackoverflow.com/users/6414",
"pm_score": 1,
"selected": false,
"text": "<p>It is possible as seen from the two links below, the method VonC gives seems to be the best but check out some of these posts and google for \"Java Dynamic Classpath\" or \"Java Dynamic Class Loading\" and find out some info from there.</p>\n\n<p>I'd post in more depth but VonC has pretty much done the job.</p>\n\n<p>From <a href=\"http://twit88.com/blog/2007/10/04/java-dynamic-loading-of-class-and-jar-file/\" rel=\"nofollow noreferrer\">Dynamic loading of class and Jar files</a>.</p>\n\n<p>Also check this <a href=\"http://forums.sun.com/thread.jspa?threadID=300557\" rel=\"nofollow noreferrer\">sun forum post</a>.</p>\n"
},
{
"answer_id": 6761503,
"author": "myfreeweb",
"author_id": 239140,
"author_profile": "https://Stackoverflow.com/users/239140",
"pm_score": 2,
"selected": false,
"text": "<p>There's no need to write your own class loader! There's <a href=\"http://code.google.com/p/clojure/source/browse/trunk/src/jvm/clojure/lang/DynamicClassLoader.java\" rel=\"nofollow\">clojure.lang.DynamicClassLoader</a>.</p>\n\n<p><a href=\"http://blog.japila.pl/2011/01/dynamically-redefining-classpath-in-clojure-repl/\" rel=\"nofollow\">http://blog.japila.pl/2011/01/dynamically-redefining-classpath-in-clojure-repl/</a></p>\n"
},
{
"answer_id": 19293096,
"author": "Akhi Youngisthan",
"author_id": 2834852,
"author_profile": "https://Stackoverflow.com/users/2834852",
"pm_score": -1,
"selected": false,
"text": "<pre><code>String s=\"java -classpath abcd/ \"+pgmname+\" \"+filename; \nProcess pro2 = Runtime.getRuntime().exec(s); \nBufferedReader in = new BufferedReader(new InputStreamReader(pro2.getInputStream()));\n</code></pre>\n\n<p>is an example of changin the classpath in java program</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
How do you change the CLASSPATH of a Java process from within the Java process?
---
Before you ask me "Why would you want to do that?" I'll explain it shortly.
>
> When you have a Clojure REPL running it is common to need more jars in your CLASSPATH to load a [Clojure](http://clojure.org) source file, and I'd like to do it without having to restart Clojure itself (which is not really an option when using it on Slime on Emacs).
>
>
>
That's the reason but I don't want this question tagged as some-weird-language some-weird-editor and be disregarded by the majority of Java developers that may have the answer.
|
Update Q4 2017: as [commented](https://stackoverflow.com/questions/252893/how-do-you-change-the-classpath-within-java/252967#comment82290481_252967) below by [vda8888](https://stackoverflow.com/users/1974520/vda8888), in Java 9, the System [`java.lang.ClassLoader`](https://docs.oracle.com/javase/9/docs/api/java/lang/ClassLoader.html) is no longer a [`java.net.URLClassLoader`](https://docs.oracle.com/javase/9/docs/api/java/net/URLClassLoader.html).
See "[Java 9 Migration Guide: The Seven Most Common Challenges](https://blog.codefx.org/java/java-9-migration-guide/)"
>
> The class loading strategy that I just described is implemented in a new type and in Java 9 the application class loader is of that type.
>
> That means it is not a `URLClassLoader` anymore, so the occasional `(URLClassLoader) getClass().getClassLoader()` or `(URLClassLoader) ClassLoader.getSystemClassLoader()` sequences will no longer execute.
>
>
>
[java.lang.ModuleLayer](https://docs.oracle.com/javase/9/docs/api/java/lang/ModuleLayer.html) would be an alternative approach used in order to influence the *modulepath* (instead of the classpath). See for instance "[Java 9 modules - JPMS basics](http://blog.joda.org/2017/04/java-9-modules-jpms-basics.html)".
---
For Java 8 or below:
Some general comments:
you cannot (in a portable way that's guaranteed to work, see below) change the system classpath. Instead, you need to define a new ClassLoader.
ClassLoaders work in a hierarchical manner... so any class that makes a static reference to class X needs to be loaded in the same ClassLoader as X, or in a child ClassLoader. You can NOT use any custom ClassLoader to make code loaded by the system ClassLoader link properly, if it wouldn't have done so before. So you need to arrange for your main application code to be run in the custom ClassLoader in addition to the extra code that you locate.
(That being said, [cracked-all](https://stackoverflow.com/users/188524/cracked-all) mentions in the comments this example of [extending the `URLClassLoader`](http://snippets.dzone.com/posts/show/3574))
And you might consider not writing your own ClassLoader, but just use URLClassLoader instead. Create a URLClassLoader with a url that are *not* in the parent classloaders url's.
```
URL[] url={new URL("file://foo")};
URLClassLoader loader = new URLClassLoader(url);
```
A [more complete solution](http://robertmaldon.blogspot.com/2007/11/dynamically-add-to-eclipse-junit.html) would be:
```
ClassLoader currentThreadClassLoader
= Thread.currentThread().getContextClassLoader();
// Add the conf dir to the classpath
// Chain the current thread classloader
URLClassLoader urlClassLoader
= new URLClassLoader(new URL[]{new File("mtFile").toURL()},
currentThreadClassLoader);
// Replace the thread classloader - assumes
// you have permissions to do so
Thread.currentThread().setContextClassLoader(urlClassLoader);
```
If you assume the JVMs system classloader is a URLClassLoader (which may not be true for all JVMs), you can use reflection as well to actually modify the system classpath... (but that's a hack;)):
```
public void addURL(URL url) throws Exception {
URLClassLoader classLoader
= (URLClassLoader) ClassLoader.getSystemClassLoader();
Class clazz= URLClassLoader.class;
// Use reflection
Method method= clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
method.setAccessible(true);
method.invoke(classLoader, new Object[] { url });
}
addURL(new File("conf").toURL());
// This should work now!
Thread.currentThread().getContextClassLoader().getResourceAsStream("context.xml");
```
|
252,897 |
<p>I am developing an application that needs to use regini (because of legacy reasons) to insert something into the registry. I have been trying to do this in such a way the the user of the application is not aware of this. I have written the following code:</p>
<pre><code>System.Diagnostics.ProcessStartInfo pi = new ProcessStartInfo();
pi.FileName = @"c:\windows\system32\regini.exe";
pi.Arguments = name;
pi.WorkingDirectory = Utils.AppSettings.WorkingDirectory.ToString();
pi.WindowStyle = ProcessWindowStyle.Hidden;
pi.RedirectStandardError = true;
pi.RedirectStandardOutput = true;
pi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = pi;
p.EnableRaisingEvents = true;
p.Start();
</code></pre>
<p>Unfortunately, I still see the 'command' window pop-up every time this code is executed. I was under the impression that </p>
<pre><code>pi.WindowStyle = ProcessWindowStyle.Hidden;
</code></pre>
<p>would prevent that. How can I prevent regini from opening its own command window? </p>
|
[
{
"answer_id": 252913,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 0,
"selected": false,
"text": "<p>I found this bug report on the Microsoft Connect Feedback Site: <a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95026\" rel=\"nofollow noreferrer\">System.Diagnostics.ProcessWindowStyle.Hidden shows window while executing</a></p>\n\n<p>Maybe there is a hint of something you forgot.</p>\n"
},
{
"answer_id": 253098,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": true,
"text": "<p>Try to add this line:</p>\n\n<pre><code>pi.CreateNoWindow = true;\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32522/"
] |
I am developing an application that needs to use regini (because of legacy reasons) to insert something into the registry. I have been trying to do this in such a way the the user of the application is not aware of this. I have written the following code:
```
System.Diagnostics.ProcessStartInfo pi = new ProcessStartInfo();
pi.FileName = @"c:\windows\system32\regini.exe";
pi.Arguments = name;
pi.WorkingDirectory = Utils.AppSettings.WorkingDirectory.ToString();
pi.WindowStyle = ProcessWindowStyle.Hidden;
pi.RedirectStandardError = true;
pi.RedirectStandardOutput = true;
pi.UseShellExecute = false;
Process p = new Process();
p.StartInfo = pi;
p.EnableRaisingEvents = true;
p.Start();
```
Unfortunately, I still see the 'command' window pop-up every time this code is executed. I was under the impression that
```
pi.WindowStyle = ProcessWindowStyle.Hidden;
```
would prevent that. How can I prevent regini from opening its own command window?
|
Try to add this line:
```
pi.CreateNoWindow = true;
```
|
252,906 |
<p>Anyone got an idea how to get from an Xserver the list of all open windows?</p>
|
[
{
"answer_id": 252911,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 8,
"selected": true,
"text": "<p>From the CLI you can use</p>\n\n<pre><code>xwininfo -tree -root\n</code></pre>\n\n<p>If you need to do this within your own code then you need to use the <code>XQueryTree</code> function from the <code>Xlib</code> library.</p>\n"
},
{
"answer_id": 1017932,
"author": "Marten",
"author_id": 125739,
"author_profile": "https://Stackoverflow.com/users/125739",
"pm_score": 4,
"selected": false,
"text": "<p>If your window manager implements EWMH specification, you can also take a look at the <code>_NET_CLIENT_LIST</code> value of the root window. This is set by most modern window managers:</p>\n\n<pre><code>xprop -root|grep ^_NET_CLIENT_LIST\n</code></pre>\n\n<p>That value can easily be obtained programmatically, see your Xlib documentation!</p>\n"
},
{
"answer_id": 61784442,
"author": "Christian Reall-Fluharty",
"author_id": 11411686,
"author_profile": "https://Stackoverflow.com/users/11411686",
"pm_score": 4,
"selected": false,
"text": "<p>Building off of <a href=\"https://stackoverflow.com/a/1017932/11411686\">Marten's answer</a>, (assuming your window manager supports <strong>E</strong>xtended <strong>W</strong>indow <strong>M</strong>anager <strong>H</strong>ints) you can feed that list of window ids back into <code>xprop</code> to get the <code>_NET_WM_NAME</code> property:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ xprop -root _NET_CLIENT_LIST |\n pcregrep -o1 '# (.*)' |\n sed 's/, /\\n/g' |\n xargs -I{} -n1 xprop -id {} _NET_WM_NAME\n</code></pre>\n\n<p>But at the command line, it would just be easier to use <code>wmctrl</code>:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ wmctrl -l\n</code></pre>\n\n<p>Programmatically, with <code>python-xlib</code>, you can do the same with:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\nfrom Xlib.display import Display\nfrom Xlib.X import AnyPropertyType\n\ndisplay = Display()\nroot = display.screen().root\n\n_NET_CLIENT_LIST = display.get_atom('_NET_CLIENT_LIST')\n_NET_WM_NAME = display.get_atom('_NET_WM_NAME')\n\nclient_list = root.get_full_property(\n _NET_CLIENT_LIST,\n property_type=AnyPropertyType,\n).value\n\nfor window_id in client_list:\n window = display.create_resource_object('window', window_id)\n window_name = window.get_full_property(\n _NET_WM_NAME,\n property_type=AnyPropertyType,\n ).value\n print(window_name)\n</code></pre>\n\n<p>Or, better yet, using the <code>EWMH</code> library:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\nfrom ewmh import EWMH\n\nwindow_manager_manager = EWMH()\nclient_list = window_manager_manager.getClientList()\n\nfor window in client_list:\n print(window_manager_manager.getWmName(window))\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
Anyone got an idea how to get from an Xserver the list of all open windows?
|
From the CLI you can use
```
xwininfo -tree -root
```
If you need to do this within your own code then you need to use the `XQueryTree` function from the `Xlib` library.
|
252,915 |
<p>How to send array in Httpservice in Adobe Flex3</p>
|
[
{
"answer_id": 435524,
"author": "bartv",
"author_id": 51371,
"author_profile": "https://Stackoverflow.com/users/51371",
"pm_score": 3,
"selected": false,
"text": "<p>I am not quite sure what you mean by sending an array to a httpservice. If you mean to send an array to a httpservice with the same field name, you can pass an array as field value.</p>\n\n<pre><code>var service:HTTPService = new HTTPService();\nservice.useProxy = true;\nservice.destination = \"myservicet\";\nservice.resultFormat = HTTPService.RESULT_FORMAT_XML;\n\nvar fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = new Object();\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field\"] = fields;\nservice.send(params);\n</code></pre>\n\n<p>The HTTPService will convert this to the url parameters:</p>\n\n<pre>facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0</pre>\n\n<p>Hope this helps!</p>\n\n<p>Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service</p>\n"
},
{
"answer_id": 447489,
"author": "Carlo",
"author_id": 55385,
"author_profile": "https://Stackoverflow.com/users/55385",
"pm_score": 0,
"selected": false,
"text": "<p>if it is a simple string array, you can <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html#join()\" rel=\"nofollow noreferrer\">join</a> it with a well know separator char, and on the other site, split the string with the same separator back to an array.</p>\n"
},
{
"answer_id": 1013842,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It really depends what is the back end technology you're using. If you're sending it to PHP you could try:</p>\n\n<pre><code>var fields:Array = [\"categories\", \"organisation\"];\nvar params:Object = {};\nparams.q = \"stackoverflow\";\nparams.rows = 0;\nparams.facet = \"true\";\nparams[\"facet.field[]\"] = fields;\nservice.send(params);\n</code></pre>\n\n<p>PHP will generate an array for you.\nAFAIR this works fine in Rails as well.</p>\n"
},
{
"answer_id": 1276866,
"author": "Sri",
"author_id": 156225,
"author_profile": "https://Stackoverflow.com/users/156225",
"pm_score": 0,
"selected": false,
"text": "<p>If it is a simple array, you could send it as a comma separated string. </p>\n\n<blockquote>\n <p>httpService.request = new Object;<br/>\n httpService.request.csv = array.toString();</p>\n</blockquote>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33016/"
] |
How to send array in Httpservice in Adobe Flex3
|
I am not quite sure what you mean by sending an array to a httpservice. If you mean to send an array to a httpservice with the same field name, you can pass an array as field value.
```
var service:HTTPService = new HTTPService();
service.useProxy = true;
service.destination = "myservicet";
service.resultFormat = HTTPService.RESULT_FORMAT_XML;
var fields:Array = ["categories", "organisation"];
var params:Object = new Object();
params.q = "stackoverflow";
params.rows = 0;
params.facet = "true";
params["facet.field"] = fields;
service.send(params);
```
The HTTPService will convert this to the url parameters:
```
facet=true&q=stackoverflow&facet%2Efield=categories&facet%2Efield=organisation&rows=0
```
Hope this helps!
Added for more clarity. When there is only 1 argument in the array, do not pass the fields as an array. For some reason, flex will not send this to the http service
|
252,921 |
<p>Magento shopping cart is built on the Zend Framework in PHP. This is the first time I've dealt with the Zend framework and I'm having the following difficulty...</p>
<p>I'm creating a custom module that will allow users to upload images whenever they purchase products. </p>
<p>I can overload the addAction() method whenever a user attempts to add a product to their cart. I can also create a custom module which presents the form to the user and accepts the file(s). However I'm not sure how to insert the code to run my module into my overloaded method:</p>
<pre><code><?php
require_once 'Mage/Checkout/controllers/CartController.php';
class Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController
{
# Overloaded addAction
public function addAction()
{
# when user tries to add to cart, request images from them
# *********
# *** what do i do in here to display a custom block ???? ###
# *** and allow addAction to continue only if successfully validated form input ###
# *********
parent::addAction();
}
}
</code></pre>
<p>I suspect my difficulties come from my lack of knowledge of the Zend MVC way of doing things. I've studied all the Magento documentation/wikis/forum threads from top to bottom.</p>
|
[
{
"answer_id": 253011,
"author": "Simon",
"author_id": 33036,
"author_profile": "https://Stackoverflow.com/users/33036",
"pm_score": 0,
"selected": false,
"text": "<p>I must admit upfront that I don't have production experience of Magento, but I have spent some time poking around their code.</p>\n\n<p>The block structure is defined in XML, and so you may not need to actually extend the Cart Controller.</p>\n\n<p>The Layout XML files can be found (on a default install) at app/design/frontend/default/default/layout. In here you will find checkout.xml which sets up the block structure for the checkout page.</p>\n"
},
{
"answer_id": 258573,
"author": "Simon",
"author_id": 33036,
"author_profile": "https://Stackoverflow.com/users/33036",
"pm_score": 2,
"selected": false,
"text": "<p>I thought I'd move to a new answer as I think I've managed to get it working.</p>\n\n<p>Here's what I did</p>\n\n<p>created the following files;</p>\n\n<p>app/code/local/Company/SpecialCheckout/controllers/Checkout/CartController.php</p>\n\n<p>app/code/local/Company/SpecialCheckout/etc/config.xml</p>\n\n<p>app/etc/modules/Company_SpecialCheckout.xml</p>\n\n<p>First the controller, which is exactly as you had;</p>\n\n<pre><code> <?PHP\nrequire_once 'Mage/Checkout/controllers/CartController.php';\nclass Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController {\n\n public function indexAction()\n {\n die('test');\n }\n}\n</code></pre>\n\n<p>Then the module configuration</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<config>\n <modules>\n <Company_SpecialCheckout>\n <version>0.1.0</version>\n </Company_SpecialCheckout>\n </modules>\n <global>\n <rewrite>\n <Company_SpecialCheckout_Checkout_Cart>\n <from><![CDATA[#^/checkout/cart#]]></from>\n <to>/SpecialCheckout/checkout_cart</to>\n </Company_SpecialCheckout_Checkout_Cart>\n </rewrite>\n </global>\n <frontend>\n <routers>\n <Company_SpecialCheckout>\n <use>standard</use>\n <args>\n <module>Company_SpecialCheckout</module>\n <frontName>SpecialCheckout</frontName>\n </args>\n </Company_SpecialCheckout>\n </routers>\n </frontend>\n</config>\n</code></pre>\n\n<p>and then finally the config file in app/etc/modules to make sure the module is picked up.</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<config>\n <modules>\n <Company_SpecialCheckout>\n <active>true</active>\n <codePool>local</codePool>\n </Company_SpecialCheckout>\n </modules>\n</config>\n</code></pre>\n\n<p>then when you go /checkout/cart you should see 'test'. This is based on details I found <a href=\"http://www.magentocommerce.com/wiki/how_to_overload_a_controller\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Make sure you have the cacheing of config files disabled in the Magento admin.</p>\n"
},
{
"answer_id": 881183,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>hey this option is given in newer version of magento 1.3.1 to upload the file from frontend\nenjoy</p>\n"
},
{
"answer_id": 3103497,
"author": "Ignacio Pascual",
"author_id": 374434,
"author_profile": "https://Stackoverflow.com/users/374434",
"pm_score": -1,
"selected": false,
"text": "<p>It was beeing a nightmare for me, I created a Tutorial in my blog:</p>\n\n<p>CONTROLLER / OVERRIDE / Frontend\n[...]\n\n \n \n #^/customer/account/#\n /mycustomer/account/\n \n \n \n[...]</p>\n\n<p>Check this out! <a href=\"http://www.unexpectedit.com/magento/magento-declare-override-controllers\" rel=\"nofollow noreferrer\">How to magento declare and override controllers</a></p>\n"
},
{
"answer_id": 4032741,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>For those who stuck on this i wrote the simplest way to solve this problem without overloading controllers. My variant based on onepage checkout <a href=\"http://www.magentocommerce.com/wiki/5_-_modules_and_development/checkout/customizing_onepage_checkout_-_remove_shipping_method?do=show\" rel=\"nofollow\">take a look in magento wiki</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17492/"
] |
Magento shopping cart is built on the Zend Framework in PHP. This is the first time I've dealt with the Zend framework and I'm having the following difficulty...
I'm creating a custom module that will allow users to upload images whenever they purchase products.
I can overload the addAction() method whenever a user attempts to add a product to their cart. I can also create a custom module which presents the form to the user and accepts the file(s). However I'm not sure how to insert the code to run my module into my overloaded method:
```
<?php
require_once 'Mage/Checkout/controllers/CartController.php';
class Company_SpecialCheckout_Checkout_CartController extends Mage_Checkout_CartController
{
# Overloaded addAction
public function addAction()
{
# when user tries to add to cart, request images from them
# *********
# *** what do i do in here to display a custom block ???? ###
# *** and allow addAction to continue only if successfully validated form input ###
# *********
parent::addAction();
}
}
```
I suspect my difficulties come from my lack of knowledge of the Zend MVC way of doing things. I've studied all the Magento documentation/wikis/forum threads from top to bottom.
|
hey this option is given in newer version of magento 1.3.1 to upload the file from frontend
enjoy
|
252,924 |
<p>This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.</p>
<p>Original string is <code>'original READ ONLY'</code></p>
<p>I want to replace the <code>'READ ONLY'</code> with <code>'READ WRITE'</code></p>
<p>Any quick answer please? Possibly with a javascript code snippet...</p>
|
[
{
"answer_id": 252928,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "<p>Good <a href=\"http://www.w3schools.com/jsref/jsref_replace.asp\" rel=\"noreferrer\">summary</a>. It is regexp based, if you use regexp notation you can specify the i and g modifiers (case insensitive (i), which will match regardless to case and global (g), which will replace all occurences), if you use string notation it'll get converted to a regex and you wont' be able to specify any modifier.</p>\n\n<pre><code><script type=\"text/javascript\">\n\nvar str1=\"Visit Microsoft!\";\nvar str2 = str1.replace(/microsoft/i, \"W3Schools\"); //Will work, per the i modifier \n\nvar str3 = \"original READ ONLY\";\nvar str4 = str3.replace(\"ONLY\", \"WRITE\"); //Will also work\n\n</script>\n</code></pre>\n"
},
{
"answer_id": 252930,
"author": "rogeriopvl",
"author_id": 28388,
"author_profile": "https://Stackoverflow.com/users/28388",
"pm_score": 2,
"selected": false,
"text": "<pre><code>stringObject.replace(findstring,newstring)\n</code></pre>\n"
},
{
"answer_id": 252939,
"author": "Andrew Bullock",
"author_id": 28543,
"author_profile": "https://Stackoverflow.com/users/28543",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer the regex approach,</p>\n\n<p>newstring = oldstring.replace(/regexforstringtoreplace/, 'new string');</p>\n\n<p>its also worth considering the g and i regex modifiers, these do a global replace (i.e. replaces all occurrences) and makes it case insensitive.</p>\n\n<p>for example:</p>\n\n<pre><code><script type=\"text/javascript\">\n\nvar str = \"this is a String\";\n\ndocument.write(str.replace(/\\s/g, \"_\"));\n\nwould print: this_is_a_string\n\ndocument.write(str.replace(/s/gi, \"f\"));\n\nwould print \"thif if a ftring\"\n\n</script>\n</code></pre>\n"
},
{
"answer_id": 253029,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 6,
"selected": true,
"text": "<p><code>String.replace()</code> is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the <strong>‘g’</strong> (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).</p>\n\n<p>An alternative <strong>non-regexp</strong> idiom for simple global string replace is:</p>\n\n<pre><code>function string_replace(haystack, find, sub) {\n return haystack.split(find).join(sub);\n}\n</code></pre>\n\n<p>This is preferable where the <code>find</code> string may contain characters that have an unwanted special meaning in regexps.</p>\n\n<p>Anyhow, either method is fine for the example in the question.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
This is a simple one. I want to replace a sub-string with another sub-string on client-side using Javascript.
Original string is `'original READ ONLY'`
I want to replace the `'READ ONLY'` with `'READ WRITE'`
Any quick answer please? Possibly with a javascript code snippet...
|
`String.replace()` is regexp-based; if you pass in a string as the first argument, the regexp made from it will not include the **‘g’** (global) flag. This option is essential if you want to replace all occurances of the search string (which is usually what you want).
An alternative **non-regexp** idiom for simple global string replace is:
```
function string_replace(haystack, find, sub) {
return haystack.split(find).join(sub);
}
```
This is preferable where the `find` string may contain characters that have an unwanted special meaning in regexps.
Anyhow, either method is fine for the example in the question.
|
252,945 |
<p>I am creating a plugin for Eclipse 3.4. I created a plug-in development project using the application with a view. Now I am trying to create a <code>TextViewer</code> the documentation says that it is located in <code>org.eclipse.jface.text.TextViewer</code>. But, this whole package is missing and eclipse cannot locate <code>TextViewer</code> class to import. I want to know why is this package/class missing? Also if it is really gone what took <code>TextViewer</code>'s place?</p>
|
[
{
"answer_id": 252982,
"author": "IAdapter",
"author_id": 30453,
"author_profile": "https://Stackoverflow.com/users/30453",
"pm_score": 1,
"selected": false,
"text": "<p>in 3.4 i have it inside</p>\n\n<p>eclipse-jee-ganymede-win32\\plugins\\org.eclipse.jface.text_3.4.0.v20080603-2000.jar</p>\n"
},
{
"answer_id": 253132,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Require-Bundle: org.eclipse.ui,\n org.eclipse.core.runtime,\n org.eclipse.jface.text\n</code></pre>\n\n<p>Add <em>org.eclipse.jface.text</em> as a dependency in your plugin manifest. You can use 3rd party tools (like IBM's <a href=\"https://www.alphaworks.ibm.com/tech/jarclassfinder/requirements\" rel=\"noreferrer\">JAR Class Finder</a>) to locate dependencies, or, alternatively, create a dummy plugin that imports everything from the target platform and use the Open Type dialog (CTRL+SHIFT+T).</p>\n\n<p>If you don't like the manual route, have a look at the <strong>Automated Management of Dependencies</strong> feature in the manifest editor, though care should be taken with this.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I am creating a plugin for Eclipse 3.4. I created a plug-in development project using the application with a view. Now I am trying to create a `TextViewer` the documentation says that it is located in `org.eclipse.jface.text.TextViewer`. But, this whole package is missing and eclipse cannot locate `TextViewer` class to import. I want to know why is this package/class missing? Also if it is really gone what took `TextViewer`'s place?
|
```
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
org.eclipse.jface.text
```
Add *org.eclipse.jface.text* as a dependency in your plugin manifest. You can use 3rd party tools (like IBM's [JAR Class Finder](https://www.alphaworks.ibm.com/tech/jarclassfinder/requirements)) to locate dependencies, or, alternatively, create a dummy plugin that imports everything from the target platform and use the Open Type dialog (CTRL+SHIFT+T).
If you don't like the manual route, have a look at the **Automated Management of Dependencies** feature in the manifest editor, though care should be taken with this.
|
252,962 |
<p>We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ? </p>
<p>We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)</p>
|
[
{
"answer_id": 252965,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use <code>scanf()</code>, tokenize your input separately and then use <code>strtoull()</code> or similar.</p>\n"
},
{
"answer_id": 252979,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>Alnitak recommends <code>strtoull()</code>, but it seems it's not <a href=\"http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/d69a6afe-6558-4913-afb0-616f00805229/\" rel=\"nofollow noreferrer\">available in Win32</a> environments. The linked-to forum thread recommends either of <code>_strtoui64()</code>, <code>_wcstoui64()</code> and <code>_tcstoui64()</code> as replacements. Perhaps this is \"on the edge\" of stuff that can't really be done with a single portable function call, and you might need to implement different code paths for different platforms. Or, I guess, write your own ASCII-to-64-bit converter, it's not rocket science.</p>\n"
},
{
"answer_id": 253053,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 2,
"selected": false,
"text": "<p>Or use the typesafety of istream...</p>\n\n<pre><code> using namespace std;\n\n // construct a number -- generate test data\n long long llOut = 0x1000000000000000;\n stringstream sout;\n // write the number\n sout << llOut;\n string snumber = sout.str();\n // construct an istream containing a number\n stringstream sin( snumber );\n\n // read the number -- the crucial bit\n long long llIn(0);\n sin >> llIn;\n</code></pre>\n"
},
{
"answer_id": 253062,
"author": "RobH",
"author_id": 25488,
"author_profile": "https://Stackoverflow.com/users/25488",
"pm_score": 2,
"selected": false,
"text": "<pre><code>std::fstream fstm( \"file.txt\" );\n__int64 foo;\nfstm >> foo;\n</code></pre>\n"
},
{
"answer_id": 253128,
"author": "KTC",
"author_id": 12868,
"author_profile": "https://Stackoverflow.com/users/12868",
"pm_score": 4,
"selected": true,
"text": "<p>GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its __int64 you can use.</p>\n\n<pre><code>#if (__cplusplus > 199711L) || defined(__GNUG__)\n typedef unsigned long long uint_64_t;\n#elif defined(_MSC_VER) || defined(__BORLANDC__) \n typedef unsigned __int64 uint_64_t;\n#else\n#error \"Please define uint_64_t\"\n#endif\n\nuint_64_t foo;\n\nstd::fstream fstm( \"file.txt\" );\nfstm >> foo;\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19734/"
] |
We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ?
We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)
|
GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its \_\_int64 you can use.
```
#if (__cplusplus > 199711L) || defined(__GNUG__)
typedef unsigned long long uint_64_t;
#elif defined(_MSC_VER) || defined(__BORLANDC__)
typedef unsigned __int64 uint_64_t;
#else
#error "Please define uint_64_t"
#endif
uint_64_t foo;
std::fstream fstm( "file.txt" );
fstm >> foo;
```
|
252,963 |
<p>How can I use Hyperlink button in gridview. I mean when I run my program,all data is displayed in gridview,but I want hyperlink in gridview, so that when I will click in hyperlink it will show the select path which is in gridview : if there is pdf file path and I just click on this hyper link then I can see the pdf file.</p>
<p>Can you tell me how can I do this? </p>
|
[
{
"answer_id": 252984,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 1,
"selected": false,
"text": "<p>You need to use a template field. e.g. lets say you're column is called 'PdfUrl'</p>\n\n<p>Then add a column to your datagrid. that looks like</p>\n\n<pre><code><asp:TemplateField HeaderText=\"Link\" SortExpression=\"PdfUrl\">\n <itemtemplate>\n <asp:HyperLink runat=\"server\" ID=\"hlkPDF\" NavigateURL='<%# DataBinder.Eval(Container.DataItem, \"PdfUrl\") %>' />\n </itemtemplate>\n</asp:TemplateField> \n</code></pre>\n"
},
{
"answer_id": 674300,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here is what i would do</p>\n\n<p>\n \n \n \n \n \n \n \n \"\n SelectCommand=\"SELECT * FROM [Customers]\"> </p>\n\n<p>Then for the test.aspx page i would have a datasource like this</p>\n\n<pre><code><asp:SqlDataSource ID=\"SqlDataSource1\" runat=\"server\" \n ConnectionString=\"<%$ ConnectionStrings:BlissConnectionString %>\" \n SelectCommand=\"SELECT * FROM [Customers] WHERE CustomerID = @ID\">\n <SelectParameters>\n <asp:QueryStringParameter Name=\"ID\" QueryStringField=\"ID\" />\n </SelectParameters>\n</asp:SqlDataSource>\n<br />\n<asp:DetailsView ID=\"DetailsView1\" runat=\"server\" AutoGenerateRows=\"False\" \n DataKeyNames=\"CustomerID\" DataSourceID=\"SqlDataSource1\" Height=\"50px\" \n Width=\"125px\">\n <Fields>\n <asp:BoundField DataField=\"CustomerID\" HeaderText=\"CustomerID\" \n InsertVisible=\"False\" ReadOnly=\"True\" SortExpression=\"CustomerID\" />\n <asp:BoundField DataField=\"CustomerName\" HeaderText=\"CustomerName\" \n SortExpression=\"CustomerName\" />\n <asp:BoundField DataField=\"CustomerAddress\" HeaderText=\"CustomerAddress\" \n SortExpression=\"CustomerAddress\" />\n <asp:BoundField DataField=\"CustomerPhone\" HeaderText=\"CustomerPhone\" \n SortExpression=\"CustomerPhone\" />\n <asp:BoundField DataField=\"CustomerEmail\" HeaderText=\"CustomerEmail\" \n SortExpression=\"CustomerEmail\" />\n </Fields>\n</asp:DetailsView>\n</code></pre>\n\n<p>Totally untested but hope this helps you.</p>\n\n<p>Regards</p>\n\n<p>Liam </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I use Hyperlink button in gridview. I mean when I run my program,all data is displayed in gridview,but I want hyperlink in gridview, so that when I will click in hyperlink it will show the select path which is in gridview : if there is pdf file path and I just click on this hyper link then I can see the pdf file.
Can you tell me how can I do this?
|
You need to use a template field. e.g. lets say you're column is called 'PdfUrl'
Then add a column to your datagrid. that looks like
```
<asp:TemplateField HeaderText="Link" SortExpression="PdfUrl">
<itemtemplate>
<asp:HyperLink runat="server" ID="hlkPDF" NavigateURL='<%# DataBinder.Eval(Container.DataItem, "PdfUrl") %>' />
</itemtemplate>
</asp:TemplateField>
```
|
252,972 |
<p>Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better?</p>
<p><strong>My situation is as follows:</strong><br>
I am working on a rewrite of a windows forms application that connects to a SQL 2008 (earlier it was SQL 2005) server. The application is an "expert-system" for an engineering company where we store structured data about constructions. We have control of all installations of the client software, we have no external customers or users, they are all internal to the company, and they are all be trusted not to do anything malicious to the software or database.</p>
<p>The current design doesn't have too many tables (about 10 - 20) but some of them have millions of records that belong to several hundred constructions. The systems performance has been ok so far, but it is starting to degrade as we are pushing the limits of the design. </p>
<p>As part of the rewrite I am considering splitting the database into one master database and several "child" databases where each describes one construction. Each child database should be of identical design. This should eliminate the performance problems we are seeing today since the data stored in each database would be less than one percent of the total data amount. </p>
<p>My concern is that instead of maintaining one database we will now get hundreds of databases that must be kept up to date. The system is constantly evolving as the companys requirements change (you know how it is), and while we try to look forward to reduce the number of changes the changes will come. So we will need a system where we keep track of all database changes done to the system so they can be applied to the child databases. Updating the client application won't be a problem, we have good control of that aspect.</p>
<p>I am thinking of a change tracing system where we store database scripts for all changes in a table in the master database. We can then give each change a version number and we can store a current version number in each child database. When the client program connects to a child database we can then check the version number of the database against the current version number of the master database and if there are patches with version numbers greater than the version number of the child database we run these and update the child database to the latest version. </p>
<p>As I see it this should work well. Any changes to the system will first be tested and validated before committed as a new version of the database. The change will then be applied to the database the first time a user opens it. I suppose we would open the database in exclusive mode while applying the changes, but as long as the changes aren't too frequent this should not be a problem.</p>
<p>So what do you think? Will this work? Have any of you done something similar? Should we scrap the solution and go for the monolithic system instead?</p>
|
[
{
"answer_id": 253024,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.</p>\n\n<p>This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).</p>\n\n<p>Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:</p>\n\n<pre><code>def change103(...):\n \"Create new table.\"\ndef change104(...):\n \"\"\"Transfer data from old table to new table and make\n complicated changes in the process.\n \"\"\"\ndef change105(...):\n \"Drop old table\"\ndef change106(...):\n \"Rename new table to old table\"\n</code></pre>\n\n<p>if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.</p>\n\n<p>But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.</p>\n"
},
{
"answer_id": 253322,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered <em>partitioning</em> your large tables by 'construction'? This could alleviate some of the growing pains by splitting the storage for the tables across files/physical devices without needing to change your application.</p>\n\n<p>Adding spindles (more drives) and performing a few hours of DBA work can often be cheaper than modifying/adapting software.</p>\n\n<p>Otherwise, I'd agree with @heikogerlach and these similar posts:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn\">How do I version my ms sql database</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1607/mechanisms-for-tracking-db-schema-changes\">Mechanisms for tracking DB schema changes</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/6371/how-do-you-manage-databases-in-development-test-and-production\">How do you manage databases in development, test and production?</a></p>\n"
},
{
"answer_id": 260017,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 1,
"selected": false,
"text": "<p>Better don't create additional databases. At first glance you may think that you'll get some performance gain, but actually you get support nightmare. Remember - what can break, does break sooner or later. </p>\n\n<p>It is way simpler to perform and optimize queries in single database. It is much easier manage user permissions in single database. It is much easier to make consistent backups for single database.</p>\n\n<p>Like KenG said, if you need break your large tables - consider partitioning them. And add some drives :)</p>\n\n<p>But at first run SQL profiler on your database and optimize indexes and queries. Several million rows is usually not a big problem to handle (unless your customer needs <em>live</em> totaling over half of these, in which case no partitioning can help).</p>\n"
},
{
"answer_id": 260193,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 1,
"selected": false,
"text": "<p>I know that this is a crazy answer but here it goes...</p>\n\n<p>I currently have a similar scenario where I need to keep control of database versions in multiple locations for a system using MS SQL Server.</p>\n\n<p>What I am doing now is using Ruby on Rails ActiveRecord Migrations to keep control of database versions. Yes I know that we are talking about Windows systems but this works fine for me. (By the way, my system is programmed in VB and .NET)</p>\n\n<p>I have installed Rails on each server, when I need to update the database schema I copy the migration files to the server and run rake db:migrate which updates the database to the latest version or rollbacks it to a desired version.</p>\n\n<p>As a side effect you will have a set of migration files for your database schema in an database independent language (in this case ruby) that you can apply to other database engines and that you can put under source control too.</p>\n\n<p>I know that this is a strange solution in which a totally different technology is used but it does not hurt to learn new approaches. You can find additional information <a href=\"http://guides.rails.info/migrations.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I have become a better .Net programmer since I learned Ruby on Rails. I asked here before a <a href=\"https://stackoverflow.com/questions/190160/how-do-i-create-the-migrations-for-a-legacy-database\">question</a> about this approach.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30366/"
] |
Please forgive my long question. I have an idea for a design that I could use some comments on. Is it a good idea to do this? And what are the pit falls I should be aware of? Are there other similar implementations that are better?
**My situation is as follows:**
I am working on a rewrite of a windows forms application that connects to a SQL 2008 (earlier it was SQL 2005) server. The application is an "expert-system" for an engineering company where we store structured data about constructions. We have control of all installations of the client software, we have no external customers or users, they are all internal to the company, and they are all be trusted not to do anything malicious to the software or database.
The current design doesn't have too many tables (about 10 - 20) but some of them have millions of records that belong to several hundred constructions. The systems performance has been ok so far, but it is starting to degrade as we are pushing the limits of the design.
As part of the rewrite I am considering splitting the database into one master database and several "child" databases where each describes one construction. Each child database should be of identical design. This should eliminate the performance problems we are seeing today since the data stored in each database would be less than one percent of the total data amount.
My concern is that instead of maintaining one database we will now get hundreds of databases that must be kept up to date. The system is constantly evolving as the companys requirements change (you know how it is), and while we try to look forward to reduce the number of changes the changes will come. So we will need a system where we keep track of all database changes done to the system so they can be applied to the child databases. Updating the client application won't be a problem, we have good control of that aspect.
I am thinking of a change tracing system where we store database scripts for all changes in a table in the master database. We can then give each change a version number and we can store a current version number in each child database. When the client program connects to a child database we can then check the version number of the database against the current version number of the master database and if there are patches with version numbers greater than the version number of the child database we run these and update the child database to the latest version.
As I see it this should work well. Any changes to the system will first be tested and validated before committed as a new version of the database. The change will then be applied to the database the first time a user opens it. I suppose we would open the database in exclusive mode while applying the changes, but as long as the changes aren't too frequent this should not be a problem.
So what do you think? Will this work? Have any of you done something similar? Should we scrap the solution and go for the monolithic system instead?
|
I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.
This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).
Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:
```
def change103(...):
"Create new table."
def change104(...):
"""Transfer data from old table to new table and make
complicated changes in the process.
"""
def change105(...):
"Drop old table"
def change106(...):
"Rename new table to old table"
```
if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.
But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.
|
252,974 |
<p>I would like to hear some opinions about using the isolated storage in Silverlight for storing sensitive data. For example, is it OK to store an authentication token (some GUID that identifies a server-side session) in this storage, or is it better to use cookies?</p>
<p>The isolated storage gives an advantage over cookies in that it is shared across browsers, but it might be more difficult to handle expiry, and there might be some other issues (security?) that I am not aware of.</p>
<p>So... what are your opinions? Or do you know any great articles about the topic?</p>
<p>Thanks, Jacob</p>
|
[
{
"answer_id": 253024,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.</p>\n\n<p>This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).</p>\n\n<p>Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:</p>\n\n<pre><code>def change103(...):\n \"Create new table.\"\ndef change104(...):\n \"\"\"Transfer data from old table to new table and make\n complicated changes in the process.\n \"\"\"\ndef change105(...):\n \"Drop old table\"\ndef change106(...):\n \"Rename new table to old table\"\n</code></pre>\n\n<p>if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.</p>\n\n<p>But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.</p>\n"
},
{
"answer_id": 253322,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered <em>partitioning</em> your large tables by 'construction'? This could alleviate some of the growing pains by splitting the storage for the tables across files/physical devices without needing to change your application.</p>\n\n<p>Adding spindles (more drives) and performing a few hours of DBA work can often be cheaper than modifying/adapting software.</p>\n\n<p>Otherwise, I'd agree with @heikogerlach and these similar posts:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/173/how-do-i-version-my-ms-sql-database-in-svn\">How do I version my ms sql database</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/1607/mechanisms-for-tracking-db-schema-changes\">Mechanisms for tracking DB schema changes</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/6371/how-do-you-manage-databases-in-development-test-and-production\">How do you manage databases in development, test and production?</a></p>\n"
},
{
"answer_id": 260017,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 1,
"selected": false,
"text": "<p>Better don't create additional databases. At first glance you may think that you'll get some performance gain, but actually you get support nightmare. Remember - what can break, does break sooner or later. </p>\n\n<p>It is way simpler to perform and optimize queries in single database. It is much easier manage user permissions in single database. It is much easier to make consistent backups for single database.</p>\n\n<p>Like KenG said, if you need break your large tables - consider partitioning them. And add some drives :)</p>\n\n<p>But at first run SQL profiler on your database and optimize indexes and queries. Several million rows is usually not a big problem to handle (unless your customer needs <em>live</em> totaling over half of these, in which case no partitioning can help).</p>\n"
},
{
"answer_id": 260193,
"author": "hectorsq",
"author_id": 14755,
"author_profile": "https://Stackoverflow.com/users/14755",
"pm_score": 1,
"selected": false,
"text": "<p>I know that this is a crazy answer but here it goes...</p>\n\n<p>I currently have a similar scenario where I need to keep control of database versions in multiple locations for a system using MS SQL Server.</p>\n\n<p>What I am doing now is using Ruby on Rails ActiveRecord Migrations to keep control of database versions. Yes I know that we are talking about Windows systems but this works fine for me. (By the way, my system is programmed in VB and .NET)</p>\n\n<p>I have installed Rails on each server, when I need to update the database schema I copy the migration files to the server and run rake db:migrate which updates the database to the latest version or rollbacks it to a desired version.</p>\n\n<p>As a side effect you will have a set of migration files for your database schema in an database independent language (in this case ruby) that you can apply to other database engines and that you can put under source control too.</p>\n\n<p>I know that this is a strange solution in which a totally different technology is used but it does not hurt to learn new approaches. You can find additional information <a href=\"http://guides.rails.info/migrations.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I have become a better .Net programmer since I learned Ruby on Rails. I asked here before a <a href=\"https://stackoverflow.com/questions/190160/how-do-i-create-the-migrations-for-a-legacy-database\">question</a> about this approach.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30056/"
] |
I would like to hear some opinions about using the isolated storage in Silverlight for storing sensitive data. For example, is it OK to store an authentication token (some GUID that identifies a server-side session) in this storage, or is it better to use cookies?
The isolated storage gives an advantage over cookies in that it is shared across browsers, but it might be more difficult to handle expiry, and there might be some other issues (security?) that I am not aware of.
So... what are your opinions? Or do you know any great articles about the topic?
Thanks, Jacob
|
I have a similar situation here, though I use MySQL. Every database has a versions table that contains the version (simply an integer) and a short comment of what has changed in this version. I use a script to update the databases. Every database change can be in one function or sometimes one change is made by multiple functions. Functions contain the version number in the function name. The script looks up the highest version number in a database and applies only the functions that have a higher version number in order.
This makes it easy to update databases (just add new change functions) and allows me to quickly upgrade a recovered database if necessary (just run the script again).
Even when testing the changes before this allows for defensive changes. If you make some heavy changes on a table and you want to play it safe:
```
def change103(...):
"Create new table."
def change104(...):
"""Transfer data from old table to new table and make
complicated changes in the process.
"""
def change105(...):
"Drop old table"
def change106(...):
"Rename new table to old table"
```
if in change104() is something going wrong (and throws an exception) you can simply delete the already converted data from the new table, fix your change function and run the script again.
But I don't think that changing a database dynamically when a client connects is a good idea. Sometimes changes can take some time. And the software that accesses a database should match the schema of the database. You have somehow to keep them in sync. Maybe you could distribute a new software version and then you want to upgrade the database when a client is actually starting to use this new software. But I haven't tried that.
|
252,976 |
<p>How can I create a query for a full outer join across a M2M relationchip using the django QuerySet API?</p>
<p>It that is not supported, some hint about creating my own manager to do this would be welcome.</p>
<p><strong>Edited to add:</strong>
@S.Lott:
Thanks for the enlightenment.
The need for the OUTER JOIN comes from the application. It has to generate a report showing the data entered, even if it still incomplete.
I was not aware of the fact that the result would be a new class/model. Your hints will help me quite a bit.</p>
|
[
{
"answer_id": 253057,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 5,
"selected": true,
"text": "<p>Django doesn't support \"joins\" in the usual SQL sense -- it supports object navigation.</p>\n\n<p>Note that a relational join (inner or outer) creates a new \"class\" of entities. One that doesn't have a definition in Django. So there's no proper \"result set\" since there's no class definition for the things you get back. The best you can do is define a tuple which will be packed with None's for missing combinations.</p>\n\n<p>A left (or right) outer join looks like this. It creates two disjoint subsets, those who have an associated set of related entities, and those who don't.</p>\n\n<pre><code>for obj in Model1.objects.all():\n if obj.model2_set().count() == 0:\n # process (obj, None) -- no Model2 association\n else:\n for obj2 in obj.model2_set.all():\n # process (obj, obj2) -- the \"inner join\" result\n</code></pre>\n\n<p>A \"Full\" outer join is a union of the remaining items that have no relationships.</p>\n\n<pre><code>for obj2 in Model2.objects.all():\n if obj2.model1_set().count() == 0:\n # process (None, obj2) -- no Model1 association\n</code></pre>\n\n<p>The issue is always, what processing are you doing with this weird collection of three different subsets of objects? </p>\n\n<p>The point of an object database is to focus the processing on the object and it's associated objects. </p>\n\n<p>The peculiar collection called a \"relational join\" is never in the original object model. It's a new class of objects built from two (or more) original objects. </p>\n\n<p>Worse, outer joins create a collection with multiple subclasses (inner join, left outer join and right outer join). What does that collection of things <strong>mean</strong>?</p>\n\n<p>Wait, it can get worse. If the processing includes checks for the missing attributes (i.e. <code>if someObj.anObj2attribute is None</code>: we're essentially looking for <code>Model1</code> items with no <code>Model2</code> object associated. Ummm... why did we put those in the outer join, only to filter them using an <code>if</code> statement? Why not just do separate queries amd process each subset properly?</p>\n\n<hr>\n\n<p>Edit: When you're showing \"incomplete\" status, it isn't an outer-join at all. It's much simpler. You need to create one (or two) separate collections in your view function for your template to display.</p>\n\n<p>First, you should use status codes, not the presence or absence of a foreign key. Optional foreign keys don't have \"reasons\" -- they're either there or not there. A status code can provide useful shades of meaning (\"incomplete\", \"in error\", \"broken\", \"not applicable\", \"to be deleted\", etc.)</p>\n\n<pre><code>errorList1 = Model1.objects.filter( status=\"Incomplete\" )\nerrorList2 = Model2.objects.filter( status=\"Incomplete\" )\n</code></pre>\n\n<p>These two are the two non-join parts of a full outer join. You can then display these two error lists in your template with appropriate column titles and status codes and everything.</p>\n\n<p>You can even put them into a single table to mimic the old full outer join report people used to see</p>\n\n<pre><code><table>\n <tr><th>Model1</th><th>Model2</th></tr>\n {% for e1 in errorList1 %}\n <tr><td>e1</td><td>NULL</td></tr>\n {% endfor %}\n {% for e2 in errorList2 %}\n <tr><td>NULL</td><td>e2</td></tr>\n {% endfor %}\n</table>\n</code></pre>\n\n<p>Looks like a full outer join report. Without the full outer join.</p>\n"
},
{
"answer_id": 2429866,
"author": "tobias.mcnulty",
"author_id": 166053,
"author_profile": "https://Stackoverflow.com/users/166053",
"pm_score": 1,
"selected": false,
"text": "<p>Colin, one of the guys I work with, wrote a post awhile back about doing custom joins in Django:</p>\n\n<p><a href=\"http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/\" rel=\"nofollow noreferrer\">http://www.caktusgroup.com/blog/2009/09/28/custom-joins-with-djangos-queryjoin/</a></p>\n\n<p>You might be able to find something useful there!</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11527/"
] |
How can I create a query for a full outer join across a M2M relationchip using the django QuerySet API?
It that is not supported, some hint about creating my own manager to do this would be welcome.
**Edited to add:**
@S.Lott:
Thanks for the enlightenment.
The need for the OUTER JOIN comes from the application. It has to generate a report showing the data entered, even if it still incomplete.
I was not aware of the fact that the result would be a new class/model. Your hints will help me quite a bit.
|
Django doesn't support "joins" in the usual SQL sense -- it supports object navigation.
Note that a relational join (inner or outer) creates a new "class" of entities. One that doesn't have a definition in Django. So there's no proper "result set" since there's no class definition for the things you get back. The best you can do is define a tuple which will be packed with None's for missing combinations.
A left (or right) outer join looks like this. It creates two disjoint subsets, those who have an associated set of related entities, and those who don't.
```
for obj in Model1.objects.all():
if obj.model2_set().count() == 0:
# process (obj, None) -- no Model2 association
else:
for obj2 in obj.model2_set.all():
# process (obj, obj2) -- the "inner join" result
```
A "Full" outer join is a union of the remaining items that have no relationships.
```
for obj2 in Model2.objects.all():
if obj2.model1_set().count() == 0:
# process (None, obj2) -- no Model1 association
```
The issue is always, what processing are you doing with this weird collection of three different subsets of objects?
The point of an object database is to focus the processing on the object and it's associated objects.
The peculiar collection called a "relational join" is never in the original object model. It's a new class of objects built from two (or more) original objects.
Worse, outer joins create a collection with multiple subclasses (inner join, left outer join and right outer join). What does that collection of things **mean**?
Wait, it can get worse. If the processing includes checks for the missing attributes (i.e. `if someObj.anObj2attribute is None`: we're essentially looking for `Model1` items with no `Model2` object associated. Ummm... why did we put those in the outer join, only to filter them using an `if` statement? Why not just do separate queries amd process each subset properly?
---
Edit: When you're showing "incomplete" status, it isn't an outer-join at all. It's much simpler. You need to create one (or two) separate collections in your view function for your template to display.
First, you should use status codes, not the presence or absence of a foreign key. Optional foreign keys don't have "reasons" -- they're either there or not there. A status code can provide useful shades of meaning ("incomplete", "in error", "broken", "not applicable", "to be deleted", etc.)
```
errorList1 = Model1.objects.filter( status="Incomplete" )
errorList2 = Model2.objects.filter( status="Incomplete" )
```
These two are the two non-join parts of a full outer join. You can then display these two error lists in your template with appropriate column titles and status codes and everything.
You can even put them into a single table to mimic the old full outer join report people used to see
```
<table>
<tr><th>Model1</th><th>Model2</th></tr>
{% for e1 in errorList1 %}
<tr><td>e1</td><td>NULL</td></tr>
{% endfor %}
{% for e2 in errorList2 %}
<tr><td>NULL</td><td>e2</td></tr>
{% endfor %}
</table>
```
Looks like a full outer join report. Without the full outer join.
|
252,988 |
<p>How to get all the database names and corresponding table names together ?</p>
|
[
{
"answer_id": 253003,
"author": "Hapkido",
"author_id": 27646,
"author_profile": "https://Stackoverflow.com/users/27646",
"pm_score": 0,
"selected": false,
"text": "<p>You will have to write a store procedure.</p>\n\n<p>First get the database name</p>\n\n<pre><code>SELECT Name FROM master.sys.databases\n</code></pre>\n\n<p>For each database</p>\n\n<pre><code>SELECT %DatabaseName%, Name FROM %DatabaseName%.SysObjects WHERE type = 'U'\n</code></pre>\n\n<p>Edit here's the store procedure</p>\n\n<pre><code>CREATE PROCEDURE sp_GetDatabasesTables \nAS\nBEGIN\n-- SET NOCOUNT ON added to prevent extra result sets from\n-- interfering with SELECT statements.\nSET NOCOUNT ON;\nCREATE TABLE #schema ( DatabaseName VarChar(50), TableName VarChar(50) );\nDECLARE @DatabaseName varchar(50);\nDECLARE cursorDatabase CURSOR FOR\n SELECT Name FROM master.sys.databases WHERE Name NOT IN ('tempdb'); -- add any table you want to filter here\n\nOPEN cursorDatabase;\n\n-- Perform the first fetch.\nFETCH NEXT FROM cursorDatabase INTO @DatabaseName;\n\n-- Check @@FETCH_STATUS to see if there are any more rows to fetch.\nWHILE @@FETCH_STATUS = 0\nBEGIN\n EXEC ('INSERT INTO #schema (DatabaseName, TableName) SELECT ''' + @DatabaseName + ''' AS DatabaseName, Name As TableName FROM ' + @DatabaseName + '.sys.SysObjects WHERE type = ''U'';');\n FETCH NEXT FROM cursorDatabase INTO @DatabaseName;\nEND\n\nCLOSE cursorDatabase;\nDEALLOCATE cursorDatabase;\nSELECT * FROM #schema\nEND\n</code></pre>\n"
},
{
"answer_id": 253042,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 1,
"selected": false,
"text": "<pre><code>CREATE TABLE #dbs ( DatabaseName VARCHAR(256), TableName VARCHAR(256) )\n\nEXEC sp_msforeachdb 'INSERT INTO #dbs\n SELECT ''?'', [name] FROM dbo.SysObjects WHERE XType = ''U'''\n\nSELECT * FROM #dbs\nDROP TABLE #dbs\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/252988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How to get all the database names and corresponding table names together ?
|
```
CREATE TABLE #dbs ( DatabaseName VARCHAR(256), TableName VARCHAR(256) )
EXEC sp_msforeachdb 'INSERT INTO #dbs
SELECT ''?'', [name] FROM dbo.SysObjects WHERE XType = ''U'''
SELECT * FROM #dbs
DROP TABLE #dbs
```
|
253,013 |
<p>We use a simple object model for our low level networking code at work where struct pointers are passed around to functions which are pretending to be methods. I've inherited most of this code which was written by consultants with passable C/C++ experience at best and I've spent many late nights trying to refactor code into something that would resemble a reasonable structure.</p>
<p>Now I would like to bring the code under unit testing but considering the object model we have chosen I have no idea how to mock objects. See the example below:</p>
<p>Sample header (foo.h):</p>
<pre><code>#ifndef FOO_H_
#define FOO_H_
typedef struct Foo_s* Foo;
Foo foo_create(TcpSocket tcp_socket);
void foo_destroy(Foo foo);
int foo_transmit_command(Foo foo, enum Command command);
#endif /* FOO_H_ */
</code></pre>
<p>Sample source (foo.c):</p>
<pre><code>struct Foo_s {
TcpSocket tcp_socket;
};
Foo foo_create(TcpSocket tcp_socket)
{
Foo foo = NULL;
assert(tcp_socket != NULL);
foo = malloc(sizeof(struct Foo_s));
if (foo == NULL) {
goto fail;
}
memset(foo, 0UL, sizeof(struct Foo_s));
foo->tcp_socket = tcp_socket;
return foo;
fail:
foo_destroy(foo);
return NULL;
}
void foo_destroy(Foo foo)
{
if (foo != NULL) {
tcp_socket_destroy(foo->tcp_socket);
memset(foo, 0UL, sizeof(struct Foo_s));
free(foo);
}
}
int foo_transmit_command(Foo foo, enum Command command)
{
size_t len = 0;
struct FooCommandPacket foo_command_packet = {0};
assert(foo != NULL);
assert((Command_MIN <= command) && (command <= Command_MAX));
/* Serialize command into foo_command_packet struct */
...
len = tcp_socket_send(foo->tcp_socket, &foo_command_packet, sizeof(foo_command_packet));
if (len < sizeof(foo_command_packet)) {
return -1;
}
return 0;
}
</code></pre>
<p>In the example above I would like to mock the <em>TcpSocket</em> object so that I can bring <em>"foo_transmit_command"</em> under unit testing but I'm not sure how to go about this without inheritance. I don't really want to redesign the code to use vtables unless I really have to. Maybe there is a better approach to this than mocking?</p>
<p>My testing experience comes mainly from C++ and I'm a bit afraid that I might have painted myself into a corner here. I would highly appreciate any recommendations from more experienced testers.</p>
<p>Edit:<br>
Like Richard Quirk pointed out it is really the call to <em>"tcp_socket_send"</em> that I want to override and I would prefer to do it without removing the real tcp_socket_send symbol from the library when linking the test since it is called by other tests in the same binary.</p>
<p>I'm starting to think that there is no obvious solution to this problem..</p>
|
[
{
"answer_id": 253119,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what you want to achieve.</p>\n\n<p>You can add all foo_* functions as function pointer members to <code>struct Foo_s</code> but you still need to explicitly pass pointer to your object as there is no implicit <code>this</code> in C. But it will give you encapsulation and polymorphism.</p>\n"
},
{
"answer_id": 253230,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>What OS are you using? I believe you could do an override with LD_PRELOAD on GNU/Linux: <a href=\"http://uberhip.com/people/godber/interception/html/slide_5.html\" rel=\"nofollow noreferrer\">This slide looks useful.</a></p>\n"
},
{
"answer_id": 253265,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 3,
"selected": true,
"text": "<p>You can use macro to redefine <code>tcp_socket_send</code> to <code>tcp_socket_send_moc</code> and link with real <code>tcp_socket_send</code> and dummy implementation for <code>tcp_socket_send_moc</code>.<br>\nyou will need to carefully select the proper place for : </p>\n\n<pre><code>#define tcp_socket_send tcp_socket_send_moc\n</code></pre>\n"
},
{
"answer_id": 975951,
"author": "Jordfräs",
"author_id": 6759,
"author_profile": "https://Stackoverflow.com/users/6759",
"pm_score": 2,
"selected": false,
"text": "<p>Have a look at TestDept:\n<a href=\"http://code.google.com/p/test-dept/\" rel=\"nofollow noreferrer\">http://code.google.com/p/test-dept/</a></p>\n\n<p>It is an open source project that aims at providing possiblity to have alternative implementations, e.g. stubs, of functions and being able to change in run-time which implementation of said function to use.</p>\n\n<p>It is all accomplished by mangling object files which is very nicely described on the home page of the project.</p>\n"
},
{
"answer_id": 4396872,
"author": "Yefei",
"author_id": 536097,
"author_profile": "https://Stackoverflow.com/users/536097",
"pm_score": 0,
"selected": false,
"text": "<p>Use Macro to refine tcp_socket_send is good. But the mock only returns one behavior. Or you need implement some variable in the mock function and setup it differently before each test case.\nAnother way is to change tcp_socket_send to function point. And points it to different mock function for different test case.</p>\n"
},
{
"answer_id": 8345978,
"author": "Martin",
"author_id": 1076006,
"author_profile": "https://Stackoverflow.com/users/1076006",
"pm_score": 1,
"selected": false,
"text": "<p>Alternatively, you can use TestApe <a href=\"http://testape.com\" rel=\"nofollow\">TestApe Unit testing for embedded software</a> - It can do it, but note it is C only. \nIt would go like this --></p>\n\n<pre><code>int mock_foo_transmit_command(Foo foo, enum Command command) {\n VALIDATE(foo, a);\n VALIDATE(command, b);\n}\n\nvoid test(void) {\n EXPECT_VALIDATE(foo_transmit_command, mock_foo_transmit_command);\n foo_transmit_command(a, b);\n}\n</code></pre>\n"
},
{
"answer_id": 33489442,
"author": "donfiguerres",
"author_id": 4097451,
"author_profile": "https://Stackoverflow.com/users/4097451",
"pm_score": 0,
"selected": false,
"text": "<p>To add to Ilya's answer. You can do this.</p>\n\n<pre><code>#define tcp_socket_send tcp_socket_send_moc\n#include \"your_source_code.c\"\n\nint tcp_socket_send_moc(...)\n{ ... }\n</code></pre>\n\n<p>I use the technique of including the source file into the unit testing module to minimize modifications in the source file when creating unit tests.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22247/"
] |
We use a simple object model for our low level networking code at work where struct pointers are passed around to functions which are pretending to be methods. I've inherited most of this code which was written by consultants with passable C/C++ experience at best and I've spent many late nights trying to refactor code into something that would resemble a reasonable structure.
Now I would like to bring the code under unit testing but considering the object model we have chosen I have no idea how to mock objects. See the example below:
Sample header (foo.h):
```
#ifndef FOO_H_
#define FOO_H_
typedef struct Foo_s* Foo;
Foo foo_create(TcpSocket tcp_socket);
void foo_destroy(Foo foo);
int foo_transmit_command(Foo foo, enum Command command);
#endif /* FOO_H_ */
```
Sample source (foo.c):
```
struct Foo_s {
TcpSocket tcp_socket;
};
Foo foo_create(TcpSocket tcp_socket)
{
Foo foo = NULL;
assert(tcp_socket != NULL);
foo = malloc(sizeof(struct Foo_s));
if (foo == NULL) {
goto fail;
}
memset(foo, 0UL, sizeof(struct Foo_s));
foo->tcp_socket = tcp_socket;
return foo;
fail:
foo_destroy(foo);
return NULL;
}
void foo_destroy(Foo foo)
{
if (foo != NULL) {
tcp_socket_destroy(foo->tcp_socket);
memset(foo, 0UL, sizeof(struct Foo_s));
free(foo);
}
}
int foo_transmit_command(Foo foo, enum Command command)
{
size_t len = 0;
struct FooCommandPacket foo_command_packet = {0};
assert(foo != NULL);
assert((Command_MIN <= command) && (command <= Command_MAX));
/* Serialize command into foo_command_packet struct */
...
len = tcp_socket_send(foo->tcp_socket, &foo_command_packet, sizeof(foo_command_packet));
if (len < sizeof(foo_command_packet)) {
return -1;
}
return 0;
}
```
In the example above I would like to mock the *TcpSocket* object so that I can bring *"foo\_transmit\_command"* under unit testing but I'm not sure how to go about this without inheritance. I don't really want to redesign the code to use vtables unless I really have to. Maybe there is a better approach to this than mocking?
My testing experience comes mainly from C++ and I'm a bit afraid that I might have painted myself into a corner here. I would highly appreciate any recommendations from more experienced testers.
Edit:
Like Richard Quirk pointed out it is really the call to *"tcp\_socket\_send"* that I want to override and I would prefer to do it without removing the real tcp\_socket\_send symbol from the library when linking the test since it is called by other tests in the same binary.
I'm starting to think that there is no obvious solution to this problem..
|
You can use macro to redefine `tcp_socket_send` to `tcp_socket_send_moc` and link with real `tcp_socket_send` and dummy implementation for `tcp_socket_send_moc`.
you will need to carefully select the proper place for :
```
#define tcp_socket_send tcp_socket_send_moc
```
|
253,026 |
<p>I used a class which derives from <code>CListBox</code>, and create it with following:</p>
<pre><code>style:WS_CHILD|WS_VISIBLE |LBS_OWNERDRAWFIXED | WS_VSCROLL | WS_HSCROLL
</code></pre>
<p>I expect the ListBox's item to be have a fixed size, not affected by the size of the list box. So I override the MeasureItem() method, in which I specify the item's size like below:</p>
<pre><code>void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS)
{
lpMIS->itemHeight = ALBUM_ITEM_HEIGHT;
lpMIS->itemWidth = ALBUM_ITEM_WIDTH;
}
</code></pre>
<p>But the item's size changes according to the List box's size changing. is there anything wrong with my approach?</p>
|
[
{
"answer_id": 253201,
"author": "Stu Mackellar",
"author_id": 28591,
"author_profile": "https://Stackoverflow.com/users/28591",
"pm_score": 0,
"selected": false,
"text": "<p>If you look at the <code>MSDN</code> entry for <a href=\"http://msdn.microsoft.com/en-us/library/t7tccyw7(VS.80).aspx\" rel=\"nofollow noreferrer\"><code>CListBox::MeasureItem</code></a> you'll see that it's only called once unless the <code>LBS_OWNERDRAWVARIABLE</code> (not <code>LBS_OWNERDRAWFIXED</code>) style is set. If I understand correctly then this would explain the behaviour you're seeing because <code>MeasureItem</code> would need to be called each time the control's size changes.</p>\n\n<p>Also, have you considered the points made in <a href=\"http://msdn.microsoft.com/en-us/library/bk2h3c6w(VS.80).aspx\" rel=\"nofollow noreferrer\">MFC Technical Note 14 : Custom Controls</a>?</p>\n"
},
{
"answer_id": 1125905,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 1,
"selected": false,
"text": "<p>What's not mentioned in the reference is that <code>WM_MEASUREITEM</code> is called <em>every time</em> the <code>*_OWNERDRAWFIXED</code> control is resized.</p>\n\n<p>I don't know however, how official this behavior is and whether it should be relied on, but it has been verified at <a href=\"http://www.codeguru.com/Cpp/controls/listview/advanced/article.php/c1013\" rel=\"nofollow noreferrer\">CodeGuru</a> and several forum posts found on the Google thing.</p>\n\n<p>If you don't want to process the message, then just set a private flag somewhere in the first <code>OnMeasureItem()</code> call and return from it as soon as you check that it's set next time.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26404/"
] |
I used a class which derives from `CListBox`, and create it with following:
```
style:WS_CHILD|WS_VISIBLE |LBS_OWNERDRAWFIXED | WS_VSCROLL | WS_HSCROLL
```
I expect the ListBox's item to be have a fixed size, not affected by the size of the list box. So I override the MeasureItem() method, in which I specify the item's size like below:
```
void CMyListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMIS)
{
lpMIS->itemHeight = ALBUM_ITEM_HEIGHT;
lpMIS->itemWidth = ALBUM_ITEM_WIDTH;
}
```
But the item's size changes according to the List box's size changing. is there anything wrong with my approach?
|
What's not mentioned in the reference is that `WM_MEASUREITEM` is called *every time* the `*_OWNERDRAWFIXED` control is resized.
I don't know however, how official this behavior is and whether it should be relied on, but it has been verified at [CodeGuru](http://www.codeguru.com/Cpp/controls/listview/advanced/article.php/c1013) and several forum posts found on the Google thing.
If you don't want to process the message, then just set a private flag somewhere in the first `OnMeasureItem()` call and return from it as soon as you check that it's set next time.
|
253,030 |
<p>If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?</p>
<p>first example:-</p>
<pre><code>if(ConditionOne && ConditionTwo && ConditionThree)
{
Code to execute
}
</code></pre>
<p>Second example:-</p>
<pre><code>if(ConditionOne)
{
if(ConditionTwo )
{
if(ConditionThree)
{
Code to execute
}
}
}
</code></pre>
<p>which is easiest to understand and read bearing in mind that each condition may be a long function name or something.</p>
|
[
{
"answer_id": 253034,
"author": "RB.",
"author_id": 15393,
"author_profile": "https://Stackoverflow.com/users/15393",
"pm_score": 2,
"selected": false,
"text": "<p>The first one is easier, because, if you read it left to right you get:\n\"If something AND somethingelse AND somethingelse THEN\" , which is an easy to understand sentence. The second example reads \"If something THEN if somethingelse THEN if something else THEN\", which is clumsy.</p>\n\n<p>Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?</p>\n"
},
{
"answer_id": 253047,
"author": "Torbjørn",
"author_id": 22621,
"author_profile": "https://Stackoverflow.com/users/22621",
"pm_score": 5,
"selected": false,
"text": "<p>Other answers explain why the first option is normally the best. But if you have multiple conditions, consider creating a separate function (or property) doing the condition checks in option 1. This makes the code much easier to read, at least when you use good method names.</p>\n\n<pre><code>if(MyChecksAreOk()) { Code to execute }\n\n...\n\nprivate bool MyChecksAreOk()\n{ \n return ConditionOne && ConditionTwo && ConditionThree;\n}\n</code></pre>\n\n<p>It the conditions only rely on local scope variables, you could make the new function static and pass in everything you need. If there is a mix, pass in the local stuff.</p>\n"
},
{
"answer_id": 253049,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 7,
"selected": false,
"text": "<p>I prefer Option A</p>\n\n<pre><code>bool a, b, c;\n\nif( a && b && c )\n{\n //This is neat & readable\n}\n</code></pre>\n\n<p>If you do have particularly long variables/method conditions you can just line break them</p>\n\n<pre><code>if( VeryLongConditionMethod(a) &&\n VeryLongConditionMethod(b) &&\n VeryLongConditionMethod(c))\n{\n //This is still readable\n}\n</code></pre>\n\n<p>If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement</p>\n\n<pre><code>bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);\nbool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);\nbool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);\n\nif( aa && bb && cc)\n{\n //This is again neat & readable\n //although you probably need to sanity check your method names ;)\n}\n</code></pre>\n\n<p>IMHO The only reason for option 'B' would be if you have separate <code>else</code> functions to run for each condition.</p>\n\n<p>e.g.</p>\n\n<pre><code>if( a )\n{\n if( b )\n {\n }\n else\n {\n //Do Something Else B\n }\n}\nelse\n{\n //Do Something Else A\n}\n</code></pre>\n"
},
{
"answer_id": 253056,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": 4,
"selected": false,
"text": "<p>The first example is more \"easy to read\". </p>\n\n<p>Actually, in my opinion you should only use the second one whenever you have to add some \"else logic\", but for a simple Conditional, use the first flavor. If you are worried about the long of the condition you always can use the next syntax:</p>\n\n<pre><code>if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine\n && ConditionTwoThatIsLongAsWell\n && ConditionThreeThatAlsoIsLong) { \n //Code to execute \n}\n</code></pre>\n\n<p>Good Luck!</p>\n"
},
{
"answer_id": 253131,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": 2,
"selected": false,
"text": "<p>The second one is a classic example of the <a href=\"http://www.codinghorror.com/blog/archives/000486.html\" rel=\"nofollow noreferrer\">Arrow Anti-pattern</a> So I'd avoid it...</p>\n\n<p>If your conditions are too long extract them into methods/properties.</p>\n"
},
{
"answer_id": 253168,
"author": "interstar",
"author_id": 8482,
"author_profile": "https://Stackoverflow.com/users/8482",
"pm_score": 3,
"selected": false,
"text": "<p>The question was asked and has, so far, been answered as though the decision should be made purely on \"syntactic\" grounds. </p>\n\n<p>I would say that the right answer of how you lay-out a number of conditions within an if, <em>ought</em> to depend on \"semantics\" too. So conditions should be broken up and grouped according to what things go together \"conceptually\".</p>\n\n<p>If two tests are really two sides of the same coin eg. if (x>0) && (x<=100) then put them together on the same line. If another condition is conceptually far more distant eg. user.hasPermission(Admin()) then put it on it's own line</p>\n\n<p>Eg.</p>\n\n<pre><code>if user.hasPermission(Admin()) {\n if (x >= 0) && (x < 100) {\n // do something\n }\n}\n</code></pre>\n"
},
{
"answer_id": 255234,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<h2>In Perl you could do this:</h2>\n<pre><code>{\n ( VeryLongCondition_1 ) or last;\n ( VeryLongCondition_2 ) or last;\n ( VeryLongCondition_3 ) or last;\n ( VeryLongCondition_4 ) or last;\n ( VeryLongCondition_5 ) or last;\n ( VeryLongCondition_6 ) or last;\n\n # Guarded code goes here\n}\n</code></pre>\n<p>If any of the conditions fail it will just continue on, after the block. If you are defining any variables that you want to keep around after the block, you will need to define them before the block.</p>\n"
},
{
"answer_id": 28644944,
"author": "CodeDriller",
"author_id": 2830887,
"author_profile": "https://Stackoverflow.com/users/2830887",
"pm_score": -1,
"selected": false,
"text": "<p>When condition is really complex I use the following style (PHP real life example):</p>\n\n<pre><code>if( $format_bool &&\n (\n ( isset( $column_info['native_type'] )\n && stripos( $column_info['native_type'], 'bool' ) !== false\n )\n || ( isset( $column_info['driver:decl_type'] )\n && stripos( $column_info['driver:decl_type'], 'bool' ) !== false\n )\n || ( isset( $column_info['pdo_type'] )\n && $column_info['pdo_type'] == PDO::PARAM_BOOL\n )\n )\n)\n</code></pre>\n\n<p>I believe it's more nice and readable than nesting multiple levels of <code>if()</code>. And in some cases like this you simply can't break complex condition into pieces because otherwise you would have to repeat the same statements in <code>if() {...}</code> block many times.</p>\n\n<p>I also believe that adding some \"air\" into code is always a good idea. It improves readability greatly.</p>\n"
},
{
"answer_id": 43506817,
"author": "Sean",
"author_id": 7892369,
"author_profile": "https://Stackoverflow.com/users/7892369",
"pm_score": 4,
"selected": false,
"text": "<pre class=\"lang-js prettyprint-override\"><code>if ( ( single conditional expression A )\n && ( single conditional expression B )\n && ( single conditional expression C )\n )\n{\n opAllABC();\n}\nelse\n{\n opNoneABC();\n}\n</code></pre>\n\n<p>Formatting a multiple conditional expressions in an if-else statement this way:</p>\n\n<ol>\n<li>allows for enhanced readability:<br>\na. all binary logical operations {&&, ||} in the expression shown first<br>\nb. both conditional operands of each binary operation are obvious because they align vertically<br>\nc. nested logical expressions operations are made obvious using indentation, just like nesting statements inside clause</li>\n<li>requires explicit parenthesis (not rely on operator precedence rules)<br>\na. this avoids a common static analysis errors</li>\n<li>allows for easier debugging<br>\na. disable individual single conditional tests with just a //<br>\nb. set a break point just before or after any individual test<br>\nc. e.g. ...</li>\n</ol>\n\n<pre class=\"lang-js prettyprint-override\"><code>// disable any single conditional test with just a pre-pended '//'\n// set a break point before any individual test\n// syntax '(1 &&' and '(0 ||' usually never creates any real code\nif ( 1\n && ( single conditional expression A )\n && ( single conditional expression B )\n && ( 0\n || ( single conditional expression C )\n || ( single conditional expression D )\n )\n )\n{\n ... ;\n}\n\nelse\n{\n ... ;\n}\n</code></pre>\n"
},
{
"answer_id": 51899288,
"author": "Tiper Loc",
"author_id": 9203238,
"author_profile": "https://Stackoverflow.com/users/9203238",
"pm_score": -1,
"selected": false,
"text": "<p>I've been facing this dilemma for a long time and I still can't find a proper solution. In my opinion only good way is to first try to get rid of conditions before so you're not suddenly comparing 5 of them.</p>\n\n<p>If there's no alternative then like others have suggested - break it down into separete ones and shorten the names or group them and e.g. if all must be true then use something like \"if no false in array of x then run\".</p>\n\n<p>If all fails @Eoin Campbell gave pretty good ideas.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
If you want to some code to execute based on two or more conditions which is the best way to format that if statement ?
first example:-
```
if(ConditionOne && ConditionTwo && ConditionThree)
{
Code to execute
}
```
Second example:-
```
if(ConditionOne)
{
if(ConditionTwo )
{
if(ConditionThree)
{
Code to execute
}
}
}
```
which is easiest to understand and read bearing in mind that each condition may be a long function name or something.
|
I prefer Option A
```
bool a, b, c;
if( a && b && c )
{
//This is neat & readable
}
```
If you do have particularly long variables/method conditions you can just line break them
```
if( VeryLongConditionMethod(a) &&
VeryLongConditionMethod(b) &&
VeryLongConditionMethod(c))
{
//This is still readable
}
```
If they're even more complicated, then I'd consider doing the condition methods separately outside the if statement
```
bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);
if( aa && bb && cc)
{
//This is again neat & readable
//although you probably need to sanity check your method names ;)
}
```
IMHO The only reason for option 'B' would be if you have separate `else` functions to run for each condition.
e.g.
```
if( a )
{
if( b )
{
}
else
{
//Do Something Else B
}
}
else
{
//Do Something Else A
}
```
|
253,036 |
<p>I have WPF ListBox which is bound to a ObservableCollection,
when the collection changes, all items update their position.</p>
<p>The new position is stored in the collection but the UI does not update.
So I added the following:</p>
<pre><code> void scenarioItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
ToolboxListItem.UpdatePositions();
lstScenario.ItemsSource = null;
lstScenario.ItemsSource = ToolboxListItem.ScenarioItems;
this.lstScenario.SelectedIndex = e.NewStartingIndex;
}
</code></pre>
<p>By setting the ItemsSource to null and then binding it again, the UI is updated,</p>
<p>but this is probably very bad coding :p</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 253094,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem yesterday, and it's a complete piece of crap :) ... I'm not setting mine to null anymore though. In my scenario, I am setting it to MyList.ToArray() (after every time I add to the list).</p>\n\n<p>I've seen multiple \"oh, you need to use an ObservableList\" <-- complete crap.</p>\n\n<p>I've seen multiple \"oh, call 'Refresh'\" <-- complete crap.</p>\n\n<p>Please forgive my upsettedness, but I also would expect this to work :)</p>\n"
},
{
"answer_id": 253298,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 7,
"selected": true,
"text": "<p>I have a Listbox bound to an object property which is of type <code>List<MyCustomType>()</code> and I verified that the following code updates the listbox when the List is updated.</p>\n\n<pre><code>void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)\n{\n MyListBox.Items.Refresh();\n}\n</code></pre>\n\n<p>If you're still facing issues, scan the VS IDE output window (Ctrl+W, O) and see if you can spot any binding errors reported.</p>\n"
},
{
"answer_id": 790120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you have an ObservableList of objects, and you're changing properties inside those objects, the notification doesn't apply since the collection is not changing directly. I have been forcing notification after changing my object properties by using Insert() to re-add my changed object to the collection, then RemoveAt() to remove the old copy. It's not pretty, but it works.</p>\n"
},
{
"answer_id": 1851824,
"author": "rolling",
"author_id": 225348,
"author_profile": "https://Stackoverflow.com/users/225348",
"pm_score": 4,
"selected": false,
"text": "<p>WPF binding a list / collection of items to a ListBox, but UI not refreshing after items updated, <strong>Solved</strong>.</p>\n\n<p>I'm just stupid. While I'd read a lot about using <code>ObservableCollection<></code> instead of <code>List<></code>, I just continued to ignore this suggestion and went following other suggestions, to no avail. Got back to my books and reread. It's pretty well explained that <code>ObservableCollection<></code> is a must use because <code>List<></code> doesn't provide the <code>INotifyCollectionChange</code> interface needed for the <code>ListBox</code> to update its display when the items change in the collection.</p>\n\n<p>This is the updated code:</p>\n\n<pre><code>private ObservableCollection<StringWrapper> m_AppLog;\nObservableCollection<StringWrapper> Log { get { return m_AppLog; } }\n</code></pre>\n\n<p>Pretty simple, and doesn't require anything else (e.g. Refresh()). Because ObservableCollection takes care itself of triggering the change event, I was able to remove the unnecessary call:</p>\n\n<pre><code>// notify bound objects\nOnPropertyChanged(\"Log\");\n</code></pre>\n\n<p><code>ObservableCollection</code> doesn't support an update by a thread which didn't create it. Because my list (a visual log to show the recent errors/info messages) can be updated from different threads, I add to adjust my code this way to ensure the update was done with the list's own dispatcher:</p>\n\n<pre><code>public void AddToLog(string message) {\n if (Thread.CurrentThread != Dispatcher.Thread) {\n // Need for invoke if called from a different thread\n Dispatcher.Invoke(\n DispatcherPriority.Normal, (ThreadStart)delegate() { AddToLog(message); });\n }\n else {\n // add this line at the top of the log\n m_AppLog.Insert(0, new StringWrapper(message));\n // ...\n</code></pre>\n\n<p>Also note that <code>ObservableCollection<></code> doesn't support <code>RemoveRange()</code> contrary to <code>List<></code>. This is part of the possible adjustments required when switching from List to ObservableCollection.</p>\n"
},
{
"answer_id": 2630735,
"author": "KP.",
"author_id": 315629,
"author_profile": "https://Stackoverflow.com/users/315629",
"pm_score": 2,
"selected": false,
"text": "<p>This is old stuff but, use an ObservableCollection. IF you want the UI to see updates to properties in the Objects of the ObservableCollection you need to implement INotifyPropertyChanged in the class defenition for that object. Then raise the property changed event in the setter of each property.</p>\n\n<pre><code>Public Class Session\nImplements INotifyPropertyChanged\n\nPublic Event PropertyChanged As PropertyChangedEventHandler _\n Implements INotifyPropertyChanged.PropertyChanged\n\nPrivate Sub NotifyPropertyChanged(ByVal info As String)\n RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))\nEnd Sub\n\nPrivate _name As String = \"No name\"\n''' <summary>\n''' Name of Session\n''' </summary>\n''' <value></value>\n''' <returns></returns>\n''' <remarks></remarks>\nPublic Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n NotifyPropertyChanged(\"Name\")\n End Set\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 4139066,
"author": "Alfred B. Thordarson",
"author_id": 3379,
"author_profile": "https://Stackoverflow.com/users/3379",
"pm_score": 3,
"selected": false,
"text": "<p>I may be having a similar problem to what you are having, but I'm not sure.</p>\n\n<p>I had an <code>ObservableCollection<MyEntity></code> and a <code>ListBox</code> bound to it. But for some <em>strange reason</em> my <code>ListBox</code> was not being updated when I changed the properties of the <code>MyEntity</code> objects in the list.</p>\n\n<p>After searching for a while I found the following page and I just had to let you know:</p>\n\n<p><a href=\"https://web.archive.org/web/20160609072341/http://wblum.org:80/listbind/net3/index.html\" rel=\"nofollow noreferrer\">http://www.wblum.org/listbind/net3/index.html</a></p>\n\n<p>It is a very good description of what you have to do to get a <code>ListBox</code> to update when the list, or the objects within it, changes. Hoping you will benefit from this.</p>\n"
},
{
"answer_id": 26303591,
"author": "flobadob",
"author_id": 339348,
"author_profile": "https://Stackoverflow.com/users/339348",
"pm_score": 0,
"selected": false,
"text": "<p>To me, it looks more like a bug in ListBox and ListView. I am binding to an ObservableCollection, the items in the collection implement INotifyPropertyChanged. The UI shows no added items when I dynamically press my 'add item' button however I have a counter control that is bound to MyCollection.Count. This counter control increments each time I press my 'add item' button. If I resize the view, the list box shows all my added items. So, the ItemSource binding on the ListBox control is broken. I also took care not to create a new MyCollection at any point, which would break the binding. Boo hoo.</p>\n"
},
{
"answer_id": 59042877,
"author": "Berger",
"author_id": 11217628,
"author_profile": "https://Stackoverflow.com/users/11217628",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's already a bit older but today I faced the same issue. I updated an property of an object inside an ObservableCollection and the View did not update, but then I found <a href=\"https://nishantrana.me/2012/04/12/refresh-observablecollection-in-wpf/\" rel=\"nofollow noreferrer\">this</a> awesome article.</p>\n\n<p>I think it's a very clean solution to manually trigger the update of an ObservableCollection:</p>\n\n<pre><code>CollectionViewSource.GetDefaultView(this.myObservableCollection).Refresh();\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28149/"
] |
I have WPF ListBox which is bound to a ObservableCollection,
when the collection changes, all items update their position.
The new position is stored in the collection but the UI does not update.
So I added the following:
```
void scenarioItems_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
ToolboxListItem.UpdatePositions();
lstScenario.ItemsSource = null;
lstScenario.ItemsSource = ToolboxListItem.ScenarioItems;
this.lstScenario.SelectedIndex = e.NewStartingIndex;
}
```
By setting the ItemsSource to null and then binding it again, the UI is updated,
but this is probably very bad coding :p
Suggestions?
|
I have a Listbox bound to an object property which is of type `List<MyCustomType>()` and I verified that the following code updates the listbox when the List is updated.
```
void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MyListBox.Items.Refresh();
}
```
If you're still facing issues, scan the VS IDE output window (Ctrl+W, O) and see if you can spot any binding errors reported.
|
253,038 |
<p>I'm having a bit of a problem. I have a datatable in the parent form. I open a dialogbox form that gets the datatable property and creates a checkboxlist. This will be used to export those columns. But when I run the application the parentform property is null. I've tried setting it in the parent and dialogbox form (I assumed this would have been done automagically if ShowDialog() was called).</p>
<p>Can someone take a look and see where I'm going wrong?
From the dialogbox:</p>
<pre><code>frmParent MyParentForm = (frmParent)this.ParentForm;
for (int i=0; i<MyParentForm.DataGridTable.Count; i++)
{
chkListExportItems.Add(MyParentForm.DataGrid.Columns[i].Name,true);
}
</code></pre>
<p>From the parent form:</p>
<pre><code>frmExports MyForm = new frmExports();
MyForm.MdiParent = this;
if (MyForm.ShowDialog == DialogResult.OK)
{
MyForm.SelectedItems // Do something
}
</code></pre>
|
[
{
"answer_id": 253094,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem yesterday, and it's a complete piece of crap :) ... I'm not setting mine to null anymore though. In my scenario, I am setting it to MyList.ToArray() (after every time I add to the list).</p>\n\n<p>I've seen multiple \"oh, you need to use an ObservableList\" <-- complete crap.</p>\n\n<p>I've seen multiple \"oh, call 'Refresh'\" <-- complete crap.</p>\n\n<p>Please forgive my upsettedness, but I also would expect this to work :)</p>\n"
},
{
"answer_id": 253298,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 7,
"selected": true,
"text": "<p>I have a Listbox bound to an object property which is of type <code>List<MyCustomType>()</code> and I verified that the following code updates the listbox when the List is updated.</p>\n\n<pre><code>void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)\n{\n MyListBox.Items.Refresh();\n}\n</code></pre>\n\n<p>If you're still facing issues, scan the VS IDE output window (Ctrl+W, O) and see if you can spot any binding errors reported.</p>\n"
},
{
"answer_id": 790120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you have an ObservableList of objects, and you're changing properties inside those objects, the notification doesn't apply since the collection is not changing directly. I have been forcing notification after changing my object properties by using Insert() to re-add my changed object to the collection, then RemoveAt() to remove the old copy. It's not pretty, but it works.</p>\n"
},
{
"answer_id": 1851824,
"author": "rolling",
"author_id": 225348,
"author_profile": "https://Stackoverflow.com/users/225348",
"pm_score": 4,
"selected": false,
"text": "<p>WPF binding a list / collection of items to a ListBox, but UI not refreshing after items updated, <strong>Solved</strong>.</p>\n\n<p>I'm just stupid. While I'd read a lot about using <code>ObservableCollection<></code> instead of <code>List<></code>, I just continued to ignore this suggestion and went following other suggestions, to no avail. Got back to my books and reread. It's pretty well explained that <code>ObservableCollection<></code> is a must use because <code>List<></code> doesn't provide the <code>INotifyCollectionChange</code> interface needed for the <code>ListBox</code> to update its display when the items change in the collection.</p>\n\n<p>This is the updated code:</p>\n\n<pre><code>private ObservableCollection<StringWrapper> m_AppLog;\nObservableCollection<StringWrapper> Log { get { return m_AppLog; } }\n</code></pre>\n\n<p>Pretty simple, and doesn't require anything else (e.g. Refresh()). Because ObservableCollection takes care itself of triggering the change event, I was able to remove the unnecessary call:</p>\n\n<pre><code>// notify bound objects\nOnPropertyChanged(\"Log\");\n</code></pre>\n\n<p><code>ObservableCollection</code> doesn't support an update by a thread which didn't create it. Because my list (a visual log to show the recent errors/info messages) can be updated from different threads, I add to adjust my code this way to ensure the update was done with the list's own dispatcher:</p>\n\n<pre><code>public void AddToLog(string message) {\n if (Thread.CurrentThread != Dispatcher.Thread) {\n // Need for invoke if called from a different thread\n Dispatcher.Invoke(\n DispatcherPriority.Normal, (ThreadStart)delegate() { AddToLog(message); });\n }\n else {\n // add this line at the top of the log\n m_AppLog.Insert(0, new StringWrapper(message));\n // ...\n</code></pre>\n\n<p>Also note that <code>ObservableCollection<></code> doesn't support <code>RemoveRange()</code> contrary to <code>List<></code>. This is part of the possible adjustments required when switching from List to ObservableCollection.</p>\n"
},
{
"answer_id": 2630735,
"author": "KP.",
"author_id": 315629,
"author_profile": "https://Stackoverflow.com/users/315629",
"pm_score": 2,
"selected": false,
"text": "<p>This is old stuff but, use an ObservableCollection. IF you want the UI to see updates to properties in the Objects of the ObservableCollection you need to implement INotifyPropertyChanged in the class defenition for that object. Then raise the property changed event in the setter of each property.</p>\n\n<pre><code>Public Class Session\nImplements INotifyPropertyChanged\n\nPublic Event PropertyChanged As PropertyChangedEventHandler _\n Implements INotifyPropertyChanged.PropertyChanged\n\nPrivate Sub NotifyPropertyChanged(ByVal info As String)\n RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))\nEnd Sub\n\nPrivate _name As String = \"No name\"\n''' <summary>\n''' Name of Session\n''' </summary>\n''' <value></value>\n''' <returns></returns>\n''' <remarks></remarks>\nPublic Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n NotifyPropertyChanged(\"Name\")\n End Set\nEnd Property\n</code></pre>\n"
},
{
"answer_id": 4139066,
"author": "Alfred B. Thordarson",
"author_id": 3379,
"author_profile": "https://Stackoverflow.com/users/3379",
"pm_score": 3,
"selected": false,
"text": "<p>I may be having a similar problem to what you are having, but I'm not sure.</p>\n\n<p>I had an <code>ObservableCollection<MyEntity></code> and a <code>ListBox</code> bound to it. But for some <em>strange reason</em> my <code>ListBox</code> was not being updated when I changed the properties of the <code>MyEntity</code> objects in the list.</p>\n\n<p>After searching for a while I found the following page and I just had to let you know:</p>\n\n<p><a href=\"https://web.archive.org/web/20160609072341/http://wblum.org:80/listbind/net3/index.html\" rel=\"nofollow noreferrer\">http://www.wblum.org/listbind/net3/index.html</a></p>\n\n<p>It is a very good description of what you have to do to get a <code>ListBox</code> to update when the list, or the objects within it, changes. Hoping you will benefit from this.</p>\n"
},
{
"answer_id": 26303591,
"author": "flobadob",
"author_id": 339348,
"author_profile": "https://Stackoverflow.com/users/339348",
"pm_score": 0,
"selected": false,
"text": "<p>To me, it looks more like a bug in ListBox and ListView. I am binding to an ObservableCollection, the items in the collection implement INotifyPropertyChanged. The UI shows no added items when I dynamically press my 'add item' button however I have a counter control that is bound to MyCollection.Count. This counter control increments each time I press my 'add item' button. If I resize the view, the list box shows all my added items. So, the ItemSource binding on the ListBox control is broken. I also took care not to create a new MyCollection at any point, which would break the binding. Boo hoo.</p>\n"
},
{
"answer_id": 59042877,
"author": "Berger",
"author_id": 11217628,
"author_profile": "https://Stackoverflow.com/users/11217628",
"pm_score": 2,
"selected": false,
"text": "<p>I know it's already a bit older but today I faced the same issue. I updated an property of an object inside an ObservableCollection and the View did not update, but then I found <a href=\"https://nishantrana.me/2012/04/12/refresh-observablecollection-in-wpf/\" rel=\"nofollow noreferrer\">this</a> awesome article.</p>\n\n<p>I think it's a very clean solution to manually trigger the update of an ObservableCollection:</p>\n\n<pre><code>CollectionViewSource.GetDefaultView(this.myObservableCollection).Refresh();\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5906/"
] |
I'm having a bit of a problem. I have a datatable in the parent form. I open a dialogbox form that gets the datatable property and creates a checkboxlist. This will be used to export those columns. But when I run the application the parentform property is null. I've tried setting it in the parent and dialogbox form (I assumed this would have been done automagically if ShowDialog() was called).
Can someone take a look and see where I'm going wrong?
From the dialogbox:
```
frmParent MyParentForm = (frmParent)this.ParentForm;
for (int i=0; i<MyParentForm.DataGridTable.Count; i++)
{
chkListExportItems.Add(MyParentForm.DataGrid.Columns[i].Name,true);
}
```
From the parent form:
```
frmExports MyForm = new frmExports();
MyForm.MdiParent = this;
if (MyForm.ShowDialog == DialogResult.OK)
{
MyForm.SelectedItems // Do something
}
```
|
I have a Listbox bound to an object property which is of type `List<MyCustomType>()` and I verified that the following code updates the listbox when the List is updated.
```
void On_MyObjProperty_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MyListBox.Items.Refresh();
}
```
If you're still facing issues, scan the VS IDE output window (Ctrl+W, O) and see if you can spot any binding errors reported.
|
253,055 |
<p>When I've worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit:</p>
<pre><code>> git commit --amend
</code></pre>
<p>Unfortunately the commit can't be pushed back to the repository. It is rejected like this:</p>
<pre><code>> git push origin
To //my.remote.repo.com/stuff.git/
! [rejected] master -> master (non-fast forward)
error: failed to push some refs to '//my.remote.repo.com/stuff.git/'
</code></pre>
<p>What should I do? (I can access the remote repository.)</p>
|
[
{
"answer_id": 253229,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 1,
"selected": false,
"text": "<p>I had to fix this problem with pulling from the remote repo and deal with the merge conflicts that arose, commit and then push. But I feel like there is a better way.</p>\n"
},
{
"answer_id": 253726,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 7,
"selected": false,
"text": "<p>Short answer: Don't push amended commits to a public repo.</p>\n\n<p>Long answer: A few Git commands, like <code>git commit --amend</code> and <code>git rebase</code>, actually rewrite the history graph. This is fine as long as you haven't published your changes, but once you do, you really shouldn't be mucking around with the history, because if someone already got your changes, then when they try to pull again, it might fail. Instead of amending a commit, you should just make a new commit with the changes.</p>\n\n<p>However, if you really, really want to push an amended commit, you can do so like this:</p>\n\n<pre><code>$ git push origin +master:master\n</code></pre>\n\n<p>The leading <code>+</code> sign will force the push to occur, even if it doesn't result in a \"fast-forward\" commit. (A fast-forward commit occurs when the changes you are pushing are a <em>direct descendant</em> of the changes already in the public repo.)</p>\n"
},
{
"answer_id": 255080,
"author": "CB Bailey",
"author_id": 19563,
"author_profile": "https://Stackoverflow.com/users/19563",
"pm_score": 8,
"selected": false,
"text": "<p>You are seeing a Git safety feature. Git refuses to update the remote branch with your branch, because your branch's head commit is not a direct descendent of the current head commit of the branch that you are pushing to.</p>\n\n<p>If this were not the case, then two people pushing to the same repository at about the same time would not know that there was a new commit coming in at the same time and whoever pushed last would lose the work of the previous pusher without either of them realising this.</p>\n\n<p>If you know that you are the only person pushing and you want to push an amended commit or push a commit that winds back the branch, you can 'force' Git to update the remote branch by using the <code>-f</code> switch.</p>\n\n<pre><code>git push -f origin master\n</code></pre>\n\n<p>Even this may not work as Git allows remote repositories to refuse non-fastforward pushes at the far end by using the configuration variable <code>receive.denynonfastforwards</code>. If this is the case the rejection reason will look like this (note the 'remote rejected' part):</p>\n\n<pre><code> ! [remote rejected] master -> master (non-fast forward)\n</code></pre>\n\n<p>To get around this, you either need to change the remote repository's configuration or as a dirty hack you can delete and recreate the branch thus:</p>\n\n<pre><code>git push origin :master\ngit push origin master\n</code></pre>\n\n<p>In general the last parameter to <code>git push</code> uses the format <code><local_ref>:<remote_ref></code>, where <code>local_ref</code> is the name of the branch on the local repository and <code>remote_ref</code> is the name of the branch on the remote repository. This command pair uses two shorthands. <code>:master</code> has a null local_ref which means push a null branch to the remote side <code>master</code>, i.e. delete the remote branch. A branch name with no <code>:</code> means push the local branch with the given name to the remote branch with the same name. <code>master</code> in this situation is short for <code>master:master</code>.</p>\n"
},
{
"answer_id": 432518,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 10,
"selected": true,
"text": "<p>I actually once pushed with <code>--force</code> and <code>.git</code> repository and got scolded by Linus <strong>BIG TIME</strong>. In general this will create a lot of problems for other people. A simple answer is \"Don't do it\".</p>\n\n<p>I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation <em>after</em> you have pushed out the amended commit with --force (or +master).</p>\n\n<ol>\n<li>Use <code>git reflog</code> to find the old commit that you amended (call it <code>old</code>, and we'll call the new commit you created by amending <code>new</code>).</li>\n<li>Create a merge between <code>old</code> and <code>new</code>, recording the tree of <code>new</code>, like <code>git checkout new && git merge -s ours old</code>.</li>\n<li>Merge that to your master with <code>git merge master</code></li>\n<li>Update your master with the result with <code>git push . HEAD:master</code></li>\n<li>Push the result out.</li>\n</ol>\n\n<p>Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor <code>new</code> over <code>old</code>. Their later merges will not see the conflicts between <code>old</code> and <code>new</code> that resulted from your amending, so they do not have to suffer.</p>\n"
},
{
"answer_id": 1459351,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>Quick rant: The fact that no one has posted the simple answer here demonstrates the desperate user-hostility exhibited by the Git CLI.</p>\n\n<p>Anyway, the \"obvious\" way to do this, assuming you haven't tried to force the push, is to pull first. This pulls the change that you amended (and so no longer have) so that you have it again.</p>\n\n<p>Once you have resolved any conflicts, you can push again.</p>\n\n<p>So:</p>\n\n<pre><code>git pull\n</code></pre>\n\n<p>If you get errors in pull, maybe something is wrong in your local repository configuration (I had a wrong ref in the .git/config branch section).</p>\n\n<p>And after</p>\n\n<pre><code>git push\n</code></pre>\n\n<p>Maybe you will get an extra commit with the subject telling about a \"Trivial merge\".</p>\n"
},
{
"answer_id": 12568457,
"author": "bara",
"author_id": 794407,
"author_profile": "https://Stackoverflow.com/users/794407",
"pm_score": 5,
"selected": false,
"text": "<p>I have solved it by discarding my local amended commit and adding the new changes on top:</p>\n\n<pre><code># Rewind to commit before conflicting\ngit reset --soft HEAD~1\n\n# Pull the remote version\ngit pull\n\n# Add the new commit on top\ngit add ...\ngit commit\ngit push\n</code></pre>\n"
},
{
"answer_id": 21904884,
"author": "davisca",
"author_id": 3298088,
"author_profile": "https://Stackoverflow.com/users/3298088",
"pm_score": 4,
"selected": false,
"text": "<p>I had the same problem.</p>\n\n<ul>\n<li>Accidentally amended the last commit that was already pushed</li>\n<li>Done a lot of changes locally, committed some five times</li>\n<li>Tried to push, got an error, panicked, merged remote, got a lot of not-my-files, pushed, failed, etc.</li>\n</ul>\n\n<p>As a Git-newbie, I thought it was complete <a href=\"https://en.wiktionary.org/wiki/FUBAR#Adjective\" rel=\"nofollow noreferrer\">FUBAR</a>.</p>\n\n<p>Solution: Somewhat like @bara suggested + created a local backup branch</p>\n\n<pre><code># Rewind to commit just before the pushed-and-amended one.\n# Replace <hash> with the needed hash.\n# --soft means: leave all the changes there, so nothing is lost.\ngit reset --soft <hash>\n\n# Create new branch, just for a backup, still having all changes in it.\n# The branch was feature/1234, new one - feature/1234-gone-bad\ngit checkout -b feature/1234-gone-bad\n\n# Commit all the changes (all the mess) not to lose it & not to carry around\ngit commit -a -m \"feature/1234 backup\"\n\n# Switch back to the original branch\ngit checkout feature/1234\n\n# Pull the from remote (named 'origin'), thus 'repairing' our main problem\ngit pull origin/feature/1234\n\n# Now you have a clean-and-non-diverged branch and a backup of the local changes.\n# Check the needed files from the backup branch\ngit checkout feature/1234-gone-bad -- the/path/to/file.php\n</code></pre>\n\n<p>Maybe it's not a fast and clean solution, and I lost my history (1 commit instead of 5), but it saved a day's work.</p>\n"
},
{
"answer_id": 27916801,
"author": "Prabhakar Undurthi",
"author_id": 2200417,
"author_profile": "https://Stackoverflow.com/users/2200417",
"pm_score": 3,
"selected": false,
"text": "<p>If you have not pushed the code to your remote branch (GitHub/Bitbucket) you can change the commit message on the command line as below.</p>\n\n<pre><code> git commit --amend -m \"Your new message\"\n</code></pre>\n\n<p>If you're working on a specific branch, do this:</p>\n\n<pre><code>git commit --amend -m \"BRANCH-NAME: new message\"\n</code></pre>\n\n<p>If you've already pushed the code with a wrong message then you need to be careful when changing the message. i.e after you change the commit message and try pushing it again you end up with having issues. To make it smooth follow the following steps.</p>\n\n<p><strong>Please read the entire answer before doing it</strong></p>\n\n<pre><code>git commit --amend -m \"BRANCH-NAME : your new message\"\n\ngit push -f origin BRANCH-NAME # Not a best practice. Read below why?\n</code></pre>\n\n<p><strong>Important note:</strong> When you use the force push directly you might end up with code issues that other developers are working on the same branch. So to avoid those conflicts you need to pull the code from your branch before making the <strong>force push</strong>:</p>\n\n<pre><code> git commit --amend -m \"BRANCH-NAME : your new message\"\n git pull origin BRANCH-NAME\n git push -f origin BRANCH-NAME\n</code></pre>\n\n<p>This is the best practice when changing the commit message, if it was already pushed.</p>\n"
},
{
"answer_id": 30965735,
"author": "Faiza",
"author_id": 2349823,
"author_profile": "https://Stackoverflow.com/users/2349823",
"pm_score": 6,
"selected": false,
"text": "<p>Here is a very simple and clean way to push your changes after you have already made a <code>commit --amend</code>:</p>\n<pre><code>git reset --soft HEAD^\ngit stash\ngit push -f origin master\ngit stash pop\ngit commit -a\ngit push origin master\n</code></pre>\n<p>Which does the following:</p>\n<ul>\n<li>Reset branch head to parent commit.</li>\n<li>Stash this last commit.</li>\n<li>Force push to remote. The remote now doesn't have the last commit.</li>\n<li>Pop your stash.</li>\n<li>Commit cleanly.</li>\n<li>Push to remote.</li>\n</ul>\n<p>Remember to change <code>origin</code> and <code>master</code> if applying this to a different branch or remote.</p>\n"
},
{
"answer_id": 34850197,
"author": "craken",
"author_id": 3952386,
"author_profile": "https://Stackoverflow.com/users/3952386",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a very simple and clean way to push your changes after you have already made a <code>git add \"your files\"</code> and <code>git commit --amend</code>:</p>\n\n<pre><code>git push origin master -f\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>git push origin master --force\n</code></pre>\n"
},
{
"answer_id": 34916908,
"author": "Praveen Dhawan",
"author_id": 5060168,
"author_profile": "https://Stackoverflow.com/users/5060168",
"pm_score": 3,
"selected": false,
"text": "<p>You are getting this error because the Git remote already has these commit files. You have to force push the branch for this to work:</p>\n\n<pre><code>git push -f origin branch_name\n</code></pre>\n\n<p>Also make sure you pull the code from remote as someone else on your team might have pushed to the same branch.</p>\n\n<pre><code>git pull origin branch_name\n</code></pre>\n\n<p>This is one of the cases where we have to force push the commit to remote.</p>\n"
},
{
"answer_id": 37668596,
"author": "ShawnFeatherly",
"author_id": 228738,
"author_profile": "https://Stackoverflow.com/users/228738",
"pm_score": 3,
"selected": false,
"text": "<p>If you know nobody has pulled your un-amended commit, use the <code>--force-with-lease</code> option of <code>git push</code>.</p>\n\n<p>In TortoiseGit, you can do the same thing under \"Push...\" options \"Force: May discard\" and checking \"known changes\".</p>\n\n<blockquote>\n <p><a href=\"https://tortoisegit.org/docs/tortoisegit/tgit-dug-push.html\" rel=\"nofollow noreferrer\">Force (May discard known changes)</a> allows the remote repository to accept a safer non-fast-forward push. This can cause the remote repository to lose commits; use it with care. This can prevent from losing unknown changes from other people on the remote. It checks if the server branch points to the same commit as the remote-tracking branch (known changes). If yes, a force push will be performed. Otherwise it will be rejected. Since git does not have remote-tracking tags, tags cannot be overwritten using this option.</p>\n</blockquote>\n"
},
{
"answer_id": 40936824,
"author": "Rolf",
"author_id": 370786,
"author_profile": "https://Stackoverflow.com/users/370786",
"pm_score": 1,
"selected": false,
"text": "<p>I just kept doing what Git told me to do. So:</p>\n\n<ul>\n<li>Can't push because of amended commit. </li>\n<li>I do a pull as suggested. </li>\n<li>Merge fails. so I fix it manually.</li>\n<li>Create a new commit (labeled\n\"merge\") and push it.</li>\n<li>It seems to work!</li>\n</ul>\n\n<p>Note: The amended commit was the latest one.</p>\n"
},
{
"answer_id": 55135753,
"author": "Harshal Wani",
"author_id": 2226399,
"author_profile": "https://Stackoverflow.com/users/2226399",
"pm_score": 0,
"selected": false,
"text": "<p>Here, How I fixed an edit in a previous commit:</p>\n<ol>\n<li><p>Save your work so far.</p>\n</li>\n<li><p>Stash your changes away for now if made: <code>git stash</code> Now your working copy is clean at the state of your last commit.</p>\n</li>\n<li><p>Make the edits and fixes.</p>\n</li>\n<li><p>Commit the changes in <strong>"amend"</strong> mode: <code>git commit --all --amend</code></p>\n</li>\n<li><p>Your editor will come up asking for a log message (by default, the old log message). Save and quit the editor when you're happy with it.</p>\n<p>The new changes are added on to the old commit. See for yourself with <code>git log</code> and <code>git diff HEAD^</code></p>\n</li>\n<li><p>Re-apply your stashed changes, if made: <code>git stash apply</code></p>\n</li>\n</ol>\n"
},
{
"answer_id": 60032800,
"author": "MadPhysicist",
"author_id": 5969463,
"author_profile": "https://Stackoverflow.com/users/5969463",
"pm_score": 1,
"selected": false,
"text": "<p>The following worked for me when changing Author and Committer of a commit. </p>\n\n<p><code>git push -f origin master</code></p>\n\n<p>Git was smart enough to figure out that these were commits of identical deltas which only differed in the meta information section.</p>\n\n<p>Both the local and remote heads pointed to the commits in question.</p>\n"
},
{
"answer_id": 60560824,
"author": "Okan Cetin",
"author_id": 9134911,
"author_profile": "https://Stackoverflow.com/users/9134911",
"pm_score": 3,
"selected": false,
"text": "<p>If you are using Visual Studio Code, you can try this extension to make it easier. </p>\n\n<p><a href=\"https://marketplace.visualstudio.com/items?itemName=cimdalli.git-commit-amend-push-force\" rel=\"noreferrer\">https://marketplace.visualstudio.com/items?itemName=cimdalli.git-commit-amend-push-force</a></p>\n\n<p>As you can understand from its name, it executes commands consecutively </p>\n\n<ul>\n<li><code>git commit --amend</code> </li>\n<li><code>git push --force</code></li>\n</ul>\n"
},
{
"answer_id": 71289589,
"author": "FNia",
"author_id": 3092394,
"author_profile": "https://Stackoverflow.com/users/3092394",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid forced push, in the remote bare repository remove the last commit (the one to be amended) using:</p>\n<pre><code>git update-ref HEAD HEAD^\n</code></pre>\n<p>then push the amended commit with no conflict.</p>\n<p>Note: This assumes no one has pulled the wrong commit in the meantime. If they have, they will have to similarly rewind and pull again, possibly merging their own changes.</p>\n"
},
{
"answer_id": 71495523,
"author": "M-Razavi",
"author_id": 601288,
"author_profile": "https://Stackoverflow.com/users/601288",
"pm_score": 3,
"selected": false,
"text": "<p>If the message to be changed is for the latest commit to the repository, then the following commands are to be executed:</p>\n<pre><code>git commit --amend -m "New message"\n\ngit push --force repository-name branch-name\n</code></pre>\n<p><strong>Note</strong>: using --force is not recommended unless you are absolutely sure that no one else has cloned your repository after the latest commit.</p>\n<p>A safer alternative is to use:</p>\n<pre><code>git push --force-with-lease repository-name branch-name\n</code></pre>\n<p>Unlike <code>--force</code>, which will destroy any changes someone else has pushed to the branch, <code>--force-with-lease</code> will abort if there was an upstream change to the repository.</p>\n"
},
{
"answer_id": 72211457,
"author": "Dario Fernández",
"author_id": 11751045,
"author_profile": "https://Stackoverflow.com/users/11751045",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it in a simple and safe way by doing:</p>\n<ol>\n<li>Amend your last commit with <code>git commit --amend</code> and whatever options you need to add</li>\n<li><code>git pull</code> to sync your local repo with your remote repo.</li>\n<li>After pull, <strong>you will have conflicts</strong> between local and remote. You just have to solve them by <strong>accepting current changes</strong> and commit again.</li>\n<li><code>git push</code></li>\n</ol>\n<p>Now your local and remote repo are updated with no need to change your repo history.</p>\n"
},
{
"answer_id": 73939340,
"author": "Hunter8",
"author_id": 11488976,
"author_profile": "https://Stackoverflow.com/users/11488976",
"pm_score": 1,
"selected": false,
"text": "<p>In this case, you should --force.</p>\n<p>Based on:</p>\n<p>If it is an individual project, I would do this:\n<code>git push origin <branch-name> -f</code></p>\n<p>If you are working with your team, or other peers are reviewing and using your code the <code>force</code> flag is not recommended. Mainly because you always want a clean git history.</p>\n<p>What I would do?</p>\n<ol>\n<li>If more people are working in the same branch or others reviewing your code, I would <code>git commit --amend</code>, then <code>git push -f ...</code> and let people know that they need to <code>git pull --rebase</code> to be able to see your changes.</li>\n<li>If something like this happens while reviewing a PR or MR, add new clean commit and at the end <code>squash</code> to clean up history.</li>\n</ol>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
] |
When I've worked a bit with my source code, I did my usual thing commit and then I pushed to a remote repository. But then I noticed I forgot to organize my imports in the source code. So I do the amend command to replace the previous commit:
```
> git commit --amend
```
Unfortunately the commit can't be pushed back to the repository. It is rejected like this:
```
> git push origin
To //my.remote.repo.com/stuff.git/
! [rejected] master -> master (non-fast forward)
error: failed to push some refs to '//my.remote.repo.com/stuff.git/'
```
What should I do? (I can access the remote repository.)
|
I actually once pushed with `--force` and `.git` repository and got scolded by Linus **BIG TIME**. In general this will create a lot of problems for other people. A simple answer is "Don't do it".
I see others gave the recipe for doing so anyway, so I won't repeat them here. But here is a tip to recover from the situation *after* you have pushed out the amended commit with --force (or +master).
1. Use `git reflog` to find the old commit that you amended (call it `old`, and we'll call the new commit you created by amending `new`).
2. Create a merge between `old` and `new`, recording the tree of `new`, like `git checkout new && git merge -s ours old`.
3. Merge that to your master with `git merge master`
4. Update your master with the result with `git push . HEAD:master`
5. Push the result out.
Then people who were unfortunate enough to have based their work on the commit you obliterated by amending and forcing a push will see the resulting merge will see that you favor `new` over `old`. Their later merges will not see the conflicts between `old` and `new` that resulted from your amending, so they do not have to suffer.
|
253,058 |
<p>Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way.</p>
<pre><code>interface IFoo
{
void DoSomething();
}
class Foo : IFoo
{
#region IFoo Members
public void DoSomething()
{
Console.WriteLine("do something implicitly");
}
#endregion
#region IFoo Members
void IFoo.DoSomething()
{
Console.WriteLine("do something explicitly");
}
#endregion
}
Foo f = new Foo();
f.DoSomething();
((IFoo)f).DoSomething();
</code></pre>
<p>Above code runs and output</p>
<pre><code>do something implicitly
do something explicitly
</code></pre>
<p>I believe that this design of C# make inconsistency of behavior. Perhaps it is mandatory that one C# class can inherit from one interface in implicit or expliict way, but not both. </p>
<p>Is there any reason that why C# is designed in such a way?</p>
|
[
{
"answer_id": 253073,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<p>Every class that implements an interface has a <em>mapping</em> between that class's members and the interface's members. If the class <em>explicitly</em> implements an interface member, then the explicit implementation will <strong>always</strong> be mapped to the interface. If there isn't an explicit implementation then an implicit implementation is expected, and that one will be mapped to the interface.</p>\n\n<p>When a class has the same member name and associated types as an interface <strong>but</strong> it also explicitly implements the corresponding member for the interface, then the class's \"implicit\" implementation <em>isn't</em> considered an implementation of the interface <em>at all</em> (unless the explicit implementation calls it).</p>\n\n<p>In addition to different meanings in each case where the class implements multiple interfaces with the same member name/types, even with only one interface, the <em>class itself</em> is considered to have an implicit interface which might have the same member/types as the sole interface but still mean something different.</p>\n"
},
{
"answer_id": 253079,
"author": "François",
"author_id": 32379,
"author_profile": "https://Stackoverflow.com/users/32379",
"pm_score": 2,
"selected": false,
"text": "<p>Multiple inheritance :\nWhat if you derive from two interfaces defining same method for different purposes?</p>\n\n<pre><code> interface IMoveable\n {\n public void Act();\n }\n\n interface IRollable\n {\n public void Act();\n }\n\n class Thing : IMoveable, IRollable\n {\n //TODO Roll/Move code here\n\n void IRollable.Act()\n {\n Roll();\n }\n\n void IMoveable.Act()\n {\n Move();\n }\n }\n</code></pre>\n"
},
{
"answer_id": 253083,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>This makes it more flexible for when there are collisions. In particular, look at <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx\" rel=\"noreferrer\"><code>IEnumerator</code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/78dfe2yb.aspx\" rel=\"noreferrer\"><code>IEnumerator<T></code></a> - they both have a <code>Current</code> property, but of different types. You <em>have</em> to use explicit interface implementation in order to implement both (and the generic form extends the non-generic form).</p>\n"
},
{
"answer_id": 253102,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 5,
"selected": true,
"text": "<p>Your example does <strong>not</strong> implement IFoo both implicitly and explicitly. You only implement IFoo.DoSometing() explicitly. You have a new method on your class called DoSomething(). It has nothing to do with IFoo.DoSomething, except that it has the same name and parameters.</p>\n"
},
{
"answer_id": 253200,
"author": "Morgan Cheng",
"author_id": 26349,
"author_profile": "https://Stackoverflow.com/users/26349",
"pm_score": 0,
"selected": false,
"text": "<p>Guys, Thanks for your answers.</p>\n\n<p>It turns out that \"C# class can inherits one interface in both implicit and explicit way at same time\" is actually a illusion. Actually, one class can inherit one interface for one time. </p>\n\n<p>In the original question, the \"DoSomething\" method seems \"implicitly implement\" interface IFoo (the method is actually generated by VS2008), but it is actually NOT. With explicit implementation of interface IFoo, the \"DoSomething\" method turns to be just normal method which has nothing to do with IFoo except with same signature.</p>\n\n<p>I still believe it is a tricky design of C#, and it is easy to use it mistakenly. Say, I have some code like this</p>\n\n<pre><code> Foo f = new Foo();\n f.DoSomething();\n</code></pre>\n\n<p>Now, I want to refactor it to below code. It seems perfectly OK, but the execution result is different.</p>\n\n<pre><code> Action<IFoo> func = foo => foo.DoSomething();\n func(f);\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
Today I happens to find that one C# class can inherit one interface both in implicit and explicit way. This surprises me. If C# works in this way, then one instance can behave differently when referenced in different way.
```
interface IFoo
{
void DoSomething();
}
class Foo : IFoo
{
#region IFoo Members
public void DoSomething()
{
Console.WriteLine("do something implicitly");
}
#endregion
#region IFoo Members
void IFoo.DoSomething()
{
Console.WriteLine("do something explicitly");
}
#endregion
}
Foo f = new Foo();
f.DoSomething();
((IFoo)f).DoSomething();
```
Above code runs and output
```
do something implicitly
do something explicitly
```
I believe that this design of C# make inconsistency of behavior. Perhaps it is mandatory that one C# class can inherit from one interface in implicit or expliict way, but not both.
Is there any reason that why C# is designed in such a way?
|
Your example does **not** implement IFoo both implicitly and explicitly. You only implement IFoo.DoSometing() explicitly. You have a new method on your class called DoSomething(). It has nothing to do with IFoo.DoSomething, except that it has the same name and parameters.
|
253,066 |
<p>How do you debug <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String)" rel="noreferrer">getResource</a>-style methods that are failing, returning null?</p>
<p>I am sure the file it's looking for is there, but it's returning NULL. How do I know what it is looking for to try to spot any mismatch?</p>
|
[
{
"answer_id": 253088,
"author": "boutta",
"author_id": 15108,
"author_profile": "https://Stackoverflow.com/users/15108",
"pm_score": 2,
"selected": false,
"text": "<p>You could use the Eclipse-debug-mode and set a breakpoint on the method that fails. From there you can go step by step down in the call tree until you see what fails.</p>\n\n<p>Most common is that the file isn't there because it wasn't copied there or isn't in the classpath etc...</p>\n"
},
{
"answer_id": 253093,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 2,
"selected": false,
"text": "<p>The getResource call is looking for a file relative to the class file.</p>\n\n<p>My first guess would be that when you have compiled you have forgotten to put the resource files into the compile folder. That's what I've been running on often.</p>\n"
},
{
"answer_id": 253185,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 0,
"selected": false,
"text": "<p>I've usually experience this whenever the ClassLoader changes.</p>\n\n<p>Depending on the exact context that an app is running ClassLoaders have different rules about when a resource file exists. For example in netbeans getResource is case insensitive, but in Sun's JRE it is.</p>\n\n<p>Although not directly answering your question, I thought you should know this (if you didn't already).</p>\n"
},
{
"answer_id": 253448,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 4,
"selected": false,
"text": "<p>Since <code>getResource()</code> searches the classpath (as others have mentioned), it might be helpful to dump the actual classpath being searched before your problemsome <code>getResource()</code> call:</p>\n\n<pre><code>log.debug(\"classpath is: \" + System.getProperty(\"java.class.path\"));\n\n//the line that is returning null\n... = Thread.currentThread().getContextClassLoader().getResource(\"foobar\");\n</code></pre>\n\n<p>What is probably happening is that the files/directories you think are on the classpath are actually not (perhaps an invalid path is being set somewhere along the way).</p>\n"
},
{
"answer_id": 256343,
"author": "Szundi",
"author_id": 22631,
"author_profile": "https://Stackoverflow.com/users/22631",
"pm_score": 0,
"selected": false,
"text": "<p>I think you should tell Eclipse or your favourite IDE where the JDK (JRE) source files can be found. Then you can step in the methods of the Java Runtime classes too.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
How do you debug [getResource](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource(java.lang.String))-style methods that are failing, returning null?
I am sure the file it's looking for is there, but it's returning NULL. How do I know what it is looking for to try to spot any mismatch?
|
Since `getResource()` searches the classpath (as others have mentioned), it might be helpful to dump the actual classpath being searched before your problemsome `getResource()` call:
```
log.debug("classpath is: " + System.getProperty("java.class.path"));
//the line that is returning null
... = Thread.currentThread().getContextClassLoader().getResource("foobar");
```
What is probably happening is that the files/directories you think are on the classpath are actually not (perhaps an invalid path is being set somewhere along the way).
|
253,075 |
<p>Is there a csh script/command to list all the files in source source tree which have line endings that show up as "^M" in emacs (under linux).</p>
<p>Thanks!</p>
|
[
{
"answer_id": 253084,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<pre><code>find . -type f -exec grep $'\\r' {} +\n</code></pre>\n\n<p>The <code>$'\\r'</code> probably requires bash to function correctly.</p>\n"
},
{
"answer_id": 253111,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 0,
"selected": false,
"text": "<pre><code>find . -type f -print | xargs grep 'cntl-M$'\n</code></pre>\n\n<p>where cntl-M has been entered by first entering cntl-V</p>\n"
},
{
"answer_id": 253130,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 4,
"selected": true,
"text": "<p>Based on my answer to <a href=\"https://stackoverflow.com/questions/204765/elegant-way-to-search-for-utf-8-files-with-bom#211855\">another question</a>:</p>\n\n<pre><code>fgrep -rl `echo -ne '\\r'` .\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5775/"
] |
Is there a csh script/command to list all the files in source source tree which have line endings that show up as "^M" in emacs (under linux).
Thanks!
|
Based on my answer to [another question](https://stackoverflow.com/questions/204765/elegant-way-to-search-for-utf-8-files-with-bom#211855):
```
fgrep -rl `echo -ne '\r'` .
```
|
253,099 |
<p>I want to examine the contents of a <code>std::vector</code> in GDB, how do I do it? Let's say it's a <code>std::vector<int></code> for the sake of simplicity.</p>
|
[
{
"answer_id": 253101,
"author": "John Carter",
"author_id": 8331,
"author_profile": "https://Stackoverflow.com/users/8331",
"pm_score": 8,
"selected": false,
"text": "<p>With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:</p>\n\n<pre><code>print *(myVector._M_impl._M_start)@myVector.size()\n</code></pre>\n\n<p>To print only the first N elements, do:</p>\n\n<pre><code>print *(myVector._M_impl._M_start)@N\n</code></pre>\n\n<p><strong>Explanation</strong></p>\n\n<p>This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:</p>\n\n<pre><code>myVector._M_impl._M_start \n</code></pre>\n\n<p>And the GDB command to print N elements of an array starting at pointer P is:</p>\n\n<pre><code>print P@N\n</code></pre>\n\n<p>Or, in a short form (for a standard .gdbinit):</p>\n\n<pre><code>p P@N\n</code></pre>\n"
},
{
"answer_id": 599934,
"author": "Nikhil",
"author_id": 66455,
"author_profile": "https://Stackoverflow.com/users/66455",
"pm_score": 4,
"selected": false,
"text": "<p>'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.</p>\n\n<p>1) Use GDB scripts from <a href=\"http://clith.com/gdb_stl_utils/\" rel=\"nofollow noreferrer\">http://clith.com/gdb_stl_utils/</a> These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.</p>\n\n<p>2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.</p>\n\n<p>3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions</p>\n"
},
{
"answer_id": 2123260,
"author": "Michał Oniszczuk",
"author_id": 257401,
"author_profile": "https://Stackoverflow.com/users/257401",
"pm_score": 7,
"selected": true,
"text": "<p>To view vector std::vector myVector contents, just type in GDB:</p>\n<pre><code>(gdb) print myVector\n</code></pre>\n<p>This will produce an output similar to:</p>\n<pre><code>$1 = std::vector of length 3, capacity 4 = {10, 20, 30}\n</code></pre>\n<p>To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on <a href=\"https://sourceware.org/gdb/wiki/STLSupport\" rel=\"nofollow noreferrer\">gdb wiki</a>.</p>\n<p>What is more, after installing above, this works well with <strong>Eclipse</strong> C++ debugger GUI (and any other IDE using GDB, as I think).</p>\n"
},
{
"answer_id": 25499805,
"author": "badeip",
"author_id": 327721,
"author_profile": "https://Stackoverflow.com/users/327721",
"pm_score": 4,
"selected": false,
"text": "<p>put the following in ~/.gdbinit</p>\n\n<pre><code>define print_vector\n if $argc == 2\n set $elem = $arg0.size()\n if $arg1 >= $arg0.size()\n printf \"Error, %s.size() = %d, printing last element:\\n\", \"$arg0\", $arg0.size()\n set $elem = $arg1 -1\n end\n print *($arg0._M_impl._M_start + $elem)@1\n else\n print *($arg0._M_impl._M_start)@$arg0.size()\n end\nend\n\ndocument print_vector\nDisplay vector contents\nUsage: print_vector VECTOR_NAME INDEX\nVECTOR_NAME is the name of the vector\nINDEX is an optional argument specifying the element to display\nend\n</code></pre>\n\n<p>After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this</p>\n\n<pre><code>gdb) help print_vector\nDisplay vector contents\nUsage: print_vector VECTOR_NAME INDEX\nVECTOR_NAME is the name of the vector\nINDEX is an optional argument specifying the element to display\n</code></pre>\n\n<p>Example usage:</p>\n\n<pre><code>(gdb) print_vector videoconfig_.entries 0\n$32 = {{subChannelId = 177 '\\261', sourceId = 0 '\\000', hasH264PayloadInfo = false, bitrate = 0, payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\\000', temporalLayers = 0 '\\000'}}\n</code></pre>\n"
},
{
"answer_id": 61823610,
"author": "Mike P",
"author_id": 201706,
"author_profile": "https://Stackoverflow.com/users/201706",
"pm_score": 0,
"selected": false,
"text": "<p>A little late to the party, so mostly a reminder to me next time I do this search! </p>\n\n<p>I have been able to use:</p>\n\n<pre><code>p/x *(&vec[2])@4\n</code></pre>\n\n<p>to print 4 elements (as hex) from <code>vec</code> starting at <code>vec[2]</code>.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331/"
] |
I want to examine the contents of a `std::vector` in GDB, how do I do it? Let's say it's a `std::vector<int>` for the sake of simplicity.
|
To view vector std::vector myVector contents, just type in GDB:
```
(gdb) print myVector
```
This will produce an output similar to:
```
$1 = std::vector of length 3, capacity 4 = {10, 20, 30}
```
To achieve above, you need to have gdb 7 (I tested it on gdb 7.01) and some python pretty-printer. Installation process of these is described on [gdb wiki](https://sourceware.org/gdb/wiki/STLSupport).
What is more, after installing above, this works well with **Eclipse** C++ debugger GUI (and any other IDE using GDB, as I think).
|
253,121 |
<p>In CSS, you can specify the spacing between table cells using the border-spacing property of a table.</p>
<p>However, this results in uniform spacing between columns and rows, and I am finding more situations where the designs I am using call for gaps between rows, but not columns, or visa versa.</p>
<p>If I have a solid background, I can simulate spacing using borders the same colour as the background colour.</p>
<p>I could also make a div (for example) the first child of every table cell, and using either padding or margins to get the desired results, but that is a lot of extra markup just to accommodate the style.</p>
<p>Given that that the data I am displaying is tabular data, is there a sensible way to achieve this style using tables?</p>
|
[
{
"answer_id": 253126,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "<p>You <em>can</em> specify different spacings for horizontal and vertical edges for <code>border-spacing</code> or related properties. Just specify more than one measurement. e.g.,</p>\n\n<pre><code>border-spacing: 1px 2px;\n</code></pre>\n"
},
{
"answer_id": 253228,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": false,
"text": "<p>In the <strong><em>general case</em></strong> where you may specify calues thayt may be applied globally or individually on a property (for example, \"padding\"), follow a simple pattern.</p>\n\n<ul>\n<li><p>If you specify a single value (e.g.\npadding:2px; ) the value is applied\nto the top, bottom, left and right\nof the object.</p></li>\n<li><p>If you specify two values (e.g.\npadding:2px 7px; ) the first value\nis applied to the top and bottom and\nthe second to the left and right.</p></li>\n<li><p>If you specify three values, the\nfirst value is applied to the top,\nthe second value to the left <em>and</em>\nright, and the final value to the\nbottom.</p></li>\n<li><p>If you specify four values (e.g.\npadding:1px,2px,3px,4px; ) the\nvalues are applied to top, right,\nbottom, left in that order (remember the order using the word TRouBLe).</p></li>\n</ul>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1577190/"
] |
In CSS, you can specify the spacing between table cells using the border-spacing property of a table.
However, this results in uniform spacing between columns and rows, and I am finding more situations where the designs I am using call for gaps between rows, but not columns, or visa versa.
If I have a solid background, I can simulate spacing using borders the same colour as the background colour.
I could also make a div (for example) the first child of every table cell, and using either padding or margins to get the desired results, but that is a lot of extra markup just to accommodate the style.
Given that that the data I am displaying is tabular data, is there a sensible way to achieve this style using tables?
|
You *can* specify different spacings for horizontal and vertical edges for `border-spacing` or related properties. Just specify more than one measurement. e.g.,
```
border-spacing: 1px 2px;
```
|
253,125 |
<p>Does anyone know how I can add a class to the link rendered using the Html.RouteLink helper method in ASP.Net MVC, it has the htmlAttributes object as the last parameter which I assumed I would be able to use, but since class is obviously a reserved word, I cannot supply this as one of the properties on the object.</p>
|
[
{
"answer_id": 253180,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 3,
"selected": false,
"text": "<p>Just use uppercase for html attribute, like this: </p>\n\n<pre><code><%= Html.RouteLink(\"Default\", \"Default\",null, new { Class=\"css_class\"}) %>\n</code></pre>\n"
},
{
"answer_id": 253369,
"author": "Robert Dean",
"author_id": 3396,
"author_profile": "https://Stackoverflow.com/users/3396",
"pm_score": 6,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code><%= Html.RouteLink(\"Default\", \"Default\",null, new { @class=\"css_class\"}) %>\n</code></pre>\n"
},
{
"answer_id": 10918321,
"author": "gavin",
"author_id": 934650,
"author_profile": "https://Stackoverflow.com/users/934650",
"pm_score": 0,
"selected": false,
"text": "<p>Please note that in the c# specificaiton, the @ special character is used in front of a variable name to allow the use of keyword as a variable name. So @class = \"css_class\" means setting value of the property called \"class\" to css_class</p>\n"
},
{
"answer_id": 40084797,
"author": "Chirag K",
"author_id": 2500692,
"author_profile": "https://Stackoverflow.com/users/2500692",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Robert, In my case(ASP.NET MVC) with razor syntax, I used it in another manner. </p>\n\n<p>@Html.RouteLink(\"Default\", \"Default\",null, new { @class=\"css_class\"})</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5160/"
] |
Does anyone know how I can add a class to the link rendered using the Html.RouteLink helper method in ASP.Net MVC, it has the htmlAttributes object as the last parameter which I assumed I would be able to use, but since class is obviously a reserved word, I cannot supply this as one of the properties on the object.
|
Try this:
```
<%= Html.RouteLink("Default", "Default",null, new { @class="css_class"}) %>
```
|
253,138 |
<p>Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.</p>
<p>We have tried a number of different approaches, all to no avail.</p>
<p>For example:</p>
<pre><code>myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
</code></pre>
<p>where someParameter is local to this method</p>
<p>The above will result in a compiler error:</p>
<blockquote>
<p>Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type</p>
</blockquote>
|
[
{
"answer_id": 253148,
"author": "François",
"author_id": 32379,
"author_profile": "https://Stackoverflow.com/users/32379",
"pm_score": 4,
"selected": false,
"text": "<pre><code>myControl.Invoke(new MethodInvoker(delegate() {...}))\n</code></pre>\n"
},
{
"answer_id": 253149,
"author": "Jelon",
"author_id": 2326,
"author_profile": "https://Stackoverflow.com/users/2326",
"pm_score": 4,
"selected": false,
"text": "<p>You need to create a delegate type. The keyword 'delegate' in the anonymous method creation is a bit misleading. You are not creating an anonymous delegate but an anonymous method. The method you created can be used in a delegate. Like this:</p>\n\n<pre><code>myControl.Invoke(new MethodInvoker(delegate() { (MyMethod(this, new MyEventArgs(someParameter)); }));\n</code></pre>\n"
},
{
"answer_id": 253150,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 9,
"selected": true,
"text": "<p>Because <code>Invoke</code>/<code>BeginInvoke</code> accepts <code>Delegate</code> (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; <code>MethodInvoker</code> (2.0) or <code>Action</code> (3.5) are common choices (note they have the same signature); like so:</p>\n\n<pre><code>control.Invoke((MethodInvoker) delegate {this.Text = \"Hi\";});\n</code></pre>\n\n<p>If you need to pass in parameters, then \"captured variables\" are the way:</p>\n\n<pre><code>string message = \"Hi\";\ncontrol.Invoke((MethodInvoker) delegate {this.Text = message;});\n</code></pre>\n\n<p>(caveat: you need to be a bit cautious if using captures <em>async</em>, but <em>sync</em> is fine - i.e. the above is fine)</p>\n\n<p>Another option is to write an extension method:</p>\n\n<pre><code>public static void Invoke(this Control control, Action action)\n{\n control.Invoke((Delegate)action);\n}\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>this.Invoke(delegate { this.Text = \"hi\"; });\n// or since we are using C# 3.0\nthis.Invoke(() => { this.Text = \"hi\"; });\n</code></pre>\n\n<p>You can of course do the same with <code>BeginInvoke</code>:</p>\n\n<pre><code>public static void BeginInvoke(this Control control, Action action)\n{\n control.BeginInvoke((Delegate)action);\n}\n</code></pre>\n\n<p>If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a <code>Form</code> base-class.</p>\n"
},
{
"answer_id": 253158,
"author": "Vokinneberg",
"author_id": 208062,
"author_profile": "https://Stackoverflow.com/users/208062",
"pm_score": 6,
"selected": false,
"text": "<p>Actually you do not need to use delegate keyword. Just pass lambda as parameter:</p>\n\n<pre><code>control.Invoke((MethodInvoker)(() => {this.Text = \"Hi\"; }));\n</code></pre>\n"
},
{
"answer_id": 285604,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 3,
"selected": false,
"text": "<p>I had problems with the other suggestions because I want to sometimes return values from my methods. If you try to use MethodInvoker with return values it doesn't seem to like it. So the solution I use is like this (very happy to hear a way to make this more succinct - I'm using c#.net 2.0):</p>\n\n<pre><code> // Create delegates for the different return types needed.\n private delegate void VoidDelegate();\n private delegate Boolean ReturnBooleanDelegate();\n private delegate Hashtable ReturnHashtableDelegate();\n\n // Now use the delegates and the delegate() keyword to create \n // an anonymous method as required\n\n // Here a case where there's no value returned:\n public void SetTitle(string title)\n {\n myWindow.Invoke(new VoidDelegate(delegate()\n {\n myWindow.Text = title;\n }));\n }\n\n // Here's an example of a value being returned\n public Hashtable CurrentlyLoadedDocs()\n {\n return (Hashtable)myWindow.Invoke(new ReturnHashtableDelegate(delegate()\n {\n return myWindow.CurrentlyLoadedDocs;\n }));\n }\n</code></pre>\n"
},
{
"answer_id": 4494513,
"author": "mhamrah",
"author_id": 30881,
"author_profile": "https://Stackoverflow.com/users/30881",
"pm_score": 3,
"selected": false,
"text": "<p>For the sake of completeness, this can also be accomplished via an Action method/anonymous method combination:</p>\n\n<pre><code>//Process is a method, invoked as a method group\nDispatcher.Current.BeginInvoke((Action) Process);\n//or use an anonymous method\nDispatcher.Current.BeginInvoke((Action)delegate => {\n SomeFunc();\n SomeOtherFunc();\n});\n</code></pre>\n"
},
{
"answer_id": 52291769,
"author": "Jürgen Steinblock",
"author_id": 98491,
"author_profile": "https://Stackoverflow.com/users/98491",
"pm_score": 0,
"selected": false,
"text": "<p>I never understood why this makes a difference for the compiler, but this is sufficient.</p>\n\n<pre><code>public static class ControlExtensions\n{\n public static void Invoke(this Control control, Action action)\n {\n control.Invoke(action);\n }\n}\n</code></pre>\n\n<p>Bonus: add some error handling, because it is likely that, if you are using <code>Control.Invoke</code> from a background thread you are updating the text / progress / enabled state of a control and don't care if the control is already disposed.</p>\n\n<pre><code>public static class ControlExtensions\n{\n public static void Invoke(this Control control, Action action)\n {\n try\n {\n if (!control.IsDisposed) control.Invoke(action);\n }\n catch (ObjectDisposedException) { }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 61158066,
"author": "Du D.",
"author_id": 1302259,
"author_profile": "https://Stackoverflow.com/users/1302259",
"pm_score": 1,
"selected": false,
"text": "<p>I like to use Action in place of MethodInvoker, it is shorter and looks cleaner.</p>\n\n<pre><code>Invoke((Action)(() => {\n DoSomething();\n}));\n\n// OR\n\nInvoke((Action)delegate {\n DoSomething();\n});\n</code></pre>\n\n<p>Eg.</p>\n\n<pre><code>// Thread-safe update on a form control\npublic void DisplayResult(string text){\n if (txtResult.InvokeRequired){\n txtResult.Invoke((Action)delegate {\n DisplayResult(text);\n });\n return;\n }\n\n txtResult.Text += text + \"\\r\\n\";\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
Having a bit of trouble with the syntax where we want to call a delegate anonymously within a Control.Invoke.
We have tried a number of different approaches, all to no avail.
For example:
```
myControl.Invoke(delegate() { MyMethod(this, new MyEventArgs(someParameter)); });
```
where someParameter is local to this method
The above will result in a compiler error:
>
> Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
>
>
>
|
Because `Invoke`/`BeginInvoke` accepts `Delegate` (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; `MethodInvoker` (2.0) or `Action` (3.5) are common choices (note they have the same signature); like so:
```
control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});
```
If you need to pass in parameters, then "captured variables" are the way:
```
string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});
```
(caveat: you need to be a bit cautious if using captures *async*, but *sync* is fine - i.e. the above is fine)
Another option is to write an extension method:
```
public static void Invoke(this Control control, Action action)
{
control.Invoke((Delegate)action);
}
```
then:
```
this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });
```
You can of course do the same with `BeginInvoke`:
```
public static void BeginInvoke(this Control control, Action action)
{
control.BeginInvoke((Delegate)action);
}
```
If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a `Form` base-class.
|
253,142 |
<p>I'd like to post some form variables into a classic ASP page. I don't want to have to alter the classic ASP pages, because of the amount of work that would need to be done, and the amount of pages that consume them.</p>
<p>The classic ASP page expects form variables Username and Userpassword to be submitted to them.</p>
<pre><code>username = Request.Form("UserName")
userpassword = Request.Form("Userpassword")
</code></pre>
<p>It then performs various actions and sets up sessions, going into an ASP application.</p>
<p>I want to submit these variables into the page from ASP.NET, but the login control is nested inside usercontrols and templates, so I can't get the form element's names to be "username" and "UserPassword".</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 253195,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 0,
"selected": false,
"text": "<p>I found this on <a href=\"http://www.jigar.net/articles/viewhtmlcontent78.aspx\" rel=\"nofollow noreferrer\">another site</a>. </p>\n\n<p>I will build up a small form with just the variables you want, and output it to the client and submit itself. It's pretty neat, but it comes with the problem of breaking the back button, and sending the password back to the client in a form unencrypted.</p>\n\n<pre><code>public class RemotePost{\n private System.Collections.Specialized.NameValueCollection Inputs \n = new System.Collections.Specialized.NameValueCollection() ;\n\n public string Url = \"\" ;\n public string Method = \"post\" ;\n public string FormName = \"form1\" ;\n\n public void Add( string name, string value ){\n Inputs.Add(name, value ) ;\n }\n\n public void Post(){\n System.Web.HttpContext.Current.Response.Clear() ;\n\n System.Web.HttpContext.Current.Response.Write( \"<html><head>\" ) ;\n\n System.Web.HttpContext.Current.Response.Write( string .Format( \"</head><body onload=\\\"document.{0}.submit()\\\">\" ,FormName)) ;\n\n System.Web.HttpContext.Current.Response.Write( string .Format( \"<form name=\\\"{0}\\\" method=\\\"{1}\\\" action=\\\"{2}\\\" >\" ,\n\n FormName,Method,Url)) ;\n for ( int i = 0 ; i< Inputs.Keys.Count ; i++){\n System.Web.HttpContext.Current.Response.Write( string .Format( \"<input name=\\\"{0}\\\" type=\\\"hidden\\\" value=\\\"{1}\\\">\" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;\n }\n System.Web.HttpContext.Current.Response.Write( \"</form>\" ) ;\n System.Web.HttpContext.Current.Response.Write( \"</body></html>\" ) ;\n System.Web.HttpContext.Current.Response.End() ;\n }\n} \n</code></pre>\n"
},
{
"answer_id": 253474,
"author": "HectorMac",
"author_id": 1400,
"author_profile": "https://Stackoverflow.com/users/1400",
"pm_score": 1,
"selected": false,
"text": "<p>Don't use the asp.net login control (if you are).</p>\n\n<p>Use simple html for the user name/password textboxes in your user control <strong><em>without</em></strong> runat=\"server\":</p>\n\n<pre><code><input type=\"text\" name=\"UserName\" />\n\n<input type=\"password\" name=\"Userpassword\" />\n\n<asp:Button ID=\"btnLogin\" runat=\"server\" PostBackUrl=\"Destination.asp\" />\n</code></pre>\n\n<p>Set the PostBackUrl property on the button to you classic asp url and all should be fine.</p>\n"
},
{
"answer_id": 256140,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 3,
"selected": true,
"text": "<p>You can't really \"forward\" a POST on, like you're wanting to do (in your OP). The client has to initiate the POST to your ASP page(s) (which the code in your second post is doing).</p>\n\n<hr>\n\n<p>Here's the self-POSTing code from your own reply so you can mark an answer, like you suggested:</p>\n\n<pre><code>public class RemotePost{\n private System.Collections.Specialized.NameValueCollection Inputs \n = new System.Collections.Specialized.NameValueCollection() ;\n\n public string Url = \"\" ;\n public string Method = \"post\" ;\n public string FormName = \"form1\" ;\n\n public void Add( string name, string value ){\n Inputs.Add(name, value ) ;\n }\n\n public void Post(){\n System.Web.HttpContext.Current.Response.Clear() ;\n\n System.Web.HttpContext.Current.Response.Write( \"<html><head>\" ) ;\n\n System.Web.HttpContext.Current.Response.Write( string .Format( \"</head><body onload=\\\"document.{0}.submit()\\\">\" ,FormName)) ;\n\n System.Web.HttpContext.Current.Response.Write( string .Format( \"<form name=\\\"{0}\\\" method=\\\"{1}\\\" action=\\\"{2}\\\" >\" ,\n\n FormName,Method,Url)) ;\n for ( int i = 0 ; i< Inputs.Keys.Count ; i++){\n System.Web.HttpContext.Current.Response.Write( string .Format( \"<input name=\\\"{0}\\\" type=\\\"hidden\\\" value=\\\"{1}\\\">\" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;\n }\n System.Web.HttpContext.Current.Response.Write( \"</form>\" ) ;\n System.Web.HttpContext.Current.Response.Write( \"</body></html>\" ) ;\n System.Web.HttpContext.Current.Response.End() ;\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253142",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
I'd like to post some form variables into a classic ASP page. I don't want to have to alter the classic ASP pages, because of the amount of work that would need to be done, and the amount of pages that consume them.
The classic ASP page expects form variables Username and Userpassword to be submitted to them.
```
username = Request.Form("UserName")
userpassword = Request.Form("Userpassword")
```
It then performs various actions and sets up sessions, going into an ASP application.
I want to submit these variables into the page from ASP.NET, but the login control is nested inside usercontrols and templates, so I can't get the form element's names to be "username" and "UserPassword".
Any ideas?
|
You can't really "forward" a POST on, like you're wanting to do (in your OP). The client has to initiate the POST to your ASP page(s) (which the code in your second post is doing).
---
Here's the self-POSTing code from your own reply so you can mark an answer, like you suggested:
```
public class RemotePost{
private System.Collections.Specialized.NameValueCollection Inputs
= new System.Collections.Specialized.NameValueCollection() ;
public string Url = "" ;
public string Method = "post" ;
public string FormName = "form1" ;
public void Add( string name, string value ){
Inputs.Add(name, value ) ;
}
public void Post(){
System.Web.HttpContext.Current.Response.Clear() ;
System.Web.HttpContext.Current.Response.Write( "<html><head>" ) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "</head><body onload=\"document.{0}.submit()\">" ,FormName)) ;
System.Web.HttpContext.Current.Response.Write( string .Format( "<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >" ,
FormName,Method,Url)) ;
for ( int i = 0 ; i< Inputs.Keys.Count ; i++){
System.Web.HttpContext.Current.Response.Write( string .Format( "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" ,Inputs.Keys[i],Inputs[Inputs.Keys[i]])) ;
}
System.Web.HttpContext.Current.Response.Write( "</form>" ) ;
System.Web.HttpContext.Current.Response.Write( "</body></html>" ) ;
System.Web.HttpContext.Current.Response.End() ;
}
}
```
|
253,157 |
<p>Is there a way to resize a <code>std::vector</code> to lower capacity when I no longer need previously reserved space?</p>
|
[
{
"answer_id": 253173,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 7,
"selected": true,
"text": "<p>Effective STL, by Scott Meyers, Item 17: Use the <code>swap</code> trick to trim excess capacity.</p>\n\n<pre><code>vector<Person>(persons).swap(persons);\n</code></pre>\n\n<p>After that, <code>persons</code> is \"shrunk to fit\".</p>\n\n<p>This relies on the fact that <code>vector</code>'s copy constructor allocates only as much as memory as needed for the elements being copied.</p>\n"
},
{
"answer_id": 253176,
"author": "philsquared",
"author_id": 32136,
"author_profile": "https://Stackoverflow.com/users/32136",
"pm_score": 3,
"selected": false,
"text": "<p>Create a new, temporary, vector from the existing one then call the swap method on the existing one, passing the temporary one in. Let the temporary (now with the old, oversized, buffer) go out of scope.</p>\n\n<p>Hey presto, your vector has exactly the right size for its contents.</p>\n\n<p>If this sounds like a lot of copying and allocation - bear in mind that this is what vector does every time it has to realloc past its current reserved limit anyway.</p>\n\n<p>[Edit]\nYes, I just said the same as Sebastien in more words. Another case of stackoverflow race-condition ;-)</p>\n"
},
{
"answer_id": 253182,
"author": "fulmicoton",
"author_id": 446497,
"author_profile": "https://Stackoverflow.com/users/446497",
"pm_score": -1,
"selected": false,
"text": "<p>You're looking for an equivalent of <a href=\"http://doc.qt.io/qt-4.8/qvector.html#squeeze\" rel=\"nofollow noreferrer\">QVector::squeeze</a> and I'm afraid it doesn't exist explicitely in the STL. \nGo for Sébastien's answer if it is correct for your STL implementation.</p>\n"
},
{
"answer_id": 9525865,
"author": "Alex Korban",
"author_id": 221619,
"author_profile": "https://Stackoverflow.com/users/221619",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using C++11, you can use <code>vec.shrink_to_fit()</code>. In VS2010 at least, that does the swap trick for you.</p>\n"
},
{
"answer_id": 20092836,
"author": "jimifiki",
"author_id": 512225,
"author_profile": "https://Stackoverflow.com/users/512225",
"pm_score": 2,
"selected": false,
"text": "<p>The swap trick is an effective way to reduce the capacity of an object, \nit swaps the content of my vector with a newly created one by copy construction: </p>\n\n<pre><code>vector<Person>(persons).swap(persons);\n</code></pre>\n\n<p>Notice that there is no guarantee that persons.capacity(); after the swap trick is equal to \nthe size: the capacity of vector(persons) is the capacity the library implementation \nreserves to vectors of size persons.size(). </p>\n\n<p>C++11 introduced <a href=\"http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/\" rel=\"nofollow noreferrer\">shrink_to_fit()</a>.</p>\n\n<p>shrink_to_fit() as well as the swap trick does not guarantee the capacity size is effectively \nreduced to the size of the vector.</p>\n\n<p>Anyway shrink_to_fit() can invalidate your iterators (if a reallocation happens) or cannot: \nit depends on the actual implementation of the library. </p>\n\n<p>Bear in mind that the swap trick requires persons.size() copy constructions of Person and \nperson.size() destructions. The shrink_to_fit() could avoid all this copying and could \nleave your iterators valid. Could. But from time to time it happens that shrink_to_fit() is implemented in \nterms of the swap trick... </p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23766/"
] |
Is there a way to resize a `std::vector` to lower capacity when I no longer need previously reserved space?
|
Effective STL, by Scott Meyers, Item 17: Use the `swap` trick to trim excess capacity.
```
vector<Person>(persons).swap(persons);
```
After that, `persons` is "shrunk to fit".
This relies on the fact that `vector`'s copy constructor allocates only as much as memory as needed for the elements being copied.
|
253,178 |
<p>I'm developing my first Word 2007 addin, and I've added an OfficeRibbon to my project. In a button-click handler, I'd like a reference to either the current <code>Word.Document</code> or <code>Word.Application</code>.</p>
<p>I'm trying to get a reference via the <code>OfficeRibbon.Context</code> property, which the documentation says should refer to the current <code>Application</code> object. However, it is always <code>null</code>.</p>
<p>Does anyone know either</p>
<p>a) if there is something I need to do to make <code>OfficeRibbon.Context</code> appear correctly populated?<br>
b) if there is some other way I can get a reference to the Word Application or active Word Document?</p>
<p>Notes:</p>
<ul>
<li><p>I'm using VS2008 SP1</p></li>
<li><p>The ribbon looks like it has initialized fine: The ribbon renders correctly in Word; I can step the debugger through both the constructor and the OnLoad members; Button click handlers execute correctly. </p></li>
<li><p>Here's <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.officeribbon.context.aspx?ppud=4" rel="nofollow noreferrer">the online help for this property</a>; </p></li>
</ul>
<blockquote>
<p><strong>OfficeRibbon.Context Property</strong></p>
<p><code>C#</code><br>
<code>public Object Context { get; internal set; }</code></p>
<p>An Object that represents the Inspector window or application instance that is associated with this OfficeRibbon object. </p>
<p><strong>Remarks</strong></p>
<p>In Outlook, this property refers to the Inspector window in which this OfficeRibbon is displayed.</p>
<p>In Excel, Word, and PowerPoint, this property returns the application instance in which this OfficeRibbon is displayed. </p>
</blockquote>
|
[
{
"answer_id": 256506,
"author": "shahkalpesh",
"author_id": 23574,
"author_profile": "https://Stackoverflow.com/users/23574",
"pm_score": 1,
"selected": false,
"text": "<p>While I dont know much about changes in Office 2007 word object model, here is my explanation using VBA knowledge.</p>\n\n<p>Application is a globally available object.\nAlso, Application.ActiveDocument should get you handle to the current document.</p>\n\n<p>Speculating: How are you trying to add the ribbon?</p>\n"
},
{
"answer_id": 895455,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 3,
"selected": true,
"text": "<p>I also encountered this problem while creating an Excel 2007 AddIn using VS2008 SP1. The workaround I used was to store the Application in an <code>internal static</code> property in the main AddIn class and then reference it in the event handler in my ribbon:</p>\n\n<pre><code>public partial class ThisAddIn\n{\n internal static Application Context { get; private set; }\n\n private void ThisAddIn_Startup(object sender, System.EventArgs e)\n {\n Context = Application;\n }\n ...\n}\n\npublic partial class MyRibbon : OfficeRibbon\n{\n private void button1_Click(object sender, RibbonControlEventArgs e)\n {\n DoStuffWithApplication(ThisAddIn.Context);\n }\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 896622,
"author": "Michael Regan",
"author_id": 1027,
"author_profile": "https://Stackoverflow.com/users/1027",
"pm_score": 2,
"selected": false,
"text": "<p>Try referencing the document with:</p>\n\n<pre><code>Globals.ThisDocument.[some item]\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bhczd18c.aspx\" rel=\"nofollow noreferrer\">MSDN Reference</a></p>\n"
},
{
"answer_id": 11023497,
"author": "Lukas Winzenried",
"author_id": 937411,
"author_profile": "https://Stackoverflow.com/users/937411",
"pm_score": 2,
"selected": false,
"text": "<p>Get it from:</p>\n\n<p><code>Globals.ThisAddIn.Application</code></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6722/"
] |
I'm developing my first Word 2007 addin, and I've added an OfficeRibbon to my project. In a button-click handler, I'd like a reference to either the current `Word.Document` or `Word.Application`.
I'm trying to get a reference via the `OfficeRibbon.Context` property, which the documentation says should refer to the current `Application` object. However, it is always `null`.
Does anyone know either
a) if there is something I need to do to make `OfficeRibbon.Context` appear correctly populated?
b) if there is some other way I can get a reference to the Word Application or active Word Document?
Notes:
* I'm using VS2008 SP1
* The ribbon looks like it has initialized fine: The ribbon renders correctly in Word; I can step the debugger through both the constructor and the OnLoad members; Button click handlers execute correctly.
* Here's [the online help for this property](http://msdn.microsoft.com/en-us/library/microsoft.office.tools.ribbon.officeribbon.context.aspx?ppud=4);
>
> **OfficeRibbon.Context Property**
>
>
> `C#`
>
> `public Object Context { get; internal set; }`
>
>
> An Object that represents the Inspector window or application instance that is associated with this OfficeRibbon object.
>
>
> **Remarks**
>
>
> In Outlook, this property refers to the Inspector window in which this OfficeRibbon is displayed.
>
>
> In Excel, Word, and PowerPoint, this property returns the application instance in which this OfficeRibbon is displayed.
>
>
>
|
I also encountered this problem while creating an Excel 2007 AddIn using VS2008 SP1. The workaround I used was to store the Application in an `internal static` property in the main AddIn class and then reference it in the event handler in my ribbon:
```
public partial class ThisAddIn
{
internal static Application Context { get; private set; }
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Context = Application;
}
...
}
public partial class MyRibbon : OfficeRibbon
{
private void button1_Click(object sender, RibbonControlEventArgs e)
{
DoStuffWithApplication(ThisAddIn.Context);
}
...
}
```
|
253,211 |
<p>I'm working on a C# library which offloads certain work tasks to the GPU using NVIDIA's CUDA. An example of this is adding two arrays together using extension methods:</p>
<pre><code>float[] a = new float[]{ ... }
float[] b = new float[]{ ... }
float[] c = a.Add(b);
</code></pre>
<p>The work in this code is done on the GPU. However, I would like it to be done asynchronously such that only when the result is needed will the code running on the CPU block (if the result is not finished on the GPU yet). To do this I've created an ExecutionResult class which hides the asynchronous execution. In use this looks as follows:</p>
<pre><code>float[] a = new float[]{ ... }
float[] b = new float[]{ ... }
ExecutionResult res = a.Add(b);
float[] c = res; //Implicit converter
</code></pre>
<p>At the last line the program blocks if the data is done ready yet. I'm not certain of the best way to implement this blocking behavior inside the ExecutionResult class as I'm not very experienced with synchronizing threads and those sorts of things.</p>
<pre><code>public class ExecutionResult<T>
{
private T[] result;
private long computed = 0;
internal ExecutionResult(T[] a, T[] b, Action<T[], T[], Action<T[]>> f)
{
f(a, b, UpdateData); //Asych call - 'UpdateData' is the callback method
}
internal void UpdateData(T[] data)
{
if (Interlocked.Read(ref computed) == 0)
{
result = data;
Interlocked.Exchange(ref computed, 1);
}
}
public static implicit operator T[](ExecutionResult<T> r)
{
//This is obviously a stupid way to do it
while (Interlocked.Read(ref r.computed) == 0)
{
Thread.Sleep(1);
}
return result;
}
}
</code></pre>
<p>The Action passed to the constructor is an asynchronous method which performs the actual work on the GPU. The nested Action is the asynchronous callback method.</p>
<p>My main concern is how to best/most elegantly handle the waiting done in the converter but also if there are more appropriate ways to attack the problem as a whole. Just leave a comment if there is something I need to elaborate or explain further.</p>
|
[
{
"answer_id": 253214,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>I wonder if you couldn't use the regular <code>Delegate.BeginInvoke</code>/<code>Delegate.EndInvoke</code> here? If not, then a wait handle (such as a <code>ManualResetEvent</code>) might be an option:</p>\n\n<pre><code>using System.Threading;\nstatic class Program {\n static void Main()\n {\n ThreadPool.QueueUserWorkItem(DoWork);\n\n System.Console.WriteLine(\"Main: waiting\");\n wait.WaitOne();\n System.Console.WriteLine(\"Main: done\");\n }\n static void DoWork(object state)\n {\n System.Console.WriteLine(\"DoWork: working\");\n Thread.Sleep(5000); // simulate work\n System.Console.WriteLine(\"DoWork: done\");\n wait.Set();\n }\n static readonly ManualResetEvent wait = new ManualResetEvent(false);\n\n}\n</code></pre>\n\n<p>Note that you can do this just using object if you really want:</p>\n\n<pre><code>using System.Threading;\nstatic class Program {\n static void Main()\n {\n object syncObj = new object();\n lock (syncObj)\n {\n ThreadPool.QueueUserWorkItem(DoWork, syncObj);\n\n System.Console.WriteLine(\"Main: waiting\");\n Monitor.Wait(syncObj);\n System.Console.WriteLine(\"Main: done\");\n }\n }\n static void DoWork(object syncObj)\n {\n\n System.Console.WriteLine(\"DoWork: working\");\n Thread.Sleep(5000); // simulate work\n System.Console.WriteLine(\"DoWork: done\");\n lock (syncObj)\n {\n Monitor.Pulse(syncObj);\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 253215,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>It's not clear to me how much this is a framework you're implementing and how much you're calling into other code, but I would follow the <a href=\"http://msdn.microsoft.com/en-us/library/ms228975.aspx\" rel=\"nofollow noreferrer\">\"normal\" async pattern</a> in .NET as far as possible.</p>\n"
},
{
"answer_id": 258281,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 2,
"selected": false,
"text": "<p>The solution I found to the problem is to pass a function to the ExecutionResult constructor which does two things. When run, it starts the asynchronous work and in addition, it returns another function which returns the desired result:</p>\n\n<pre><code>private Func<T[]> getResult;\n\ninternal ExecutionResult(T[] a, T[] b, Func<T[], T[], Func<T[]>> asynchBinaryFunction)\n{\n getResult = asynchUnaryFunction(a);\n}\n\npublic static implicit operator T[](ExecutionResult<T> r)\n{\n return r.getResult();\n}\n</code></pre>\n\n<p>The 'getResult' function blocks until the data has been calculated and fetched from the GPU. This works well with how the CUDA driver API is structured.</p>\n\n<p>It is a quite clean and simple solution. Since C# allows anonymous functions to be created with access to the local scope it is simply a matter of replacing the blocking part of a method passed to the ExecutionResult constructor such that...</p>\n\n<pre><code> ...\n\n status = LaunchGrid(func, length);\n\n //Fetch result\n float[] c = new float[length];\n status = CUDADriver.cuMemcpyDtoH(c, ptrA, byteSize);\n status = Free(ptrA, ptrB);\n\n return c;\n}\n</code></pre>\n\n<p>becomes...</p>\n\n<pre><code> ...\n\n status = LaunchGrid(func, length);\n\n return delegate\n {\n float[] c = new float[length];\n CUDADriver.cuMemcpyDtoH(c, ptrA, byteSize); //Blocks until work is done\n Free(ptrA, ptrB);\n return c;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 1449819,
"author": "Danny Varod",
"author_id": 38368,
"author_profile": "https://Stackoverflow.com/users/38368",
"pm_score": 0,
"selected": false,
"text": "<p>Using cudaThreadSyncronize() or memcpy() you can preform synchronous operations - suitable for Invoke().<BR>\n<BR>\nCUDA also lets you request an asynchronic memory transfer using callAsync() / sync() - suitable for Begin/EndInvoke() using callAsync().</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4055/"
] |
I'm working on a C# library which offloads certain work tasks to the GPU using NVIDIA's CUDA. An example of this is adding two arrays together using extension methods:
```
float[] a = new float[]{ ... }
float[] b = new float[]{ ... }
float[] c = a.Add(b);
```
The work in this code is done on the GPU. However, I would like it to be done asynchronously such that only when the result is needed will the code running on the CPU block (if the result is not finished on the GPU yet). To do this I've created an ExecutionResult class which hides the asynchronous execution. In use this looks as follows:
```
float[] a = new float[]{ ... }
float[] b = new float[]{ ... }
ExecutionResult res = a.Add(b);
float[] c = res; //Implicit converter
```
At the last line the program blocks if the data is done ready yet. I'm not certain of the best way to implement this blocking behavior inside the ExecutionResult class as I'm not very experienced with synchronizing threads and those sorts of things.
```
public class ExecutionResult<T>
{
private T[] result;
private long computed = 0;
internal ExecutionResult(T[] a, T[] b, Action<T[], T[], Action<T[]>> f)
{
f(a, b, UpdateData); //Asych call - 'UpdateData' is the callback method
}
internal void UpdateData(T[] data)
{
if (Interlocked.Read(ref computed) == 0)
{
result = data;
Interlocked.Exchange(ref computed, 1);
}
}
public static implicit operator T[](ExecutionResult<T> r)
{
//This is obviously a stupid way to do it
while (Interlocked.Read(ref r.computed) == 0)
{
Thread.Sleep(1);
}
return result;
}
}
```
The Action passed to the constructor is an asynchronous method which performs the actual work on the GPU. The nested Action is the asynchronous callback method.
My main concern is how to best/most elegantly handle the waiting done in the converter but also if there are more appropriate ways to attack the problem as a whole. Just leave a comment if there is something I need to elaborate or explain further.
|
It's not clear to me how much this is a framework you're implementing and how much you're calling into other code, but I would follow the ["normal" async pattern](http://msdn.microsoft.com/en-us/library/ms228975.aspx) in .NET as far as possible.
|
253,212 |
<p>How are assertions done in c++? Example code is appreciated.</p>
|
[
{
"answer_id": 253219,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 3,
"selected": false,
"text": "<p>Assertion are boolean expressions which should typically always be true.</p>\n\n<p>They are used to ensure what you expected is also what happens.</p>\n\n<pre><code>void some_function(int age)\n{\n assert(age > 0);\n}\n</code></pre>\n\n<p>You wrote the function to deal with ages, you also 'know' for sure you're always passing sensible arguments, then you use an assert. It's like saying \"I know this can never go wrong, but if it does, I want to know\", because, well, everyone makes mistakes.</p>\n\n<p>So it's not to check for sensible user input, if there are scenario's where something can go wrong, don't use an assert. Do real checks and deal with the errors.</p>\n\n<p>Asserts are typically only for debug builds, so don't put code with side effects in asserts. </p>\n"
},
{
"answer_id": 253220,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 1,
"selected": false,
"text": "<p>An assertion is something you add to your program that causes the program to stop immediately if a condition is met, and display an error message. You generally use them for things which you believe can never happen in your code. </p>\n"
},
{
"answer_id": 253223,
"author": "andygeers",
"author_id": 4397,
"author_profile": "https://Stackoverflow.com/users/4397",
"pm_score": 6,
"selected": true,
"text": "<p>Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special \"debug\" build of your application, so they won't slow down the final release version.</p>\n\n<p>Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:</p>\n\n<pre><code>#include <assert.h>\n\nvoid function(int* pointer_arg)\n{\n assert(pointer_arg != NULL);\n\n ...\n}\n</code></pre>\n\n<p>An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:</p>\n\n<pre><code>assert(a++ == 5);\n</code></pre>\n\n<p>Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:</p>\n\n<pre><code>assert((a == 5) && \"a has the wrong value!!\");\n</code></pre>\n"
},
{
"answer_id": 253224,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a <a href=\"http://en.wikipedia.org/wiki/Assert\" rel=\"nofollow noreferrer\">definition</a> of what an assertion is and <a href=\"http://www.cplusplus.com/reference/clibrary/cassert/assert.html\" rel=\"nofollow noreferrer\">here</a> is some sample code. In a nutshell an assertion is a way for a developer to test his (or her) assumptions about the state of the code at any given point. For example, if you were doing the following code:</p>\n\n<pre><code>mypointer->myfunct();\n</code></pre>\n\n<p>You probably want to assert that mypointer is not NULL because that's your assumption--that mypointer will never be NULL before the call. </p>\n"
},
{
"answer_id": 253225,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 2,
"selected": false,
"text": "<p>Assertions are statements allowing you to test any assumptions you might have in your program. This is especially useful to document your program logic (preconditions and postconditions). Assertions that fail usually throw runtime errors, and are signs that something is VERY wrong with your program - your assertion failed because something you assumed to be true was not. The usual reasons are: there is a flaw in your function's logic, or the caller of your function passed you bad data.</p>\n"
},
{
"answer_id": 253227,
"author": "SmacL",
"author_id": 22564,
"author_profile": "https://Stackoverflow.com/users/22564",
"pm_score": 3,
"selected": false,
"text": "<p>Assertions are used to verify design assumptions, usually in terms of input parameters and return results. For example</p>\n\n<pre><code>// Given customer and product details for a sale, generate an invoice\n\nInvoice ProcessOrder(Customer Cust,Product Prod)\n{\n assert(IsValid(Cust));\n assert(IsValid(Prod);\n'\n'\n'\n assert(IsValid(RetInvoice))\n return(RetInvoice);\n\n}\n</code></pre>\n\n<p>The assert statements aren't required for the code to run, but they check the validity of the input and output. If the input is invalid, there is a bug in the calling function. If the input is valid and output is invalid, there is a bug in this code. See <a href=\"http://en.wikipedia.org/wiki/Design_by_contract\" rel=\"nofollow noreferrer\">design by contract</a> for more details of this use of asserts.</p>\n\n<p>Edit: As pointed out in other posts, the default implementation of assert is not included in the release run-time. A common practice that many would use, including myself, is to replace it with a version that is included in the release build, but is only called in a diagnostics mode. This enables proper regression testing on release builds with full assertion checking. My version is as follows;</p>\n\n<pre><code>extern void _my_assert(void *, void *, unsigned);\n\n#define myassert(exp) \\\n{ \\\n if (InDiagnostics) \\\n if ( !(exp) ) \\\n _my_assert(#exp, __FILE__, __LINE__); \\\n} \\\n</code></pre>\n\n<p>There is a small runtime overhead in this technique, but it makes tracking any bugs that have made it into the field much easier.</p>\n"
},
{
"answer_id": 253280,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 2,
"selected": false,
"text": "<p>Use assertions to check for \"can't happen\" situations.</p>\n\n<p>Typical usage: check against invalid/impossible arguments at the top of a function.</p>\n\n<p>Seldom seen, but still useful: loop invariants and postconditions.</p>\n"
},
{
"answer_id": 254094,
"author": "Don Wakefield",
"author_id": 3778,
"author_profile": "https://Stackoverflow.com/users/3778",
"pm_score": 1,
"selected": false,
"text": "<p>This doesn't address the <em>assert</em> facility which has come down to us from early C days, but you should also be aware of <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_staticassert.html\" rel=\"nofollow noreferrer\">Boost StaticAssert</a> functionality, in the event that your projects can use Boost.</p>\n\n<p>The standard C/C++ assert works during runtime. The Boost StaticAssert facility enables you to make some classes of assertions at compile time, catching logic errors and the like even earlier.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22076/"
] |
How are assertions done in c++? Example code is appreciated.
|
Asserts are a way of explicitly checking the assumptions that your code makes, which helps you track down lots of bugs by narrowing down what the possible problems could be. They are typically only evaluated in a special "debug" build of your application, so they won't slow down the final release version.
Let's say you wrote a function that took a pointer as an argument. There's a good chance that your code will assume that the pointer is non-NULL, so why not explicitly check that with an assertion? Here's how:
```
#include <assert.h>
void function(int* pointer_arg)
{
assert(pointer_arg != NULL);
...
}
```
An important thing to note is that the expressions you assert must never have side effects, since they won't be present in the release build. So never do something like this:
```
assert(a++ == 5);
```
Some people also like to add little messages into their assertions to help give them meaning. Since a string always evaulates to true, you could write this:
```
assert((a == 5) && "a has the wrong value!!");
```
|
253,226 |
<p>I have an interface - here's a nicely contrived version as an example:</p>
<pre><code>public interface Particle {
enum Charge {
POSITIVE, NEGATIVE
}
Charge getCharge();
double getMass();
etc...
}
</code></pre>
<p>Is there any difference in how implementations of this would behave if I defined the <code>Charge</code> enum as static - i.e. does this have any effect:</p>
<pre><code>public interface Particle {
static enum Charge {
POSITIVE, NEGATIVE
}
Charge getCharge();
double getMass();
etc...
}
</code></pre>
|
[
{
"answer_id": 253239,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>No, it makes no difference. From the <a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-9.html#jls-9.5\" rel=\"noreferrer\">language spec, section 9.5</a>:</p>\n\n<blockquote>\n <p>Interfaces may contain member type\n declarations (<a href=\"http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.5\" rel=\"noreferrer\">§8.5</a>). A member type\n declaration in an interface is\n implicitly <code>static</code> and <code>public</code>.</p>\n</blockquote>\n"
},
{
"answer_id": 253282,
"author": "idrosid",
"author_id": 17876,
"author_profile": "https://Stackoverflow.com/users/17876",
"pm_score": 7,
"selected": true,
"text": "<p>No, it makes no difference. However the reason is not because it is a member declaration inside an interface, as Jon says. The real reason is according to language spec (<strong>8.9</strong>) that </p>\n\n<blockquote>\n <p>Nested enum types are implicitly\n static. It is permissable to\n explicitly declare a nested enum type\n to be static.</p>\n</blockquote>\n\n<p>At the following example static does not make any difference either (even though we have no interface):</p>\n\n<pre><code>public class A {\n enum E {A,B};\n}\n\npublic class A {\n static enum E {A,B};\n}\n</code></pre>\n\n<p>Another example with a nested <strong>private</strong> enum (not implicitly public).</p>\n\n<pre><code>public class A {\n private static enum E {A,B}\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1853/"
] |
I have an interface - here's a nicely contrived version as an example:
```
public interface Particle {
enum Charge {
POSITIVE, NEGATIVE
}
Charge getCharge();
double getMass();
etc...
}
```
Is there any difference in how implementations of this would behave if I defined the `Charge` enum as static - i.e. does this have any effect:
```
public interface Particle {
static enum Charge {
POSITIVE, NEGATIVE
}
Charge getCharge();
double getMass();
etc...
}
```
|
No, it makes no difference. However the reason is not because it is a member declaration inside an interface, as Jon says. The real reason is according to language spec (**8.9**) that
>
> Nested enum types are implicitly
> static. It is permissable to
> explicitly declare a nested enum type
> to be static.
>
>
>
At the following example static does not make any difference either (even though we have no interface):
```
public class A {
enum E {A,B};
}
public class A {
static enum E {A,B};
}
```
Another example with a nested **private** enum (not implicitly public).
```
public class A {
private static enum E {A,B}
}
```
|
253,238 |
<p>When designing user table what would be the must have fields from the security/user authentication point of view for a Web based Application (.NET and SqlServer 2005)</p>
<p>I came with with the following fields:</p>
<pre><code>userID
username -- preferably email
passwordHash
onceUsePassword -- to indicate that the password should be changed after login
alternativeContactEmail
userStatusID -- FK to a lookup table with statuses like: active, diabled etc
dateCreated
dateUpdated
lastPasswordUpdate
lastLogon
-- and then the rest like :forename, surname etc which are not of the interest in this question
</code></pre>
<p>Am I missing something? </p>
<p>Is standard identity (INT) sufficient for userID or should the GUID be used instead (the userID is not going to be exposed anywhere)?</p>
<p><strong>EDIT:</strong> </p>
<ul>
<li>I am limited to the use of .NET 1.1
(don't ask...) </li>
<li>The salt info will be merged with passwordHash</li>
<li>the account would be unlocked by sending a temporary, single use system generated password to the user email address (hence onceUsePassword field)</li>
</ul>
|
[
{
"answer_id": 253241,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 3,
"selected": true,
"text": "<p>Why not just use the built-in SQL Membership Provider if you're using SQL Server anyway? It's much better than rolling your own since it's been tested by a lot of people. </p>\n\n<p>In any case, you should think about adding a salt field your table.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Salt_(cryptography)\" rel=\"nofollow noreferrer\">Salting</a></p>\n\n<p>Update:\n.NET 1.1? I guess that answers my question. Is your application for the consumption of the general public? If so, you might want to add a way for them to unlock their accounts via a secret question.</p>\n"
},
{
"answer_id": 253313,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>onceUsePassword -- to indicate that\n the password should be changed after\n login</p>\n</blockquote>\n\n<p>If you have to explain it that much, you should rename it. Something like \"forceChangePasswordOnLogin\".</p>\n"
},
{
"answer_id": 253320,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 1,
"selected": false,
"text": "<p>You should add a \"salt\" field to use <a href=\"http://en.wikipedia.org/wiki/Password_salting\" rel=\"nofollow noreferrer\">password salting</a> to avoid dictionary attacks with <a href=\"http://en.wikipedia.org/wiki/Rainbow_table\" rel=\"nofollow noreferrer\">rainbow tables</a> if your database ever got compromised.</p>\n\n<p>I'm not sure what you mean by \"The salt info will be merged with passwordHash\". Does that mean that the same salt is used for all password hashs? Would make more sense to generate a random salt for each hash, and store it in a separate field.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241/"
] |
When designing user table what would be the must have fields from the security/user authentication point of view for a Web based Application (.NET and SqlServer 2005)
I came with with the following fields:
```
userID
username -- preferably email
passwordHash
onceUsePassword -- to indicate that the password should be changed after login
alternativeContactEmail
userStatusID -- FK to a lookup table with statuses like: active, diabled etc
dateCreated
dateUpdated
lastPasswordUpdate
lastLogon
-- and then the rest like :forename, surname etc which are not of the interest in this question
```
Am I missing something?
Is standard identity (INT) sufficient for userID or should the GUID be used instead (the userID is not going to be exposed anywhere)?
**EDIT:**
* I am limited to the use of .NET 1.1
(don't ask...)
* The salt info will be merged with passwordHash
* the account would be unlocked by sending a temporary, single use system generated password to the user email address (hence onceUsePassword field)
|
Why not just use the built-in SQL Membership Provider if you're using SQL Server anyway? It's much better than rolling your own since it's been tested by a lot of people.
In any case, you should think about adding a salt field your table.
[Salting](http://en.wikipedia.org/wiki/Salt_(cryptography))
Update:
.NET 1.1? I guess that answers my question. Is your application for the consumption of the general public? If so, you might want to add a way for them to unlock their accounts via a secret question.
|
253,242 |
<p>I have a query where i have a date column (time) which tells about "IN" & "OUT" timing of the people attendance by this single column</p>
<p>My queries are :-</p>
<p>1) How to get the daily attendance of each employee
2) How to come to know if the employee is present less than 5 hours</p>
<p>Please let me know the queries in SQL server.</p>
|
[
{
"answer_id": 253249,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 0,
"selected": false,
"text": "<pre><code> select \n datediff(minute, TimeFrom, TimeTo) as AttendedTimeInMinutes,\n case when datediff(minute, sTimeFrom, sTimeTo) < 5 * 60 \n then \n 'less than 5 hours' \n else '5 hours or more' \n end\n from YourTable\n</code></pre>\n"
},
{
"answer_id": 253250,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 0,
"selected": false,
"text": "<p>To find the difference between two datetimes you can use the following:</p>\n\n<pre><code>SELECT Datepart(hour, dateTimeEnd - dateTimeStart)\n</code></pre>\n\n<p>The DatePart function returns part of a date time variable, and the dateTimeEnd - dateTimeStart returns the difference between two dates as a new DateTime</p>\n"
},
{
"answer_id": 253310,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to group the query by the user and the items for a particular day then compare the maximum and minimum values, e.g. </p>\n\n<pre><code>declare @users table (\n UserId int, \n DateColumn datetime\n)\n\ninsert into @users values (1, '2008-10-31 15:15') \ninsert into @users values (1, '2008-10-31 10:30') \ninsert into @users values (1, '2008-10-30 16:15') \ninsert into @users values (1, '2008-10-30 10:30') \n\nselect\n UserID\n , cast(dt as datetime) dt\n , [in]\n , [out]\n , case when datepart(hour, [out]-[in]) >= 5 then 'yes' else 'no' end [5Hours?], \n , cast(datediff(minute, [in], [out]) as float)/60 [hours] \nfrom (\n select\n UserID\n , convert(varchar, DateColumn, 112) dt\n , min(DateColumn) [in]\n , max(DateColumn) [out] \n from @users \n group by \n UserID, convert(varchar, DateColumn, 112) \n ) a \n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a query where i have a date column (time) which tells about "IN" & "OUT" timing of the people attendance by this single column
My queries are :-
1) How to get the daily attendance of each employee
2) How to come to know if the employee is present less than 5 hours
Please let me know the queries in SQL server.
|
You'll need to group the query by the user and the items for a particular day then compare the maximum and minimum values, e.g.
```
declare @users table (
UserId int,
DateColumn datetime
)
insert into @users values (1, '2008-10-31 15:15')
insert into @users values (1, '2008-10-31 10:30')
insert into @users values (1, '2008-10-30 16:15')
insert into @users values (1, '2008-10-30 10:30')
select
UserID
, cast(dt as datetime) dt
, [in]
, [out]
, case when datepart(hour, [out]-[in]) >= 5 then 'yes' else 'no' end [5Hours?],
, cast(datediff(minute, [in], [out]) as float)/60 [hours]
from (
select
UserID
, convert(varchar, DateColumn, 112) dt
, min(DateColumn) [in]
, max(DateColumn) [out]
from @users
group by
UserID, convert(varchar, DateColumn, 112)
) a
```
|
253,247 |
<p>I have an animation that I'm displaying using a UIImageView:</p>
<pre><code>imageView.animationImages = myImages;
imageView.animationDuration = 3;
[imageView startAnimating];
</code></pre>
<p>I know I can stop it using stopAnimating, but what I want is to be able to pause it. The reason is that when you call stop, none of your animation images are displayed, whereas I would like the last one that is up at the time when I hit a button to stay up.</p>
<p>I have tried setting the duration to a much larger number, but that causes all the images to disappear as well. There must be a really basic way to do this?</p>
|
[
{
"answer_id": 253349,
"author": "Dan",
"author_id": 9774,
"author_profile": "https://Stackoverflow.com/users/9774",
"pm_score": -1,
"selected": false,
"text": "<p>Maybe you can take a screenshot of the last animated image and display that?</p>\n"
},
{
"answer_id": 255109,
"author": "rustyshelf",
"author_id": 6044,
"author_profile": "https://Stackoverflow.com/users/6044",
"pm_score": 4,
"selected": true,
"text": "<p>Hmmm...since no one seems to know I guess it's not possible. </p>\n\n<p>I went ahead and wrote my own <code>UIView</code>, with a <code>UIImageView</code> <code>subview</code>, that uses an <code>NSTimer</code> to switch between images. The advantage of this is that I can pause and resume the timer at my leisure, and performance doesn't seem to be an issue.</p>\n"
},
{
"answer_id": 624980,
"author": "mazniak",
"author_id": 42523,
"author_profile": "https://Stackoverflow.com/users/42523",
"pm_score": 4,
"selected": false,
"text": "<p>This code will pause an animated object at its current position in the animation process. If you record other variables like the time or progress or whatever you need, it should be fairly trivial to resume the animation again.</p>\n\n<pre><code>UIView *viewBeingAnimated = //your view that is being animated\nviewBeingAnimated.frame = [[viewBeingAnimated.layer presentationLayer] frame];\n[viewBeingAnimated.layer removeAllAnimations];\n//when user unpauses, create new animation from current position.\n</code></pre>\n"
},
{
"answer_id": 1628560,
"author": "oddmeter",
"author_id": 166365,
"author_profile": "https://Stackoverflow.com/users/166365",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to set the image property as well as the <code>animationImages</code> property. Doing this will display the static image when the <code>UIImageView</code> has its animations stopped.</p>\n\n<p>Assuming your class is a subclass of <code>UIImageView</code> and have an <code>NSMutableArray</code> of images, do the following:</p>\n\n<pre><code>self.animationImages = images;\n//yes, I'm skipping the step to check and make sure you have at least one\n//element in your array\nself.image = [images objectAtIndex: 0];\n</code></pre>\n"
},
{
"answer_id": 9241109,
"author": "SW_Cali",
"author_id": 838813,
"author_profile": "https://Stackoverflow.com/users/838813",
"pm_score": 2,
"selected": false,
"text": "<p>@oddmeter just a little edit:</p>\n\n<pre><code> animatedView.animationImages = images; //images is your array\n [animatedView startAnimating];\n\n\n //Then when you need to pause;\n\n[animatedView stopAnimating]; //Important!!\n animatedView.image = [images objectAtIndex: 0];\n</code></pre>\n"
},
{
"answer_id": 9794053,
"author": "Mihai Timar",
"author_id": 757408,
"author_profile": "https://Stackoverflow.com/users/757408",
"pm_score": 2,
"selected": false,
"text": "<p>This should do the trick: <a href=\"https://developer.apple.com/library/ios/#qa/qa2009/qa1673.html\" rel=\"nofollow\">https://developer.apple.com/library/ios/#qa/qa2009/qa1673.html</a></p>\n\n<p>It basically tells you what you need to do to pause/resume any <code>CALayer</code> based animation.</p>\n\n<p>If you feel uncomfortable using <code>CALayer</code> methods on <code>UIImageView</code> controlled animation, you could always just make the <code>UIImage</code> array based animation yourself. The code needed is very short, you can take it from here: <a href=\"http://rssv2.blogspot.com/2011/04/animating-series-of-images-with-calayer.html\" rel=\"nofollow\">http://rssv2.blogspot.com/2011/04/animating-series-of-images-with-calayer.html</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6044/"
] |
I have an animation that I'm displaying using a UIImageView:
```
imageView.animationImages = myImages;
imageView.animationDuration = 3;
[imageView startAnimating];
```
I know I can stop it using stopAnimating, but what I want is to be able to pause it. The reason is that when you call stop, none of your animation images are displayed, whereas I would like the last one that is up at the time when I hit a button to stay up.
I have tried setting the duration to a much larger number, but that causes all the images to disappear as well. There must be a really basic way to do this?
|
Hmmm...since no one seems to know I guess it's not possible.
I went ahead and wrote my own `UIView`, with a `UIImageView` `subview`, that uses an `NSTimer` to switch between images. The advantage of this is that I can pause and resume the timer at my leisure, and performance doesn't seem to be an issue.
|
253,284 |
<p>I am having dependency troubles. I have two classes: <code>Graphic</code> and <code>Image</code>. Each one has its own .cpp and .h files. I am declaring them as the following: </p>
<p><code>Graphic.h</code>: </p>
<pre><code>
#include "Image.h"
class Image;
class Graphic {
...
};
</code></pre>
<p><code>Image.h</code>:<br>
<pre><code>
#include "Graphic.h"
class Graphic;
class Image : public Graphic {
...
};</code></pre></p>
<p>When I try to compile, I get the following error: </p>
<pre>
Image.h:12: error: expected class-name before ‘{’ token
</pre>
<p>If I remove the forward declaration of <code>Graphic</code> from <code>Image.h</code> I get the following error: </p>
<pre>
Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
Image.h:10: error: forward declaration of ‘struct Graphic’
</pre>
|
[
{
"answer_id": 253294,
"author": "marijne",
"author_id": 7038,
"author_profile": "https://Stackoverflow.com/users/7038",
"pm_score": 3,
"selected": false,
"text": "<p>You don't need to include Image.h or forward declare Image in Graphic.h - that's a circular dependency. If Graphic.h depends on anything in Image.h you need to split that out into a third header. (If Graphic has an Image member, that just isn't going to work.)</p>\n"
},
{
"answer_id": 253295,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>Since Image extends Graphic, remove the inclusion of Image in your Graphic.h file.</p>\n\n<p><code>Graphic.h</code></p>\n\n<pre><code>class Graphic {\n ...\n};\n</code></pre>\n"
},
{
"answer_id": 253297,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 0,
"selected": false,
"text": "<p>First remove this, you must always have the complete class definition available in order to inherit from a class:</p>\n\n<pre><code>class Graphic;\n</code></pre>\n\n<p>Second, remove all references to Image from Graphic.h. The parent will usually not need to know of its childs.</p>\n"
},
{
"answer_id": 253318,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 5,
"selected": true,
"text": "<p>This worked for me:</p>\n\n<p>Image.h:</p>\n\n<pre><code>#ifndef IMAGE_H\n#define IMAGE_H\n\n#include \"Graphic.h\"\nclass Image : public Graphic {\n\n};\n\n#endif\n</code></pre>\n\n<p>Graphic.h:</p>\n\n<pre><code>#ifndef GRAPHIC_H\n#define GRAPHIC_H\n\n#include \"Image.h\"\n\nclass Graphic {\n};\n\n#endif\n</code></pre>\n\n<p>The following code compiles with no error:</p>\n\n<pre><code>#include \"Graphic.h\"\n\nint main()\n{\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 253331,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 2,
"selected": false,
"text": "<p>Graphic.h doesn't need to include image.h, and it doesn't need to forward declare the Image class. Also, Image.h doesn't need to forward declare the Graphic class since you #include the file that defines that class (as you must).</p>\n\n<p><code>Graphic.h:</code></p>\n\n<pre><code>class Graphic {\n ...\n};\n</code></pre>\n\n<p><code>Image.h</code>:</p>\n\n<pre><code>#include \"Graphic.h\"\nclass Image : public Graphic {\n ...\n};\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] |
I am having dependency troubles. I have two classes: `Graphic` and `Image`. Each one has its own .cpp and .h files. I am declaring them as the following:
`Graphic.h`:
```
#include "Image.h"
class Image;
class Graphic {
...
};
```
`Image.h`:
```
#include "Graphic.h"
class Graphic;
class Image : public Graphic {
...
};
```
When I try to compile, I get the following error:
```
Image.h:12: error: expected class-name before ‘{’ token
```
If I remove the forward declaration of `Graphic` from `Image.h` I get the following error:
```
Image.h:13: error: invalid use of incomplete type ‘struct Graphic’
Image.h:10: error: forward declaration of ‘struct Graphic’
```
|
This worked for me:
Image.h:
```
#ifndef IMAGE_H
#define IMAGE_H
#include "Graphic.h"
class Image : public Graphic {
};
#endif
```
Graphic.h:
```
#ifndef GRAPHIC_H
#define GRAPHIC_H
#include "Image.h"
class Graphic {
};
#endif
```
The following code compiles with no error:
```
#include "Graphic.h"
int main()
{
return 0;
}
```
|
253,286 |
<p>I'm trying to design a model for a application allowing 2 people to bet with each other (I know, sounds stupid...). What I'm wondering about is how to connect the bet with users. The structure is like this</p>
<pre><code>|-------------| |----------|
| Bet | | User |
| BetUser1 | |----------|
| BetUser2 |
| Winner |
| ... |
|-------------|
</code></pre>
<p>So we got 2 people that bet with each other (both are <code>Users</code> from django auth system) and then, after one of them wins, there's a winner. Now all those 3 fields are of type <code>User</code>, but:</p>
<ul>
<li>Should I make BetUser1 and BetUser2 separate fields, or design some many-to-two relationship here? (with many-to-two being a many-to-many and with some external way of ensuring no more then 2 <code>Users</code> can be assigned to each bet?</li>
<li>winner can only be either user 1 or user 2, noone else of course. How should I create this field, yet another <code>ForeignKey(User)</code>, or some else?</li>
</ul>
<p>Just looking for some fresh point of view, as it seems that in such stupid case I'm stuck with the django model system.</p>
|
[
{
"answer_id": 253335,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 3,
"selected": true,
"text": "<p>I would probably add a third model to represent a specific wager someone has placed, as it is conceivable that more than two people could enter into a bet. It would look something like this:</p>\n\n<pre><code>USER WAGER BET\n User (FK(User)) Description\n Bet (FK(Bet)) Winner (FK (Wager), null=True)\n Amount\n</code></pre>\n\n<p>Django will automatically generate <code>user.wager_set</code> and <code>bet.wager_set</code> based on the foreign keys. This allows you to easily iterate and display the wagers for a bet, as well as the wagers from each user. You can also add a <code>unique_together</code> constraint on <code>User</code> and <code>Bet</code> in the Wager table so that each user can only make one wager.</p>\n\n<p>When the betting is all done, and a winner has been selected, you just set <code>bet.winner</code>.</p>\n\n<p>In case you run into it, you might see a warning about <code>related_name</code> by having <code>Bet</code> point to <code>Wager</code> and <code>Wager</code> point to <code>Bet</code>. To fix, just add <code>related_name=wagers</code> to <code>Wager.bet</code>.</p>\n"
},
{
"answer_id": 253482,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 1,
"selected": false,
"text": "<p>What you need is a Many-to-Many relation with extra data (e.g. the amount on the wager, the time entered,...)</p>\n\n<p>There is a <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\" rel=\"nofollow noreferrer\">chaper</a> on this in the excellent Django docs on writing models.</p>\n\n<p>Tyler has already outlined the proper schema for this.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
I'm trying to design a model for a application allowing 2 people to bet with each other (I know, sounds stupid...). What I'm wondering about is how to connect the bet with users. The structure is like this
```
|-------------| |----------|
| Bet | | User |
| BetUser1 | |----------|
| BetUser2 |
| Winner |
| ... |
|-------------|
```
So we got 2 people that bet with each other (both are `Users` from django auth system) and then, after one of them wins, there's a winner. Now all those 3 fields are of type `User`, but:
* Should I make BetUser1 and BetUser2 separate fields, or design some many-to-two relationship here? (with many-to-two being a many-to-many and with some external way of ensuring no more then 2 `Users` can be assigned to each bet?
* winner can only be either user 1 or user 2, noone else of course. How should I create this field, yet another `ForeignKey(User)`, or some else?
Just looking for some fresh point of view, as it seems that in such stupid case I'm stuck with the django model system.
|
I would probably add a third model to represent a specific wager someone has placed, as it is conceivable that more than two people could enter into a bet. It would look something like this:
```
USER WAGER BET
User (FK(User)) Description
Bet (FK(Bet)) Winner (FK (Wager), null=True)
Amount
```
Django will automatically generate `user.wager_set` and `bet.wager_set` based on the foreign keys. This allows you to easily iterate and display the wagers for a bet, as well as the wagers from each user. You can also add a `unique_together` constraint on `User` and `Bet` in the Wager table so that each user can only make one wager.
When the betting is all done, and a winner has been selected, you just set `bet.winner`.
In case you run into it, you might see a warning about `related_name` by having `Bet` point to `Wager` and `Wager` point to `Bet`. To fix, just add `related_name=wagers` to `Wager.bet`.
|
253,289 |
<p>I am new to PHP and trying to get the following code to work:</p>
<pre><code><?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
"ARTICLE_NO :{$row['ARTICLE_NO']} <br>" .
"ARTICLE_NAME :{$row['ARTICLE_NAME']} <br>" .
"SUBTITLE :{$row['SUBTITLE']} <br>" .
"CURRENT_BID :{$row['CURRENT_BID']} <br>" .
"START_PRICE :{$row['START_PRICE']} <br>" .
"BID_COUNT :{$row['BID_COUNT']} <br>" .
"QUANT_TOTAL :{$row['QUANT_TOTAL']} <br>" .
"QUANT_SOLD :{$row['QUANT_SOLD']} <br>" .
"STARTS :{$row['STARTS']} <br>" .
"ENDS :{$row['ENDS']} <br>" .
"ORIGIN_END :{$row['ORIGIN_END']} <br>" .
"SELLER_ID :{$row['SELLER_ID']} <br>" .
"BEST_BIDDER_ID :{$row['BEST_BIDDER_ID']} <br>" .
"FINISHED :{$row['FINISHED']} <br>" .
"WATCH :{$row['WATCH']} <br>" .
"BUYITNOW_PRICE :{$row['BUYITNOW_PRICE']} <br>" .
"PIC_URL :{$row['PIC_URL']} <br>" .
"PRIVATE_AUCTION :{$row['PRIVATE_AUCTION']} <br>" .
"AUCTION_TYPE :{$row['AUCTION_TYPE']} <br>" .
"INSERT_DATE :{$row['INSERT_DATE']} <br>" .
"UPDATE_DATE :{$row['UPDATE_DATE']} <br>" .
"CAT_1_ID :{$row['CAT_1_ID']} <br>" .
"CAT_2_ID :{$row['CAT_2_ID']} <br>" .
"ARTICLE_DESC :{$row['ARTICLE_DESC']} <br>" .
"DESC_TEXTONLY :{$row['DESC_TEXTONLY']} <br>" .
"COUNTRYCODE :{$row['COUNTRYCODE']} <br>" .
"LOCATION :{$row['LOCATION']} <br>" .
"CONDITIONS :{$row['CONDITIONS']} <br>" .
"REVISED :{$row['REVISED']} <br>" .
"PAYPAL_ACCEPT :{$row['PAYPAL_ACCEPT']} <br>" .
"PRE_TERMINATED :{$row['PRE_TERMINATED']} <br>" .
"SHIPPING_TO :{$row['SHIPPING_TO']} <br>" .
"FEE_INSERTION :{$row['FEE_INSERTION']} <br>" .
"FEE_FINAL :{$row['FEE_FINAL']} <br>" .
"FEE_LISTING :{$row['FEE_LISTING']} <br>" .
"PIC_XXL :{$row['PIC_XXL']} <br>" .
"PIC_DIASHOW :{$row['PIC_DIASHOW']} <br>" .
"PIC_COUNT :{$row['PIC_COUNT']} <br>" .
"ITEM_SITE_ID :{$row['ITEM_SITE_ID']};
}
include 'closedb.php';
?>
</code></pre>
<p>However I get this error:</p>
<pre><code>Parse error: syntax error, unexpected $end in C:\Programme\EasyPHP 2.0b1\www\test.php on line 56
</code></pre>
<p>I would also like to know if there is perhaps an easier way to obtain mysql records instead of typing by hand?</p>
<p>edit:</p>
<p>I fixed the semicolon and quote issue, and now get:</p>
<pre><code>Parse error: syntax error, unexpected T_STRING in C:\Programme\EasyPHP 2.0b1\www\test.php on line 51
</code></pre>
<p>I am sorry I don't know how to make colors in the code.</p>
|
[
{
"answer_id": 253299,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 4,
"selected": true,
"text": "<p><strong>Edit</strong></p>\n\n<p>You say that you're still getting an error. Did you remember to add a <strong>.</strong> when you removed that extra semi-colon?</p>\n\n<hr>\n\n<p>You have a semi-colon in the middle of your string, two lines after the echo.</p>\n\n<p><img src=\"https://farm4.static.flickr.com/3049/2989189590_754c627f5d.jpg?v=0\"></p>\n\n<p>Also, the end of the string is missing a double-quote.</p>\n\n<p><img src=\"https://farm4.static.flickr.com/3151/2988333441_7e6705715d.jpg?v=0\"></p>\n\n<hr>\n\n<p>As far as a cleaner way to output all the values goes, you can loop over the result array like this:</p>\n\n<pre><code>while($row = mysql_fetch_array($result, MYSQL_ASSOC))\n{\n foreach($row as $field=>$value)\n {\n echo \"$field: {$value} <br />\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 253305,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 2,
"selected": false,
"text": "<p>For the second part of your question, you could do this if field names are all logical:</p>\n\n<pre><code>while($row = mysql_fetch_array($result, MYSQL_ASSOC))\n{\n foreach($row as $key => $value)\n {\n echo \"$key: $value\\n\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 253308,
"author": "jakber",
"author_id": 29812,
"author_profile": "https://Stackoverflow.com/users/29812",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Edit:</strong> \nYour SQL query only returns 3 fields. But you try to access a lot more than that. Try \"SELECT *\" if you want to return all the fields of a table. Otherwise make sure you select the fields you try to read (probably not why you get an error though, just an observation).</p>\n\n<p>The syntax coloring of </p>\n\n<pre><code>include 'closedb.php';\n\n?>\n</code></pre>\n\n<p>indicates that the string lacks a closing quote. The line</p>\n\n<pre><code>\"ITEM_SITE_ID :{$row['ITEM_SITE_ID']};\n</code></pre>\n\n<p>confirms that.</p>\n\n<p>Also the line</p>\n\n<pre><code>\"Message : {$row['message']} <br><br>\";\n</code></pre>\n\n<p>ends the string concatenation. The semi-colon should probably be a period.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I am new to PHP and trying to get the following code to work:
```
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT name, subject, message FROM contact";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "Name :{$row['name']} <br>" .
"Subject : {$row['subject']} <br>" .
"Message : {$row['message']} <br><br>";
"ARTICLE_NO :{$row['ARTICLE_NO']} <br>" .
"ARTICLE_NAME :{$row['ARTICLE_NAME']} <br>" .
"SUBTITLE :{$row['SUBTITLE']} <br>" .
"CURRENT_BID :{$row['CURRENT_BID']} <br>" .
"START_PRICE :{$row['START_PRICE']} <br>" .
"BID_COUNT :{$row['BID_COUNT']} <br>" .
"QUANT_TOTAL :{$row['QUANT_TOTAL']} <br>" .
"QUANT_SOLD :{$row['QUANT_SOLD']} <br>" .
"STARTS :{$row['STARTS']} <br>" .
"ENDS :{$row['ENDS']} <br>" .
"ORIGIN_END :{$row['ORIGIN_END']} <br>" .
"SELLER_ID :{$row['SELLER_ID']} <br>" .
"BEST_BIDDER_ID :{$row['BEST_BIDDER_ID']} <br>" .
"FINISHED :{$row['FINISHED']} <br>" .
"WATCH :{$row['WATCH']} <br>" .
"BUYITNOW_PRICE :{$row['BUYITNOW_PRICE']} <br>" .
"PIC_URL :{$row['PIC_URL']} <br>" .
"PRIVATE_AUCTION :{$row['PRIVATE_AUCTION']} <br>" .
"AUCTION_TYPE :{$row['AUCTION_TYPE']} <br>" .
"INSERT_DATE :{$row['INSERT_DATE']} <br>" .
"UPDATE_DATE :{$row['UPDATE_DATE']} <br>" .
"CAT_1_ID :{$row['CAT_1_ID']} <br>" .
"CAT_2_ID :{$row['CAT_2_ID']} <br>" .
"ARTICLE_DESC :{$row['ARTICLE_DESC']} <br>" .
"DESC_TEXTONLY :{$row['DESC_TEXTONLY']} <br>" .
"COUNTRYCODE :{$row['COUNTRYCODE']} <br>" .
"LOCATION :{$row['LOCATION']} <br>" .
"CONDITIONS :{$row['CONDITIONS']} <br>" .
"REVISED :{$row['REVISED']} <br>" .
"PAYPAL_ACCEPT :{$row['PAYPAL_ACCEPT']} <br>" .
"PRE_TERMINATED :{$row['PRE_TERMINATED']} <br>" .
"SHIPPING_TO :{$row['SHIPPING_TO']} <br>" .
"FEE_INSERTION :{$row['FEE_INSERTION']} <br>" .
"FEE_FINAL :{$row['FEE_FINAL']} <br>" .
"FEE_LISTING :{$row['FEE_LISTING']} <br>" .
"PIC_XXL :{$row['PIC_XXL']} <br>" .
"PIC_DIASHOW :{$row['PIC_DIASHOW']} <br>" .
"PIC_COUNT :{$row['PIC_COUNT']} <br>" .
"ITEM_SITE_ID :{$row['ITEM_SITE_ID']};
}
include 'closedb.php';
?>
```
However I get this error:
```
Parse error: syntax error, unexpected $end in C:\Programme\EasyPHP 2.0b1\www\test.php on line 56
```
I would also like to know if there is perhaps an easier way to obtain mysql records instead of typing by hand?
edit:
I fixed the semicolon and quote issue, and now get:
```
Parse error: syntax error, unexpected T_STRING in C:\Programme\EasyPHP 2.0b1\www\test.php on line 51
```
I am sorry I don't know how to make colors in the code.
|
**Edit**
You say that you're still getting an error. Did you remember to add a **.** when you removed that extra semi-colon?
---
You have a semi-colon in the middle of your string, two lines after the echo.

Also, the end of the string is missing a double-quote.

---
As far as a cleaner way to output all the values goes, you can loop over the result array like this:
```
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $field=>$value)
{
echo "$field: {$value} <br />";
}
}
```
|
253,312 |
<p>Any ideas why this won't validate here:</p>
<p><a href="http://validator.w3.org/#validate_by_input" rel="nofollow noreferrer">http://validator.w3.org/#validate_by_input</a></p>
<p>It seems the form input tags are wrong but reading through the XHTML spec they should validate fine. Any ideas?</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
<div class="Header">
<table class="HeaderTable">
<tr>
<td>
<div class="Heading">Test <span class="Standard">Test</span>
</div>
</td>
<td>
<div class="Controls">
<form id="ControlForm" method="get" action="Edit.php">
<input type="submit" name="action" id="Edit" value="Edit" />
<input type="submit" name="action" id="New" value="New" />
</form>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 253340,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 3,
"selected": false,
"text": "<p>Try putting a <code>fieldset</code> tag around the inputs. I think the idea of forms in XHTML is that they can't have direct descendants that aren't div, fieldset, etc.</p>\n"
},
{
"answer_id": 253348,
"author": "FOR",
"author_id": 27826,
"author_profile": "https://Stackoverflow.com/users/27826",
"pm_score": 2,
"selected": false,
"text": "<p>As someone else put it:</p>\n\n<p>[quote]\nThe validator is telling you that your hidden input element cannot immediately follow the form tag - it needs to have a container element of some kind. \n[/quote]</p>\n\n<p>(<a href=\"http://www.webmasterworld.com/forum21/9223.htm\" rel=\"nofollow noreferrer\">Source</a>)</p>\n\n<p>I guess a fieldset could help; See <a href=\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\" rel=\"nofollow noreferrer\">The XHTML DTD</a>:</p>\n\n<pre><code><!ELEMENT form %form.content;>\n\n<!ENTITY % form.content \"(%block; | %misc;)*\">\n\n<!ENTITY % misc \"noscript | %misc.inline;\">\n<!ENTITY % misc.inline \"ins | del | script\">\n\n<!ENTITY % block \"p | %heading; | div | %lists; | %blocktext; | fieldset | table\">\n\n<!ENTITY % heading \"h1|h2|h3|h4|h5|h6\">\n<!ENTITY % lists \"ul | ol | dl\">\n<!ENTITY % blocktext \"pre | hr | blockquote | address\">\n</code></pre>\n\n<p>No input for you :(</p>\n"
},
{
"answer_id": 253353,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 3,
"selected": true,
"text": "<p>You need to move </p>\n\n<pre><code><div class=\"Controls\">\n</code></pre>\n\n<p>so that it's <strong>inside</strong> the <strong><form</strong> tag</p>\n\n<hr>\n\n<p>This validates nicely</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n <title>Test</title>\n</head>\n\n<body>\n <div class=\"Header\">\n <table class=\"HeaderTable\">\n <tr>\n <td>\n <div class=\"Heading\">Test <span class=\"Standard\">Test</span></div>\n </td>\n <td>\n <form id=\"ControlForm\" method=\"get\" action=\"Edit.php\">\n <div class=\"Controls\">\n <input type=\"submit\" name=\"action\" id=\"Edit\" value=\"Edit\" />\n <input type=\"submit\" name=\"action\" id=\"New\" value=\"New\" />\n </div>\n </form>\n </td>\n </tr>\n </table>\n </div>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 253361,
"author": "François",
"author_id": 32379,
"author_profile": "https://Stackoverflow.com/users/32379",
"pm_score": 0,
"selected": false,
"text": "<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>Test</title>\n </head>\n\n <body>\n <div class=\"Header\">\n <table class=\"HeaderTable\">\n <tr>\n <td>\n <div class=\"Heading\">Test <span class=\"Standard\">Test</span>\n </div>\n </td>\n <td>\n\n <form id=\"ControlForm\" method=\"get\" action=\"Edit.php\">\n <div class=\"Controls\">\n <input type=\"submit\" name=\"action\" id=\"Edit\" value=\"Edit\" />\n <input type=\"submit\" name=\"action\" id=\"New\" value=\"New\" />\n </div>\n </form>\n\n </td>\n </tr>\n </table>\n </div>\n </body>\n</html>\n</code></pre>\n\n<p>Put your div inside your form.</p>\n"
},
{
"answer_id": 253379,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 0,
"selected": false,
"text": "<p>Your input elements should be within a fieldset. This validates and has the added benefit of making the document more accessible to non-visual user agents.</p>\n\n<p>As an aside, your markup is suffering from <em>divitis</em> a bit. You could put classes on the table cells directly rather than nesting div elements within them (I'm not going to comment on the use of tables for layout). Also, you could style the form element directly rather than nesting it within a div.</p>\n\n<p>Anyway, here's your example with a fieldset added so it validates:</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n <head>\n <title>Test</title>\n </head>\n <body>\n <div class=\"Header\">\n <table class=\"HeaderTable\">\n <tr>\n <td>\n <div class=\"Heading\">Test <span class=\"Standard\">Test</span></div>\n </td>\n <td>\n <div class=\"Controls\">\n <form id=\"ControlForm\" method=\"get\" action=\"Edit.php\">\n <fieldset>\n <input type=\"submit\" name=\"action\" id=\"Edit\" value=\"Edit\" />\n <input type=\"submit\" name=\"action\" id=\"New\" value=\"New\" />\n </fieldset>\n </form>\n </div>\n </td>\n </tr>\n </table>\n </div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 2629855,
"author": "Adrian",
"author_id": 315514,
"author_profile": "https://Stackoverflow.com/users/315514",
"pm_score": 1,
"selected": false,
"text": "<p>I had the very same problem and it took me some time to figure out. Is this a recent change with the w3c validator? it's just I'm sure some of my pages with forms validated in the past, but now they all seem to through up errors for the same problem. </p>\n\n<p>I used to always do something like:</p>\n\n<pre><code><div>\n<form>\n <label></label>\n <input />\n <label></label>\n <input />\n <label></label>\n <input />\n</form>\n</code></pre>\n\n<p></p>\n\n<p>and get validation errors, so now I just add fieldset or div around all the labels and inputs to get it to validate, like this:</p>\n\n<pre><code><div>\n<form>\n <fieldset>or<div>\n <label></label>\n <input />\n <label></label>\n <input />\n <label></label>\n <input />\n </fieldset>or</div>\n</form>\n</code></pre>\n\n<p></p>\n\n<p>Seems to work, but I'm sure I didn't have to do this in the past... hmmm?</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13227/"
] |
Any ideas why this won't validate here:
<http://validator.w3.org/#validate_by_input>
It seems the form input tags are wrong but reading through the XHTML spec they should validate fine. Any ideas?
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
<div class="Header">
<table class="HeaderTable">
<tr>
<td>
<div class="Heading">Test <span class="Standard">Test</span>
</div>
</td>
<td>
<div class="Controls">
<form id="ControlForm" method="get" action="Edit.php">
<input type="submit" name="action" id="Edit" value="Edit" />
<input type="submit" name="action" id="New" value="New" />
</form>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
```
|
You need to move
```
<div class="Controls">
```
so that it's **inside** the **<form** tag
---
This validates nicely
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
</head>
<body>
<div class="Header">
<table class="HeaderTable">
<tr>
<td>
<div class="Heading">Test <span class="Standard">Test</span></div>
</td>
<td>
<form id="ControlForm" method="get" action="Edit.php">
<div class="Controls">
<input type="submit" name="action" id="Edit" value="Edit" />
<input type="submit" name="action" id="New" value="New" />
</div>
</form>
</td>
</tr>
</table>
</div>
</body>
</html>
```
|
253,324 |
<p>I need a smart way to get the data types out of INFORMATION_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement. The problem is the 'extra' fields that need to be understood, such as NUMERIC<code>_</code>PRECISION and NUMERIC<code>_</code>SCALE.</p>
<p>Obviously, I can ignore the columns for INTEGER (precision of 10 and scale of 0), but there are other types I would be interested in, such as NUMERIC. So without writing lots of code to parse the table, any ideas on how to get a sort of field shorthand out of the column definition?</p>
<p>I would like to be able to get something like :
int,
datetime,
money,
numeric**(10,2)**</p>
|
[
{
"answer_id": 253330,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 1,
"selected": false,
"text": "<p>SMO Scripting should take care of the script generations. I believe that this is what MS uses in SQL Management Studio for script generations. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms162153.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms162153.aspx</a></p>\n\n<p>@YourComment - <code>I need a smart way to get the data types out of INFORMATION_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement</code></p>\n\n<p>This is what you asked for. Short of that, you will have to parse the info schema view results. </p>\n"
},
{
"answer_id": 253374,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select column_type = data_type + \n case\n when data_type like '%text' then ''\n when data_type like '%char' and character_maximum_length = -1 then '(max)'\n when character_maximum_length is not null then '(' + convert(varchar(10), character_maximum_length) + ')'\n when data_type = 'numeric' then '(' + convert(varchar(10), isnull(numeric_precision, 18)) + ', ' + \n convert(varchar(10), isnull(numeric_scale, 0)) + ')'\n else ''\n end\n,*\nfrom information_schema.columns\n</code></pre>\n"
},
{
"answer_id": 457148,
"author": "Vitor Silva",
"author_id": 1842864,
"author_profile": "https://Stackoverflow.com/users/1842864",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using smo you can get both precision and scale by accessing the Properties colletion of the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.column_properties.aspx\" rel=\"nofollow noreferrer\">Column Object</a></p>\n\n<p>Column.Property[\"NumericScale\"].Value</p>\n\n<p>Column.Property[\"NumericPrecision\"].Value</p>\n"
},
{
"answer_id": 11234044,
"author": "Tim Lehner",
"author_id": 880904,
"author_profile": "https://Stackoverflow.com/users/880904",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an update (ripoff!) of <a href=\"https://stackoverflow.com/a/253374/880904\">GalacticCowboy's answer</a> to fix some issues and update for all (I think) SQL Server 2008R2 datatypes:</p>\n\n<pre><code>select data_type + \n case\n when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')\n then ''\n when data_type in ('float')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'\n when data_type in ('datetime2', 'datetimeoffset', 'time')\n then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'\n when data_type in ('decimal', 'numeric')\n then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'\n when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1\n then '(max)'\n when character_maximum_length is not null\n then '(' + cast(character_maximum_length as varchar(11)) + ')'\n else ''\n end as CONDENSED_TYPE\n , *\nfrom information_schema.columns\norder by table_schema, table_name, ordinal_position\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3893/"
] |
I need a smart way to get the data types out of INFORMATION\_SCHEMA.COLUMNS in a way that could be used in a CREATE TABLE statement. The problem is the 'extra' fields that need to be understood, such as NUMERIC`_`PRECISION and NUMERIC`_`SCALE.
Obviously, I can ignore the columns for INTEGER (precision of 10 and scale of 0), but there are other types I would be interested in, such as NUMERIC. So without writing lots of code to parse the table, any ideas on how to get a sort of field shorthand out of the column definition?
I would like to be able to get something like :
int,
datetime,
money,
numeric\*\*(10,2)\*\*
|
Here is an update (ripoff!) of [GalacticCowboy's answer](https://stackoverflow.com/a/253374/880904) to fix some issues and update for all (I think) SQL Server 2008R2 datatypes:
```
select data_type +
case
when data_type like '%text' or data_type in ('image', 'sql_variant' ,'xml')
then ''
when data_type in ('float')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ')'
when data_type in ('datetime2', 'datetimeoffset', 'time')
then '(' + cast(coalesce(datetime_precision, 7) as varchar(11)) + ')'
when data_type in ('decimal', 'numeric')
then '(' + cast(coalesce(numeric_precision, 18) as varchar(11)) + ',' + cast(coalesce(numeric_scale, 0) as varchar(11)) + ')'
when (data_type like '%binary' or data_type like '%char') and character_maximum_length = -1
then '(max)'
when character_maximum_length is not null
then '(' + cast(character_maximum_length as varchar(11)) + ')'
else ''
end as CONDENSED_TYPE
, *
from information_schema.columns
order by table_schema, table_name, ordinal_position
```
|
253,351 |
<p>I am writing a Java Application for Data Entry using Eclipse and SWT. Naturally it has a great many Text objects. </p>
<p>What I would like to happen is that when user enters something into one field focus automatically changes to the next field.</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 254030,
"author": "Drazen Urch",
"author_id": 33074,
"author_profile": "https://Stackoverflow.com/users/33074",
"pm_score": 2,
"selected": false,
"text": "<pre><code>final Text textBox = new Text(shell, SWT.NONE);\ntextBox.addKeyListener(new KeyAdapter() {\n public void keyPressed(KeyEvent e) {\n if (x.getText().length() == 1); {\n x.traverse(SWT.TRAVERSE_TAB_NEXT);\n }\n }\n});\n</code></pre>\n"
},
{
"answer_id": 254055,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 1,
"selected": false,
"text": "<pre><code>final Text textBox = new Text(shell, SWT.NONE);\ntextBox.addKeyListener(new KeyAdapter() {\n\n public void keyPressed(KeyEvent arg0) {\n if (textBox.getText().equals(\"\") == false) {\n textBox.traverse(SWT.TRAVERSE_TAB_NEXT);\n }\n }});\n</code></pre>\n"
},
{
"answer_id": 255959,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "<p>I assume you want to change the focus <em>after</em> the field has been filled. I suggest using a DocumentListener (or whatever SWT calls it) to be notified of changes to the field's content: if it has the right number of characters, jump to the next field.</p>\n"
},
{
"answer_id": 255993,
"author": "Daniel Schneller",
"author_id": 1252368,
"author_profile": "https://Stackoverflow.com/users/1252368",
"pm_score": 1,
"selected": false,
"text": "<p>You may also want to have a look at the VerifyListener interface. See this interesting blog post for a caveat though: <a href=\"http://eclipsenuggets.blogspot.com/2008/10/eclipse-bug-patterns-selfish-validation.html\" rel=\"nofollow noreferrer\">http://eclipsenuggets.blogspot.com/2008/10/eclipse-bug-patterns-selfish-validation.html</a></p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33074/"
] |
I am writing a Java Application for Data Entry using Eclipse and SWT. Naturally it has a great many Text objects.
What I would like to happen is that when user enters something into one field focus automatically changes to the next field.
Thanks in advance
|
```
final Text textBox = new Text(shell, SWT.NONE);
textBox.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (x.getText().length() == 1); {
x.traverse(SWT.TRAVERSE_TAB_NEXT);
}
}
});
```
|
253,360 |
<p>Whilst trying to get our app working in Firefox (I'm a big proponent of X-Browser support but our lead dev is resisting me saying IE is good enough). So I'm doing a little side project to see how much work it is to convert.</p>
<p>I've hit a problem straight away.</p>
<p>The main.aspx page binds to a webservice using the IE only method of adding behaviour through a htc file, which is auto-generated by VS I beleive.</p>
<p> </p>
<p>Firefox doesn't support this but there is an xml bindings file which can be used to enable htc support (see here: <a href="http://dean.edwards.name/moz-behaviors/overview/" rel="nofollow noreferrer">http://dean.edwards.name/moz-behaviors/overview/</a>). The examples work in FF3 but when I use my webservice.htc as I normally would e.g.:</p>
<pre><code>//Main.aspx
/*SNIP*/
<style type="text/css" media="all">
#webservice
{
behavior:url(webservice.htc);
-moz-binding:url(bindings.xml#webservice.htc);
}
</style>
</head>
<body>
<div id="webservice"></div> <!-- we use this div to load the webservice stuff -->
/*SNIP*/
//Main.js
webservice.useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper");
</code></pre>
<p>I get webservice is not defined (works fine in IE), I obviously tried</p>
<pre><code>var webservice = document.getElementById("webservice")
</code></pre>
<p>and </p>
<pre><code>$("#webservice").useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper");
</code></pre>
<p>as well which just gives me "useService is not defined" in Firebug. Which leads me to beleive that the binding is not working. However I can see that webservice.htc is being loaded by Firefox in the Firebug console window.</p>
<p>Anyone got any experience of this?</p>
<p>Am I going to have to rewrite how the webservice is called?</p>
<p>Cheers,
Rob</p>
|
[
{
"answer_id": 254299,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 3,
"selected": true,
"text": "<p>I don't think that you are on the right way for achieving real cross-browser compatibility. Adding support for IE-specific features for Firefox is definitely <strong>not</strong> the way to go. What about Opera, Safari, Chrome...? If the app you're working on is used strictly on the intranet then supporting Firefox may be enough however...</p>\n\n<p>IMHO, the code should be refactored, but in an other way. If you are working with ASP.NET 2.0 (in this case you'd need ASP.NET Ajax) or newer, you can create proxy between Ajax and SOAP web services. In that case you would need to rewrite all your behaviors as a JavaScript code which may not be a small feat.</p>\n\n<p>On a side note: AFAIK VS.NET does not generate behaviors.</p>\n\n<p>Sorry if this is not too helpful :(</p>\n"
},
{
"answer_id": 259631,
"author": "savetheclocktower",
"author_id": 25720,
"author_profile": "https://Stackoverflow.com/users/25720",
"pm_score": 1,
"selected": false,
"text": "<p>Your jQuery snippet has an error: since <code>useService</code> is a method defined on the node itself, not the jQuery object, you'd have to do:</p>\n\n<pre><code>$(\"#webservice\")[0].useService(url + asmpath +\n \"/WebServiceWrapper.asmx?WSDL\",\"WebServiceWrapper\");\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950/"
] |
Whilst trying to get our app working in Firefox (I'm a big proponent of X-Browser support but our lead dev is resisting me saying IE is good enough). So I'm doing a little side project to see how much work it is to convert.
I've hit a problem straight away.
The main.aspx page binds to a webservice using the IE only method of adding behaviour through a htc file, which is auto-generated by VS I beleive.
Firefox doesn't support this but there is an xml bindings file which can be used to enable htc support (see here: <http://dean.edwards.name/moz-behaviors/overview/>). The examples work in FF3 but when I use my webservice.htc as I normally would e.g.:
```
//Main.aspx
/*SNIP*/
<style type="text/css" media="all">
#webservice
{
behavior:url(webservice.htc);
-moz-binding:url(bindings.xml#webservice.htc);
}
</style>
</head>
<body>
<div id="webservice"></div> <!-- we use this div to load the webservice stuff -->
/*SNIP*/
//Main.js
webservice.useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper");
```
I get webservice is not defined (works fine in IE), I obviously tried
```
var webservice = document.getElementById("webservice")
```
and
```
$("#webservice").useService(url + asmpath + "/WebServiceWrapper.asmx?WSDL","WebServiceWrapper");
```
as well which just gives me "useService is not defined" in Firebug. Which leads me to beleive that the binding is not working. However I can see that webservice.htc is being loaded by Firefox in the Firebug console window.
Anyone got any experience of this?
Am I going to have to rewrite how the webservice is called?
Cheers,
Rob
|
I don't think that you are on the right way for achieving real cross-browser compatibility. Adding support for IE-specific features for Firefox is definitely **not** the way to go. What about Opera, Safari, Chrome...? If the app you're working on is used strictly on the intranet then supporting Firefox may be enough however...
IMHO, the code should be refactored, but in an other way. If you are working with ASP.NET 2.0 (in this case you'd need ASP.NET Ajax) or newer, you can create proxy between Ajax and SOAP web services. In that case you would need to rewrite all your behaviors as a JavaScript code which may not be a small feat.
On a side note: AFAIK VS.NET does not generate behaviors.
Sorry if this is not too helpful :(
|
253,378 |
<p>I am trying the following code:</p>
<pre><code><?php
$link = mysql_connect('localhost', 'root', 'geheim');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $field=>$value)
{
echo "$field: {$value} <br />";
}
}
mysql_close($link);
?>
</code></pre>
<p>And get this error:</p>
<pre><code>Warning: mysql_fetch_array(): supplied argument is not a
valid MySQL result resource in
C:\Programme\EasyPHP 2.0b1\www\test.php on line 14
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 253383,
"author": "MattBelanger",
"author_id": 655,
"author_profile": "https://Stackoverflow.com/users/655",
"pm_score": 0,
"selected": false,
"text": "<p>Are you getting anything returned? If no results are found, mysql_query returns FALSE.</p>\n\n<p>Check that before running fetch_array.</p>\n"
},
{
"answer_id": 253385,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 1,
"selected": false,
"text": "<p>$query = \"SELECT * FROM Auctions\";</p>\n\n<p>$result = mysql_query($query) or die(mysql_error());</p>\n\n<p>so you'll see the error</p>\n"
},
{
"answer_id": 253386,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 2,
"selected": false,
"text": "<p>Your MySQL query possibly does not match any rows in the database.</p>\n\n<p>Check the return value of <a href=\"http://nl2.php.net/mysql_query\" rel=\"nofollow noreferrer\">mysql_query()</a>, which returns \"resource\" on success and \"false\" on failure.</p>\n\n<pre><code>$query = \"SELECT * FROM Auctions\"; \n$result = mysql_query($query);\n\nif ($result !== false) {\n while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { \n foreach ($row as $field=>$value) { \n echo $field . ':' . $value\n }\n }\n} else {\n // query returned 0 rows\n}\n</code></pre>\n\n<p>As others also suggested, you can use <a href=\"http://nl3.php.net/manual/en/function.mysql-error.php\" rel=\"nofollow noreferrer\">mysql_error()</a> to look if the query returns any mySQL errors</p>\n"
},
{
"answer_id": 253389,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<p>You haven't selected a database - use <a href=\"http://www.php.net/mysql_select_db\" rel=\"nofollow noreferrer\"><code>mysql_select_db()</code></a></p>\n\n<p>That would be something like:</p>\n\n<pre><code><?php\n $link = mysql_connect('localhost', 'root', 'geheim');\n if (!$link) {\n die('Could not connect: ' . mysql_error());\n }\n echo 'Connected successfully';\n\n $db_selected = mysql_select_db('foo', $link);\n if (!$db_selected) {\n die ('Error selecting database: '. mysql_error());\n }\n echo 'Using database successfully';\n\n $query = \"SELECT * FROM Auctions\";\n $result = mysql_query($query);\n while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {\n foreach($row as $field=>$value) {\n echo \"$field: {$value} <br />\";\n }\n }\n mysql_close($link);\n?> \n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I am trying the following code:
```
<?php
$link = mysql_connect('localhost', 'root', 'geheim');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach($row as $field=>$value)
{
echo "$field: {$value} <br />";
}
}
mysql_close($link);
?>
```
And get this error:
```
Warning: mysql_fetch_array(): supplied argument is not a
valid MySQL result resource in
C:\Programme\EasyPHP 2.0b1\www\test.php on line 14
```
What am I missing?
|
You haven't selected a database - use [`mysql_select_db()`](http://www.php.net/mysql_select_db)
That would be something like:
```
<?php
$link = mysql_connect('localhost', 'root', 'geheim');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Error selecting database: '. mysql_error());
}
echo 'Using database successfully';
$query = "SELECT * FROM Auctions";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
foreach($row as $field=>$value) {
echo "$field: {$value} <br />";
}
}
mysql_close($link);
?>
```
|
253,394 |
<p>I need to add a row to a spreadsheet using VBScript on a PC that does not have Microsoft Office installed.</p>
<p>I tried [<code>Set objExcel = CreateObject("Excel.Application")</code>]</p>
<p>Since Excel does not exist on the PC I cannot create this object.</p>
<p>Is there a way to modify a spreadsheet without Excel?</p>
|
[
{
"answer_id": 253402,
"author": "DilbertDave",
"author_id": 31580,
"author_profile": "https://Stackoverflow.com/users/31580",
"pm_score": 0,
"selected": false,
"text": "<p>Without Excel installed I cannot see how you will be able to change an Excel document. </p>\n\n<p>However, If your are using Excel 2007 spreadsheets (xslx) then you should able to use the OpenXML functionality of the .NET Framework to update the contents without Excel physically being installed.</p>\n\n<p>Take a look <a href=\"http://www.microsoft.com/uk/msdn/screencasts/screencast/239/Intro-to-the-Office-Open-XML-File-Format.aspx\" rel=\"nofollow noreferrer\">here</a> for more information on Office OpenXML.</p>\n"
},
{
"answer_id": 253405,
"author": "ProfK",
"author_id": 8741,
"author_profile": "https://Stackoverflow.com/users/8741",
"pm_score": 1,
"selected": false,
"text": "<p>Not without extreme difficulty. Microsoft have released their file format specifications, <a href=\"http://download.microsoft.com/download/0/B/E/0BE8BDD7-E5E8-422A-ABFD-4342ED7AD886/Excel97-2007BinaryFileFormat(xls)Specification.pdf\" rel=\"nofollow noreferrer\">Excel here</a>, but these are not to be taken lightly, and I think you will have a difficult time using VBScript. </p>\n"
},
{
"answer_id": 253406,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use the Microsoft Jet Driver:</p>\n\n<p>See <a href=\"http://www.simongibson.com/intranet/adooledb/#excel\" rel=\"nofollow noreferrer\">here</a> for a vbscript sample. See <a href=\"https://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c#151048\">here</a> for more links and ways to insert rows.</p>\n"
},
{
"answer_id": 253565,
"author": "ProfK",
"author_id": 8741,
"author_profile": "https://Stackoverflow.com/users/8741",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to see <a href=\"https://stackoverflow.com/questions/151005/create-excel-xls-and-xlsx-file-from-c#151048\">this question</a>. It's C# based, but should give you an insight into the techniques for accessing spreatsheets.</p>\n"
},
{
"answer_id": 254209,
"author": "aphoria",
"author_id": 2441,
"author_profile": "https://Stackoverflow.com/users/2441",
"pm_score": 3,
"selected": false,
"text": "<p>To use the code below, create an Excel workbook named \"Test.xls\" in the same folder as the vbscript file.</p>\n\n<p>In Test.xls, enter the following data in cells A1 thru B4:</p>\n\n<pre><code>First Last\nJoe Smith\nMary Jones\nSam Nelson\n</code></pre>\n\n<p>Paste the vbscript code below into a .vbs file:</p>\n\n<pre><code>Const adOpenStatic = 3\nConst adLockOptimistic = 3\n\nfilename = \"Test.xls\"\nSet cn = CreateObject(\"ADODB.Connection\")\ncn.Open \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" & filename & _\n \";Extended Properties=Excel 8.0\"\n\nquery = \"Select * from [Sheet1$A1:B65535]\"\nSet rs = CreateObject(\"ADODB.Recordset\")\nrs.Open query, cn, adOpenStatic, adLockOptimistic\n\nrs.AddNew\nrs(\"First\") = \"George\"\nrs(\"Last\") = \"Washington\"\nrs.Update\n\nrs.MoveFirst\nDo Until rs.EOF\n WScript.Echo rs.Fields(\"First\") & \" \" & rs.Fields(\"Last\")\n rs.MoveNext\nLoop\n</code></pre>\n\n<p>At a command prompt, type:</p>\n\n<pre><code>CSCRIPT Yourfile.vbs\n</code></pre>\n\n<p>It will add a name to the spreadsheet and then write out all the names.</p>\n\n<pre><code>Joe Smith\nMary Jones\nSam Nelson\nGeorge Washington\n</code></pre>\n"
},
{
"answer_id": 254228,
"author": "Onorio Catenacci",
"author_id": 2820,
"author_profile": "https://Stackoverflow.com/users/2820",
"pm_score": -1,
"selected": false,
"text": "<p>I believe the simple answer to your question is no because you need the Excel COM object which is only installed when Excel is installed. This used to be one of the real drawbacks of writing an Office app--the need for the entire application (Excel, Word or whatever) in order for an end-user to use it.</p>\n"
},
{
"answer_id": 254602,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This is the final version of the script I used, thank you all for the help.</p>\n\n<pre><code>Dim arrValue\narrValue = Array(\"Test\",\"20\",\"\",\"I\",\"2.25\",\"3.9761\",\"20\",\"60\",\"12\",\"1\",\"\",\"1\",\"1\",\"1\")\nAddXLSRow \"C:\\Test.xls\", \"A1:N109\", arrValue\n\nSub AddXLSRow(strSource, strRange, arrValues)\n'This routine uses the data from an array to fill fields in the specified spreadsheet.\n'Input strSource (String) = The Full path and filename of the spreadsheet to be used.\n'Input arrValues (Array) = An array of values to be added to the spreadsheet.\nDim strConnection, conn, rs, strSQL, index\n\nstrConnection = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" & strSource & \";Extended Properties=\"\"Excel 8.0;HDR=Yes;\"\";\"\n\nSet conn = CreateObject(\"ADODB.Connection\")\nconn.Open strConnection\nSet rs = CreateObject(\"ADODB.recordset\")\nstrSQL = \"SELECT * FROM \" & strRange\nrs.open strSQL, conn, 3,3\nrs.AddNew \nindex = 0\nFor Each field In rs.Fields\n If field.Type = 202 Then\n field.value = arrValues(index)\n ElseIffield.Type = 5 And arrValues(index) <> \"\" Then\n field.value = CDbl(arrValues(index))\n End If\n If NOT index >= UBound(arrValues) Then\n index = index + 1\n End If\nNext\nrs.Update\nrs.Close\nSet rs = Nothing\nconn.Close\nSet conn = Nothing\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 254749,
"author": "BobC",
"author_id": 31167,
"author_profile": "https://Stackoverflow.com/users/31167",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry to be late to the party. The fact that no one's mentioned <a href=\"http://msdn.microsoft.com/en-us/office/aa905533.aspx\" rel=\"nofollow noreferrer\">VSTO</a> probably means that I'm misunderstanding the question. And at any rate I've heard mixed reviews from folks using it.</p>\n"
},
{
"answer_id": 5765581,
"author": "UnderCoverGuy",
"author_id": 721916,
"author_profile": "https://Stackoverflow.com/users/721916",
"pm_score": 1,
"selected": false,
"text": "<p>I know...years later but today I needed to figure out how to access an Excel spreadsheet using vbScript without loading Excel on my server. I searched around the net and found your information helpful, but I still needed more so I kept searching. I finally found the solution that I needed and wanted to share it here just in case anyone else has the same issues that as I did.</p>\n\n<p>I was trying to access (read/write) an Excel spreadsheet using vbScript on a Windows 2008 server and I didn't want to install Excel on my server. My solution was here (it uses PowerShell but it is easy to decypher to VBS):</p>\n\n<p><a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/2008/09/11/how-can-i-read-from-excel-without-using-excel.aspx\" rel=\"nofollow\">Using vbScript to read from an Excel spreadsheet without Excel installed</a></p>\n\n<p><a href=\"http://blogs.technet.com/b/heyscriptingguy/archive/2008/09/15/how-can-i-write-to-excel-without-using-excel.aspx\" rel=\"nofollow\">Using vbScript to write to an Excel spreadsheet without Excel installed</a></p>\n\n<p>I hope that this helps someone that needs the same solution in the future.</p>\n\n<p>L8r...</p>\n\n<p>UCG</p>\n"
},
{
"answer_id": 13858538,
"author": "rgshenoy",
"author_id": 1218945,
"author_profile": "https://Stackoverflow.com/users/1218945",
"pm_score": -1,
"selected": false,
"text": "<p>Use EPPlus. \nepplus.codeplex.com</p>\n\n<p>You can do most things that you can do with VSTO, without excel installed.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to add a row to a spreadsheet using VBScript on a PC that does not have Microsoft Office installed.
I tried [`Set objExcel = CreateObject("Excel.Application")`]
Since Excel does not exist on the PC I cannot create this object.
Is there a way to modify a spreadsheet without Excel?
|
To use the code below, create an Excel workbook named "Test.xls" in the same folder as the vbscript file.
In Test.xls, enter the following data in cells A1 thru B4:
```
First Last
Joe Smith
Mary Jones
Sam Nelson
```
Paste the vbscript code below into a .vbs file:
```
Const adOpenStatic = 3
Const adLockOptimistic = 3
filename = "Test.xls"
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filename & _
";Extended Properties=Excel 8.0"
query = "Select * from [Sheet1$A1:B65535]"
Set rs = CreateObject("ADODB.Recordset")
rs.Open query, cn, adOpenStatic, adLockOptimistic
rs.AddNew
rs("First") = "George"
rs("Last") = "Washington"
rs.Update
rs.MoveFirst
Do Until rs.EOF
WScript.Echo rs.Fields("First") & " " & rs.Fields("Last")
rs.MoveNext
Loop
```
At a command prompt, type:
```
CSCRIPT Yourfile.vbs
```
It will add a name to the spreadsheet and then write out all the names.
```
Joe Smith
Mary Jones
Sam Nelson
George Washington
```
|
253,399 |
<p>Delphi (and probably a lot of other languages) has class helpers. These provide a way to add extra methods to an existing class. Without making a subclass.</p>
<p>So, what are good uses for class helpers?</p>
|
[
{
"answer_id": 253400,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 4,
"selected": false,
"text": "<p>At first I was kind of sceptic about class helpers. But then I read an interesting <a href=\"http://blogs.conceptfirst.com/blog/2006/05/08/class-helpers-good-or-bad/\" rel=\"noreferrer\">blog entry</a> and now I'm convinced that they are indeed useful.</p>\n\n<p>For example, if you want extra functionality for an existing instance class and for some reason you are not able to change the existing source. You can create a class helper to add this functionality. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>type\n TStringsHelper = class helper for TStrings\n public\n function IsEmpty: Boolean;\n end;\n\nfunction TStringsHelper.IsEmpty: Boolean;\nbegin\n Result := Count = 0;\nend;\n</code></pre>\n\n<p>Every time, we now use an instance of (a subclass of) TStrings, and TStringsHelper is within the scope. We have access to the method IsEmpty. </p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nbegin\n if Memo1.Lines.IsEmpty then\n Button1.Caption := 'Empty'\n else\n Button1.Caption := 'Filled';\nend;\n</code></pre>\n\n<p><strong>Notes:</strong></p>\n\n<ul>\n<li>Class helpers can be stored in a separate unit, so you can add your own nifty class helpers. Be sure to give these units a easy to remember name like ClassesHelpers for helpers for the Classes unit.</li>\n<li>There are also record helpers.</li>\n<li>If there are multiple class helpers within scope, expect some problems, only one helper can be used.</li>\n</ul>\n"
},
{
"answer_id": 253421,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>This sounds very much like extension methods in C#3 (and VB9). The best use I've seen for them is the extensions to <code>IEnumerable<T></code> (and <code>IQueryable<T></code>) which lets LINQ work against arbitrary sequences:</p>\n\n<pre><code>var query = someOriginalSequence.Where(person => person.Age > 18)\n .OrderBy(person => person.Name)\n .Select(person => person.Job);\n</code></pre>\n\n<p>(or whatever, of course). All of this is doable because extension methods allow you to effectively chain together calls to static methods which take the same type as they return.</p>\n"
},
{
"answer_id": 253471,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 6,
"selected": true,
"text": "<p>I'm using them:</p>\n\n<ul>\n<li>To <a href=\"http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-5-class.html\" rel=\"noreferrer\" title=\"Class helper enumerators\">insert enumerators</a> into VCL classes that don't implement them.</li>\n<li>To <a href=\"http://gp.17slon.com/gp/gpstreams.htm\" rel=\"noreferrer\" title=\"GpStreams\">enhance</a> VCL classes.</li>\n<li><p>To add methods to the TStrings class so I can use the same methods in <a href=\"http://gp.17slon.com/gp/gplists.htm\" rel=\"noreferrer\" title=\"GpLists\">my derived lists</a> and in TStringList.</p>\n\n<pre><code>TGpStringListHelper = class helper for TStringList\npublic\n function Last: string;\n function Contains(const s: string): boolean;\n function FetchObject(const s: string): TObject;\n procedure Sort;\n procedure Remove(const s: string);\nend; { TGpStringListHelper }\n</code></pre></li>\n<li><p>To simplify access to record fields and <a href=\"http://17slon.com/blogs/gabr/2008/03/walking-key-value-container.html\" rel=\"noreferrer\" title=\"Walking the key-value container\">remove casting</a>.</p></li>\n</ul>\n"
},
{
"answer_id": 253636,
"author": "Robert Walker",
"author_id": 28300,
"author_profile": "https://Stackoverflow.com/users/28300",
"pm_score": 2,
"selected": false,
"text": "<p>The first time I remember experiencing what you're calling \"class helpers\" was while learning Objective C. Cocoa (Apple's Objective C framework) uses what are called \"Categories.\"</p>\n\n<p>A category allows you to extend an existing class by adding you own methods without subclassing. In fact Cocoa encourages you to avoid subclassing when possible. Often it makes sense to subclass, but often it can be avoided using categories.</p>\n\n<p>A good example of the use of a category in Cocoa is what's called \"Key Value Code (KVC)\" and \"Key Value Observing (KVO).\"</p>\n\n<p>This system is implemented using two categories (NSKeyValueCoding and NSKeyValueObserving). These categories define and implement methods that can be added to any class you want. For example Cocoa adds \"conformance\" to KVC/KVO by using these categories to add methods to NSArray such as:</p>\n\n<pre><code>- (id)valueForKey:(NSString *)key\n</code></pre>\n\n<p>NSArray class does not have either a declaration nor an implementation of this method. However, through use of the category. You can call that method on any NSArray class. You are not required to subclass NSArray to gain KVC/KVO conformance.</p>\n\n<pre><code>NSArray *myArray = [NSArray array]; // Make a new empty array\nid myValue = [myArray valueForKey:@\"name\"]; // Call a method defined in the category\n</code></pre>\n\n<p>Using this technique makes it easy to add KVC/KVO support to your own classes. Java interfaces allow you to add method declarations, but categories allow you to also add the actual implementations to existing classes.</p>\n"
},
{
"answer_id": 253697,
"author": "Uwe Raabe",
"author_id": 26833,
"author_profile": "https://Stackoverflow.com/users/26833",
"pm_score": 2,
"selected": false,
"text": "<p>As GameCat shows, TStrings is a good candidate to avoid some typing:</p>\n\n<pre><code>type\n TMyObject = class\n public\n procedure DoSomething;\n end;\n\n TMyObjectStringsHelper = class helper for TStrings\n private\n function GetMyObject(const Name: string): TMyObject;\n procedure SetMyObject(const Name: string; const Value: TMyObject);\n public\n property MyObject[const Name: string]: TMyObject read GetMyObject write SetMyObject; default;\n end;\n\nfunction TMyObjectStringsHelper.GetMyObject(const Name: string): TMyObject;\nvar\n idx: Integer;\nbegin\n idx := IndexOf(Name);\n if idx < 0 then\n result := nil\n else\n result := Objects[idx] as TMyObject;\nend;\n\nprocedure TMyObjectStringsHelper.SetMyObject(const Name: string; const Value:\n TMyObject);\nvar\n idx: Integer;\nbegin\n idx := IndexOf(Name);\n if idx < 0 then\n AddObject(Name, Value)\n else\n Objects[idx] := Value;\nend;\n\nvar\n lst: TStrings;\nbegin\n ...\n lst['MyName'] := TMyObject.Create; \n ...\n lst['MyName'].DoSomething;\n ...\nend;\n</code></pre>\n\n<hr>\n\n<p>Did you ever need to access multi line strings in the registry?</p>\n\n<pre><code>type\n TRegistryHelper = class helper for TRegistry\n public\n function ReadStrings(const ValueName: string): TStringDynArray;\n end;\n\nfunction TRegistryHelper.ReadStrings(const ValueName: string): TStringDynArray;\nvar\n DataType: DWord;\n DataSize: DWord;\n Buf: PChar;\n P: PChar;\n Len: Integer;\n I: Integer;\nbegin\n result := nil;\n if RegQueryValueEx(CurrentKey, PChar(ValueName), nil, @DataType, nil, @DataSize) = ERROR_SUCCESS then begin\n if DataType = REG_MULTI_SZ then begin\n GetMem(Buf, DataSize + 2);\n try\n if RegQueryValueEx(CurrentKey, PChar(ValueName), nil, @DataType, PByte(Buf), @DataSize) = ERROR_SUCCESS then begin\n for I := 0 to 1 do begin\n if Buf[DataSize - 2] <> #0 then begin\n Buf[DataSize] := #0;\n Inc(DataSize);\n end;\n end;\n\n Len := 0;\n for I := 0 to DataSize - 1 do\n if Buf[I] = #0 then\n Inc(Len);\n Dec(Len);\n if Len > 0 then begin\n SetLength(result, Len);\n P := Buf;\n for I := 0 to Len - 1 do begin\n result[I] := StrPas(P);\n Inc(P, Length(P) + 1);\n end;\n end;\n end;\n finally\n FreeMem(Buf, DataSize);\n end;\n end;\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 254877,
"author": "Mason Wheeler",
"author_id": 32914,
"author_profile": "https://Stackoverflow.com/users/32914",
"pm_score": 2,
"selected": false,
"text": "<p>They're very useful for plug-ins. For example, let's say your project defines a certain data structure and it's saved to disc in a certain way. But then some other program does something very similar, but the data file's different. But you don't want to bloat your EXE with a bunch of import code for a feature that a lot of your users won't need to use. You can use a plugin framework and put importers into a plugin that would work like this:</p>\n\n<pre><code>type\n TCompetitionToMyClass = class helper for TMyClass\n public\n constructor Convert(base: TCompetition);\n end;\n</code></pre>\n\n<p>And then define the converter. One caveat: a class <em>helper</em> is not a class <em>friend</em>. This technique will only work if it's possible to completely setup a new TMyClass object through its public methods and properties. But if you can, it works really well.</p>\n"
},
{
"answer_id": 483060,
"author": "Jamo",
"author_id": 32303,
"author_profile": "https://Stackoverflow.com/users/32303",
"pm_score": 0,
"selected": false,
"text": "<p>I've seen them used for making available class methods consistent across classes: Adding Open/Close and Show/Hide to all classes of a given \"type\" rather than only Active and Visible properties. </p>\n"
},
{
"answer_id": 1081613,
"author": "mjn",
"author_id": 80901,
"author_profile": "https://Stackoverflow.com/users/80901",
"pm_score": 2,
"selected": false,
"text": "<p>I would not recommend to use them, since I read this comment:</p>\n\n<blockquote>\n <p>\"The biggest problem with class\n helpers, from the p.o.v of using them\n in your own applications, is the fact\n that only ONE class helper for a given\n class may be in scope at any time.\"\n ... \"That is, if you have two helpers\n in scope, only ONE will be recognised\n by the compiler. You won't get any\n warnings or even hints about any other\n helpers that may be hidden.\"</p>\n</blockquote>\n\n<p><a href=\"http://davidglassborow.blogspot.com/2006/05/class-helpers-good-or-bad.html\" rel=\"nofollow noreferrer\">http://davidglassborow.blogspot.com/2006/05/class-helpers-good-or-bad.html</a></p>\n"
},
{
"answer_id": 69827499,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 0,
"selected": false,
"text": "<p><em>If</em> Dephi supported extension methods, one use i want is:</p>\n<pre><code>TGuidHelper = class\npublic\n class function IsEmpty(this Value: TGUID): Boolean;\nend;\n\nclass function TGuidHelper(this Value: TGUID): Boolean;\nbegin\n Result := (Value = TGuid.Empty);\nend;\n</code></pre>\n<p>So i can call <code>if customerGuid.IsEmpty then ...</code>.</p>\n<p>Another good example is to be able to read values from an XML document (or JSON if you're into that sort of thing) with the <code>IDataRecord</code> paradigm (which i love):</p>\n<pre><code>orderGuid := xmlDocument.GetGuid('/Order/OrderID');\n</code></pre>\n<p>Which is much better than:</p>\n<pre><code>var\n node: IXMLDOMNode;\n\n node := xmlDocument.selectSingleNode('/Order/OrderID');\n if Assigned(node) then\n orderID := StrToGuid(node.Text) //throw convert error on empty or invalid\n else\n orderID := TGuid.Empty; // "DBNull" becomes the null guid\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18061/"
] |
Delphi (and probably a lot of other languages) has class helpers. These provide a way to add extra methods to an existing class. Without making a subclass.
So, what are good uses for class helpers?
|
I'm using them:
* To [insert enumerators](http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-5-class.html "Class helper enumerators") into VCL classes that don't implement them.
* To [enhance](http://gp.17slon.com/gp/gpstreams.htm "GpStreams") VCL classes.
* To add methods to the TStrings class so I can use the same methods in [my derived lists](http://gp.17slon.com/gp/gplists.htm "GpLists") and in TStringList.
```
TGpStringListHelper = class helper for TStringList
public
function Last: string;
function Contains(const s: string): boolean;
function FetchObject(const s: string): TObject;
procedure Sort;
procedure Remove(const s: string);
end; { TGpStringListHelper }
```
* To simplify access to record fields and [remove casting](http://17slon.com/blogs/gabr/2008/03/walking-key-value-container.html "Walking the key-value container").
|
253,403 |
<p>I am developing a java web app using servlet, in order to prevent user from hitting the back button to see previous users' info, I have the following code :</p>
<pre><code> protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession(true);
response.setContentType("text/html");
response.setHeader("Cache-Control","no-cache,no-store");
response.setDateHeader("Expires",0);
response.setHeader("Pragma","no-cache");
......
// if (!User_Logged_In)
session.invalidate();
}
</code></pre>
<p>Besides I also have the following code in the file : web/WEB-INF/web.xml</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
......
<filter>
<filter-name>ResponseHeaderFilter</filter-name>
<filter-class>ResponseHeaderFilter</filter-class>
<init-param>
<param-name>Cache-Control</param-name>
<param-value>private,no-cache,no-store</param-value>
</init-param>
<init-param>
<param-name>Pragma</param-name>
<param-value>no-cache</param-value>
</init-param>
<init-param>
<param-name>Expires</param-name>
<param-value>0</param-value>
</init-param>
</filter>
</web-app>
</code></pre>
<p>And the ResponseHeaderFilter.java looks like this :</p>
<pre><code>import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ResponseHeaderFilter implements Filter
{
FilterConfig fc;
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException
{
HttpServletResponse response=(HttpServletResponse)res;
for (Enumeration e=fc.getInitParameterNames();e.hasMoreElements();) // Set the provided HTTP response parameters
{
String headerName=(String)e.nextElement();
response.addHeader(headerName,fc.getInitParameter(headerName));
}
chain.doFilter(req,response); // Pass the request/response on
}
public void init(FilterConfig filterConfig)
{
this.fc=filterConfig;
}
public void destroy()
{
this.fc=null;
}
}
</code></pre>
<p>So far it's still not working correctly. The back button will bring up a warning window saying the data has expired, it asks if the user wants to repost it. If you choose yes, it will still display the previous pages info. What am I doing wrong? What's the fix ?</p>
<p>Frank</p>
<hr>
<p>Yes, I am developing a web app for a PC in public place, if user B hits the back button he might see user A's private info.</p>
<p>I was trying to use session id with servlet, but how to do it, any sample code ?</p>
<p>I also tried the following :</p>
<pre><code><Html>
<Head>...</Head>
<Body onLoad=document.execCommand("ClearAuthenticationCache","false")>
......
<script type="text/javascript">
// Clear current credentials : Requires IE6 SP1 or later
// document.execCommand("ClearAuthenticationCache");
document.execCommand("ClearAuthenticationCache","false");
</script>
......
</Html>
</code></pre>
<p>It works for IE but but Firefox.</p>
|
[
{
"answer_id": 253417,
"author": "Omar Kooheji",
"author_id": 20400,
"author_profile": "https://Stackoverflow.com/users/20400",
"pm_score": 2,
"selected": false,
"text": "<p>Breaking the back button is a cardinal sin of web development.</p>\n\n<p>but you could try a bit of java script in the onload that refreshed the details according to the currently logged in session.</p>\n"
},
{
"answer_id": 253434,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure if I understand your problem exactly. Are you concerned about Person A logging off, Person B logs in from the same PC and browser instance, and then you want to prevent Person B from seeing whatever A was viewing?</p>\n\n<p>If so, it should be sufficient to check the credentials of the user on every page load. Check that the current user is authorized to view the data being requested.</p>\n"
},
{
"answer_id": 253442,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 4,
"selected": false,
"text": "<p>How will hitting the back button cause the user to see <em>another</em> user's data? What is your use case? Is it designed for a public terminal, where each user submits data and then leaves? In this case, associate each input with a unique session id. Keep track of valid session ids in your server. Once the input is submitted, remove that session id from the valid ids. If it comes up again, then don't display the information.</p>\n"
},
{
"answer_id": 253465,
"author": "catfood",
"author_id": 12802,
"author_profile": "https://Stackoverflow.com/users/12802",
"pm_score": 3,
"selected": false,
"text": "<p>Your problem is that you're trying to keep the client from seeing what's on his or her own computer. You can't keep them from looking at their browser cache. You can't keep them from disabling JavaScript (and thus your scripting code). You can't keep them from using a browser that doesn't observe that \"repost\" convention that you mention.</p>\n\n<p>This is not a problem that can be solved with JavaScript or a server-side solution. That part of why \"breaking the back button\" is frowned upon: it doesn't actually solve anything.</p>\n"
},
{
"answer_id": 253476,
"author": "MBoy",
"author_id": 15511,
"author_profile": "https://Stackoverflow.com/users/15511",
"pm_score": -1,
"selected": false,
"text": "<p>I had a similar problem in .Net. I added the following javascript to my logout page:</p>\n\n<p>document.execCommand(\"ClearAuthenticationCache\",\"false\");</p>\n\n<p>now if you press the back button you need to authenticate again.</p>\n"
},
{
"answer_id": 253489,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like your real problem is that the re-post works. That would probably be because you:</p>\n\n<ol>\n<li>are trusting credentials from the browser rather than the current session, or </li>\n<li>are not checking that the current session is allowed access the data represented by a key/identifier value sent from the browser</li>\n</ol>\n\n<p>I recommend that after a user has logged in you never trust a user name submitted by the browser. Ideally use the security services of a framework like <a href=\"http://static.springframework.org/spring-security/site/\" rel=\"nofollow noreferrer\">Spring Security</a> but in their absence you can rely on <a href=\"http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal()\" rel=\"nofollow noreferrer\">HttpServletRequest.getUserPrincipal()</a>. </p>\n\n<p>To make sure the current session is allowed access the data you could use an Access Control List mechanism provided by a framework such as Spring Security or include a <code>WHERE OWNER=?</code> clause in your database queries.</p>\n"
},
{
"answer_id": 253528,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>If you're worried about someone seeing what was in a form in a previous page you could use a hidden form for the \"real\" post and use one that's just for display for the user. When the user submits the display form, you copy all of the fields to the hidden form, clear the display form, then submit the hidden one.</p>\n\n<p>I agree with everyone else - fiddling with the back button this is a bad way to handle protecting information.</p>\n"
},
{
"answer_id": 253638,
"author": "Instantsoup",
"author_id": 9861,
"author_profile": "https://Stackoverflow.com/users/9861",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not 100% sure this is a fix to your issue, as I don't fully understand how you would get another user's data using back. However, I know that for the web apps I develop I try to exclusively use <a href=\"http://en.wikipedia.org/wiki/Post/Redirect/Get\" rel=\"nofollow noreferrer\">Redirect After Post</a> to avoid back button and refresh duplicate form submissions.</p>\n"
},
{
"answer_id": 253719,
"author": "Huibert Gill",
"author_id": 1254442,
"author_profile": "https://Stackoverflow.com/users/1254442",
"pm_score": 0,
"selected": false,
"text": "<p>Jeff Atwood described a way to prevent CSRF and XSRF attacks <a href=\"https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You could use this technique to solve your \"<em>users seeing what they should not see</em>\" problem.</p>\n"
},
{
"answer_id": 254016,
"author": "Steve Bosman",
"author_id": 4389,
"author_profile": "https://Stackoverflow.com/users/4389",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure I understand your problem correctly, but it sounds like you are allowing rePOSTs.</p>\n\n<p>One approach to prevent resubmission is to use tokens. Put a random token in the form and session. On submission check that the submitted token matches the token in the session </p>\n\n<ul>\n<li>if it does, replace the token in the session with a fresh one and process the request</li>\n<li>otherwise stop processing the request).</li>\n</ul>\n"
},
{
"answer_id": 254959,
"author": "laz",
"author_id": 8753,
"author_profile": "https://Stackoverflow.com/users/8753",
"pm_score": 1,
"selected": false,
"text": "<p>All of the different browsers have different behaviors and quirks when it comes to how history relates to the cache and the various headers available to control it. Firefox 3 works differently from Firefox 2, re-displaying potentially sensitive data when a user clicks the back button in spite of using caching directives to prevent it. The best solution is to use a session cookie that is not persisted and inform the user of the need to close the browser window after logging out. Especially if they are at a public terminal. Painful, I know, but current browser offerings and the HTTP specification do not provide any mechanisms for dealing with browser history. History may be treated differently than caching by a user agent according to the HTTP specification. See <a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-13.13\" rel=\"nofollow noreferrer\" title=\"13.13 History Lists\">13.13 History Lists</a> as defined in RFC 2616 Hypertext Transfer Protocol -- HTTP/1.1 for the problem and rationale.</p>\n"
},
{
"answer_id": 309060,
"author": "David Kolar",
"author_id": 3283,
"author_profile": "https://Stackoverflow.com/users/3283",
"pm_score": 0,
"selected": false,
"text": "<p>I think this is as much a user interface challenge as a coding problem. On top of whatever anti-caching techniques you employ, you need to make it clear to the user that they must hit a big, obvious \"Logout\" button (or equivalent) when they are done. </p>\n"
},
{
"answer_id": 341099,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if this might help. This works for ASP, use an equivalent solution for other languages.</p>\n\n\n\n\n\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32834/"
] |
I am developing a java web app using servlet, in order to prevent user from hitting the back button to see previous users' info, I have the following code :
```
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
HttpSession session=request.getSession(true);
response.setContentType("text/html");
response.setHeader("Cache-Control","no-cache,no-store");
response.setDateHeader("Expires",0);
response.setHeader("Pragma","no-cache");
......
// if (!User_Logged_In)
session.invalidate();
}
```
Besides I also have the following code in the file : web/WEB-INF/web.xml
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
......
<filter>
<filter-name>ResponseHeaderFilter</filter-name>
<filter-class>ResponseHeaderFilter</filter-class>
<init-param>
<param-name>Cache-Control</param-name>
<param-value>private,no-cache,no-store</param-value>
</init-param>
<init-param>
<param-name>Pragma</param-name>
<param-value>no-cache</param-value>
</init-param>
<init-param>
<param-name>Expires</param-name>
<param-value>0</param-value>
</init-param>
</filter>
</web-app>
```
And the ResponseHeaderFilter.java looks like this :
```
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ResponseHeaderFilter implements Filter
{
FilterConfig fc;
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException
{
HttpServletResponse response=(HttpServletResponse)res;
for (Enumeration e=fc.getInitParameterNames();e.hasMoreElements();) // Set the provided HTTP response parameters
{
String headerName=(String)e.nextElement();
response.addHeader(headerName,fc.getInitParameter(headerName));
}
chain.doFilter(req,response); // Pass the request/response on
}
public void init(FilterConfig filterConfig)
{
this.fc=filterConfig;
}
public void destroy()
{
this.fc=null;
}
}
```
So far it's still not working correctly. The back button will bring up a warning window saying the data has expired, it asks if the user wants to repost it. If you choose yes, it will still display the previous pages info. What am I doing wrong? What's the fix ?
Frank
---
Yes, I am developing a web app for a PC in public place, if user B hits the back button he might see user A's private info.
I was trying to use session id with servlet, but how to do it, any sample code ?
I also tried the following :
```
<Html>
<Head>...</Head>
<Body onLoad=document.execCommand("ClearAuthenticationCache","false")>
......
<script type="text/javascript">
// Clear current credentials : Requires IE6 SP1 or later
// document.execCommand("ClearAuthenticationCache");
document.execCommand("ClearAuthenticationCache","false");
</script>
......
</Html>
```
It works for IE but but Firefox.
|
How will hitting the back button cause the user to see *another* user's data? What is your use case? Is it designed for a public terminal, where each user submits data and then leaves? In this case, associate each input with a unique session id. Keep track of valid session ids in your server. Once the input is submitted, remove that session id from the valid ids. If it comes up again, then don't display the information.
|
253,410 |
<p>Alright, I know how the <code>fieldset</code>/<code>legend</code> works out in HTML. Say you have a form with some fields:</p>
<pre><code><form>
<fieldset>
<legend>legend</legend>
<input name="input1" />
</fieldset>
</form>
</code></pre>
<p>What should I use the <code>legend</code> for? It's being displayed as a <strong>title</strong>, but isn't a legend semantically an explanation of the contents? In my view, preferably you'd do something like this:</p>
<pre><code><form>
<fieldset>
<legend>* = required</legend>
<label for="input1">input 1 *</label><input id="input1" name="input1" />
</fieldset>
</form>
</code></pre>
<p>But that doesn't really work out with how fieldsets are rendered. Is this just a ambigious naming in HTML, or is it my misunderstanding of the English word 'legend'?</p>
<hr>
<p>Edit: fixed some errors ;-)</p>
|
[
{
"answer_id": 253413,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, the naming is ambiguous. It’s best to consider it as a caption for the fieldset.</p>\n\n<p>See <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.10\" rel=\"nofollow noreferrer\">the HTML spec on <code>FIELDSET</code> and <code>LEGEND</code> elements</a> if you haven’t already:</p>\n\n<blockquote>\n <p>The <a href=\"http://www.w3.org/TR/html401/interact/forms.html#edef-LEGEND\" rel=\"nofollow noreferrer\"><code>LEGEND</code></a> element allows authors to assign a caption to a <a href=\"http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET\" rel=\"nofollow noreferrer\"><code>FIELDSET</code></a>. The legend improves accessibility when the <a href=\"http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET\" rel=\"nofollow noreferrer\"><code>FIELDSET</code></a> is rendered non-visually.</p>\n</blockquote>\n"
},
{
"answer_id": 253419,
"author": "Dan Maharry",
"author_id": 2756,
"author_profile": "https://Stackoverflow.com/users/2756",
"pm_score": 1,
"selected": false,
"text": "<p>I guess you meant to write</p>\n\n<pre><code><form>\n <fieldset>\n <legend>legend</legend>\n <input name=\"input1\" />\n </fieldset>\n</form>\n</code></pre>\n\n<p>but you're right in part. The word legend has several meanings including</p>\n\n<ul>\n<li>An explanatory caption accompanying\nan illustration. </li>\n<li>An explanatory\ntable or list of the symbols\nappearing on a map or chart.</li>\n</ul>\n\n<p>So it can in fact mean both.</p>\n"
},
{
"answer_id": 253423,
"author": "FOR",
"author_id": 27826,
"author_profile": "https://Stackoverflow.com/users/27826",
"pm_score": 1,
"selected": false,
"text": "<p>When you say that the legend \"It's being displayed as a title\".. clearly it depends on the CSS involved. When you don't specify CSS yourself, each browser uses its own built-in styles, which may or may not be the best thing ever.</p>\n\n<p>I agree that a legend is different than a title... I don't necessarily think that the legend is the right place for something like \"* = required\" (that seems just a cautionary piece of information for the user, not really an explanation of the fieldset itself). </p>\n\n<p>A legend, after all, can be defined as a caption, or brief description accompanying an illustration (usually; something other than an image in this case).</p>\n\n<p>As far as how it gets displayed, again, CSS gives you power to make it appear (or not) as you see fit.</p>\n"
},
{
"answer_id": 253430,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 1,
"selected": false,
"text": "<p>Think of the legend as a title of a groupbox. You use it to group similar form elements together. You could have all of the input fields for a shipping address in one fieldset with a legend of \"Shipping Address\" and the set of all input fields for a billing address in another fieldset with a legend of \"Billing Address\".</p>\n\n<p>Here's an example:</p>\n\n<p><a href=\"http://piasecki.name/fieldset-legend-example.jpg\" rel=\"nofollow noreferrer\">Fieldsets in Skiviez Checkout http://piasecki.name/fieldset-legend-example.jpg</a></p>\n\n<p>They can be tricky to style via CSS (because Internet Explorer displays the background of the fieldset incorrectly. <a href=\"http://www.skiviez.com/Styles/Skiviez-InternetExplorer7.css\" rel=\"nofollow noreferrer\">Our IE stylesheet</a> has some good examples; look in the \"#content form fieldset\" section.</p>\n"
},
{
"answer_id": 253449,
"author": "Már Örlygsson",
"author_id": 16271,
"author_profile": "https://Stackoverflow.com/users/16271",
"pm_score": 1,
"selected": false,
"text": "<p>The <code><legend></code> element is the semantic equivalent of a \"headline\" or \"title\" for the group of form controls contained by the <a href=\"http://www.w3.org/TR/html401/interact/forms.html#h-17.10\" rel=\"nofollow noreferrer\"><code><fieldset></code></a>.</p>\n\n<blockquote>\n <p>The FIELDSET element allows authors to group thematically related controls</p>\n</blockquote>\n\n<p>which means <code>fieldset</code>s should group together <em>several</em> form controls -- not just a single pair of <code><input></code> and <code><legend></code>.</p>\n\n<p>In fact <code><div></code>s, <code><p></code>s, or <code><li></code>s are quite suitable containers for <code><input></code> + <code><legend></code> pairs.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/909/"
] |
Alright, I know how the `fieldset`/`legend` works out in HTML. Say you have a form with some fields:
```
<form>
<fieldset>
<legend>legend</legend>
<input name="input1" />
</fieldset>
</form>
```
What should I use the `legend` for? It's being displayed as a **title**, but isn't a legend semantically an explanation of the contents? In my view, preferably you'd do something like this:
```
<form>
<fieldset>
<legend>* = required</legend>
<label for="input1">input 1 *</label><input id="input1" name="input1" />
</fieldset>
</form>
```
But that doesn't really work out with how fieldsets are rendered. Is this just a ambigious naming in HTML, or is it my misunderstanding of the English word 'legend'?
---
Edit: fixed some errors ;-)
|
Yes, the naming is ambiguous. It’s best to consider it as a caption for the fieldset.
See [the HTML spec on `FIELDSET` and `LEGEND` elements](http://www.w3.org/TR/html401/interact/forms.html#h-17.10) if you haven’t already:
>
> The [`LEGEND`](http://www.w3.org/TR/html401/interact/forms.html#edef-LEGEND) element allows authors to assign a caption to a [`FIELDSET`](http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET). The legend improves accessibility when the [`FIELDSET`](http://www.w3.org/TR/html401/interact/forms.html#edef-FIELDSET) is rendered non-visually.
>
>
>
|
253,415 |
<p>I'm having trouble getting the right number of elements in the ArrayList <code>alt</code> in the JSP page below. When I view the JSP it shows the size is 1 (<code><%=alt.size()%></code>) when it should be 3; I think I'm adding that method to the array in the generator class, so I don't understand why it's showing 1.</p>
<p>This is my jsp page:</p>
<pre><code><%
ArrayList<Alert> a = AlertGenerator.getAlert();
pageContext.setAttribute("alt", a);
%>
<c:forEach var="alert" items="${alt}" varStatus="status" >
<p>You have <%=alt.size()%> Active Alert(s)</p>
<ul>
<li><a href="#" class="linkthree">${alert.alert1}</a></li>
<li><a href="#" class="linkthree">${alert.alert2}</a></li>
<li><a href="#" class="linkthree">${alert.alert3}</a></li>
</ul>
</c:forEach>
</code></pre>
<p>This is class that generates the alerts:</p>
<pre><code>package com.cg.mock;
import java.util.ArrayList;
public class AlertGenerator {
public static ArrayList<Alert> getAlert() {
ArrayList<Alert> alt = new ArrayList<Alert>();
alt.add(new Alert("alert1","alert2","alert3"));
return alt;
}
}
</code></pre>
<p>This is my bean class:</p>
<pre><code>package com.cg.mock;
public class Alert {
String alert1;
String alert2;
String alert3;
public Alert(String alert1, String alert2,String alert3) {
super();
this.alert1 = alert1;
this.alert2 = alert2;
this.alert3 = alert3;
}
public String getAlert1() {
return alert1;
}
public void setAlert1(String alert1) {
this.alert1 = alert1;
}
public String getAlert2() {
return alert2;
}
public void setAlert2(String alert2) {
this.alert2 = alert2;
}
public String getAlert3() {
return alert3;
}
public void setAlert3(String alert3) {
this.alert3 = alert3;
}
}
</code></pre>
|
[
{
"answer_id": 253432,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 1,
"selected": false,
"text": "<p>Why are you expecting it to return <code>3</code> when you've only <code>add</code>ed one item to the <code>List</code>?</p>\n"
},
{
"answer_id": 253433,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is you have only one Alert instance in your ArrayList, but that single Alert has 3 properties: alert1, alert2, and alert3.</p>\n\n<p>Take a look at the line:</p>\n\n<pre><code>alt.add(new Alert(\"alert1\",\"alert2\",\"alert3\"));\n</code></pre>\n\n<p>You only have one add line, and it is not in a loop.</p>\n\n<p>A possible solution:</p>\n\n<pre><code>public class Alert {\n private String description;\n private String status;\n private Date raisedOn;\n public Alert(String description, String status) {\n this.description = description;\n this.status = status;\n this.raisedOn = new Date();\n }\n public String getDescription() { return description; }\n public String getStatus() { return status; }\n public Date getRaisedOn() { return raisedOn; }\n}\n\n\n....\nalt.add(new Alert(\"Disk Almost Full\", \"Warning\"));\nalt.add(new Alert(\"Disk Full\", \"Severe\"));\n...\n\n...\n<table>\n <tr><th>Description</th><th>Status</th><th>Raised</th></td>\n <c:forEach var=\"alert\" items=\"${alt}\">\n <tr>\n <td><c:out value=\"${alert.description}\"/></td>\n <td><c:out value=\"${alert.status}\"/></td>\n <td><c:out value=\"${alert.raisedOn}\"/></td>\n </tr>\n </c:forEach>\n</table>\n</code></pre>\n"
},
{
"answer_id": 253436,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": 0,
"selected": false,
"text": "<p>The ArrayList contains ONLY one element Alert (the element Alert contains three Strings alerts.</p>\n"
},
{
"answer_id": 253601,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 1,
"selected": true,
"text": "<p>To get 3 Alerts you can redesign as follows. Notice that there is only one property of the alert class. You can create a new instance of the Alert for each alert.</p>\n\n<pre><code>package com.cg.mock;\n\npublic class Alert {\n String alert1;\n public Alert(String alert1) {\n super();\n this.alert1 = alert1; \n }\n public String getAlert1() {\n return alert1;\n }\n public void setAlert1(String alert1) {\n this.alert1 = alert1;\n }\n}\n</code></pre>\n\n<p>In the AlertGenerator:</p>\n\n<pre><code>ArrayList<Alert> alt = new ArrayList<Alert>();\n\nalt.add(new Alert(\"alert1\");\nalt.add(new Alert(\"alert2\");\nalt.add(new Alert(\"alert3\");\n\nreturn alt;\n</code></pre>\n\n<p>And on the JSP:</p>\n\n<pre><code><p>You have <%=alt.size()%> Active Alert(s)</p>\n<ul>\n<c:forEach var=\"alert\" items=\"${alt}\" varStatus=\"status\" > \n\n <li><a href=\"#\" class=\"linkthree\">${alert.alert1}</a></li>\n\n </c:forEach>\n </ul>\n</code></pre>\n\n<p>Notice the ul's are outside the forEach loop.</p>\n"
},
{
"answer_id": 253623,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "<p>Change your JSP to:</p>\n\n<pre><code><%\n ArrayList<Alert> a = AlertGenerator.getAlert();\n pageContext.setAttribute(\"alt\", a);\n%>\n<p>You have <%=alt.size()%> Active Alert(s)</p>\n<ul>\n <c:forEach var=\"alert\" items=\"${alt}\" varStatus=\"status\" >\n <li><a href=\"#\" class=\"linkthree\">${alert.alert}</a></li>\n </c:forEach>\n</ul>\n</code></pre>\n\n<p>Change AlertGenerator.java to:</p>\n\n<pre><code>package com.cg.mock;\n\nimport java.util.ArrayList;\n\npublic class AlertGenerator {\n\n public static ArrayList<Alert> getAlert() {\n\n ArrayList<Alert> alt = new ArrayList<Alert>();\n\n alt.add(new Alert(\"alert2\"));\n alt.add(new Alert(\"alert2\"));\n alt.add(new Alert(\"alert3\"));\n\n return alt;\n }\n}\n</code></pre>\n\n<p>Change Alert.java to:</p>\n\n<pre><code>package com.cg.mock;\n\npublic class Alert {\n String alert;\n public Alert(String alert) {\n this.alert = alert;\n }\n public String getAlert() {\n return alert;\n }\n public void setAlert(String alert) {\n this.alert = alert;\n }\n}\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28557/"
] |
I'm having trouble getting the right number of elements in the ArrayList `alt` in the JSP page below. When I view the JSP it shows the size is 1 (`<%=alt.size()%>`) when it should be 3; I think I'm adding that method to the array in the generator class, so I don't understand why it's showing 1.
This is my jsp page:
```
<%
ArrayList<Alert> a = AlertGenerator.getAlert();
pageContext.setAttribute("alt", a);
%>
<c:forEach var="alert" items="${alt}" varStatus="status" >
<p>You have <%=alt.size()%> Active Alert(s)</p>
<ul>
<li><a href="#" class="linkthree">${alert.alert1}</a></li>
<li><a href="#" class="linkthree">${alert.alert2}</a></li>
<li><a href="#" class="linkthree">${alert.alert3}</a></li>
</ul>
</c:forEach>
```
This is class that generates the alerts:
```
package com.cg.mock;
import java.util.ArrayList;
public class AlertGenerator {
public static ArrayList<Alert> getAlert() {
ArrayList<Alert> alt = new ArrayList<Alert>();
alt.add(new Alert("alert1","alert2","alert3"));
return alt;
}
}
```
This is my bean class:
```
package com.cg.mock;
public class Alert {
String alert1;
String alert2;
String alert3;
public Alert(String alert1, String alert2,String alert3) {
super();
this.alert1 = alert1;
this.alert2 = alert2;
this.alert3 = alert3;
}
public String getAlert1() {
return alert1;
}
public void setAlert1(String alert1) {
this.alert1 = alert1;
}
public String getAlert2() {
return alert2;
}
public void setAlert2(String alert2) {
this.alert2 = alert2;
}
public String getAlert3() {
return alert3;
}
public void setAlert3(String alert3) {
this.alert3 = alert3;
}
}
```
|
To get 3 Alerts you can redesign as follows. Notice that there is only one property of the alert class. You can create a new instance of the Alert for each alert.
```
package com.cg.mock;
public class Alert {
String alert1;
public Alert(String alert1) {
super();
this.alert1 = alert1;
}
public String getAlert1() {
return alert1;
}
public void setAlert1(String alert1) {
this.alert1 = alert1;
}
}
```
In the AlertGenerator:
```
ArrayList<Alert> alt = new ArrayList<Alert>();
alt.add(new Alert("alert1");
alt.add(new Alert("alert2");
alt.add(new Alert("alert3");
return alt;
```
And on the JSP:
```
<p>You have <%=alt.size()%> Active Alert(s)</p>
<ul>
<c:forEach var="alert" items="${alt}" varStatus="status" >
<li><a href="#" class="linkthree">${alert.alert1}</a></li>
</c:forEach>
</ul>
```
Notice the ul's are outside the forEach loop.
|
253,426 |
<p>Working with TCL and I'd like to implement something like the <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">Strategy Pattern</a>. I want to pass in the "strategy" for printing output in a TCL function, so I can easily switch between printing to the screen and printing to a log file. What's the best way to do this in TCL?</p>
|
[
{
"answer_id": 253459,
"author": "Tom",
"author_id": 26155,
"author_profile": "https://Stackoverflow.com/users/26155",
"pm_score": 0,
"selected": false,
"text": "<p>How about using variable functions? I don't remember much TCL (it's been a while...) but maybe one of these would do what you need:<br></p>\n\n<ul>\n<li>[$var param1 param2]</li>\n<li>[$var] param1 param2</li>\n<li>$var param1 param2</li>\n</ul>\n\n<p>If i'm wrong, anyone is free to correct me.</p>\n"
},
{
"answer_id": 254632,
"author": "Jackson",
"author_id": 29061,
"author_profile": "https://Stackoverflow.com/users/29061",
"pm_score": 5,
"selected": true,
"text": "<p>TCL allows you to store the name of a procedure in a variable and then call the procedure using that variable; so</p>\n\n<pre><code>proc A { x } {\n puts $x\n}\n\nset strat A\n$strat Hello\n</code></pre>\n\n<p>will call the proc A and print out Hello</p>\n"
},
{
"answer_id": 255441,
"author": "ramanman",
"author_id": 11093,
"author_profile": "https://Stackoverflow.com/users/11093",
"pm_score": 2,
"selected": false,
"text": "<p>A slightly expanded example of what was listed above that might illustrate the Strategy Pattern more clearly:</p>\n\n<pre><code>proc PrintToPDF {document} {\n<snip logic>\n}\n\nproc PrintToScreen {document} {\n<snip logic>\n}\n\nproc PrintToPrinter {document} {\n<snip logic>\n}\n\n\nset document \"my cool formatted document here\"\n\nset printMethod \"printer\"\n\n\nswitch -- $printMethod {\n \"printer\" {\n set pMethodName \"PrintToPrinter\"\n }\n \"pdf\" {\n set pMethodName \"PrintToScreen\"\n }\n \"screen\" {\n set pMethodName \"PrintToPDF\"\n }\n}\n\n$pMethodName $document\n</code></pre>\n"
},
{
"answer_id": 274443,
"author": "Michael Mathews",
"author_id": 21242,
"author_profile": "https://Stackoverflow.com/users/21242",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to the answer showing how you assign a procedure to a variable, you can also pass the name of a procedure as an argument to another procedure. Here's a simple example:</p>\n\n<pre><code>\nproc foo { a } {\n puts \"a = $a\"\n}\n\nproc bar { b } {\n puts \"b = $b\"\n}\n\nproc foobar { c } {\n $c 1\n}\n\nfoobar foo\nfoobar bar\n</code></pre>\n\n<p>This will print a = 1 and b = 1</p>\n"
},
{
"answer_id": 659289,
"author": "bta",
"author_id": 79566,
"author_profile": "https://Stackoverflow.com/users/79566",
"pm_score": 0,
"selected": false,
"text": "<p>To clarify why Jackson's method works, remember that in TCL, <em>everything</em> is a string. Whether you are working with a literal string, a function, a variable, or whatever it may be, <em>everything</em> is a string. You can pass a \"function pointer\" just like you can a \"data pointer\": simply use the object's name with no leading \"$\".</p>\n"
},
{
"answer_id": 1181202,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 2,
"selected": false,
"text": "<p>Aside from using a proc, you could actually use a code block instead. There are a few variations on this. first is the most obvious, just <code>eval</code>ing it.</p>\n\n<pre><code>set strategy {\n puts $x\n}\n\nset x \"Hello\"\neval $strategy\nunset x\n</code></pre>\n\n<p>This works, but there are a few downsides. First the obvious, both pieces of code must collude to using a common naming for the arguments. This replaces one namespace headache (procs) with another (locals), and this is arguably actually <em>worse</em>.</p>\n\n<p>Less obvious is that eval deliberately interprets its argument without compiling bytecode. This is because it is assumed that eval will be called with dynamically generated, usually unique arguments, and compiling to bytecode would be inefficient if the bytecode would only be used once, relative to just interpreting the block immediately. This is easier to fix, so here's the idiom:</p>\n\n<pre><code>set x \"Hello\"\nif 1 $strategy\nunset x\n</code></pre>\n\n<p><code>if</code>, unlike <code>eval</code>, does compile and cache its code block. If the <code>$strategy</code> block is only ever one or just a handful of different possible values, then this works very well. </p>\n\n<p>This doesn't help at all with the yuckiness of passing arguments to the block with local variables. There are a lot of ways around that, such as doing <a href=\"http://www.tcl.tk/man/tcl8.5/TclCmd/string.htm#M39\" rel=\"nofollow noreferrer\">substitutions</a> in the same way tk does substitutions on command arguments with <code>%</code>'s. You can try doing some hackish things using up <code>uplevel</code> or <code>upvar</code>. For example you could do this:</p>\n\n<pre><code>set strategy {\n puts %x\n}\n\nif 1 [string map [list %% % %x Hello] $strategy]\n</code></pre>\n\n<p>On the off chance that the arguments being passed don't change very much, this works well in terms of bytecode compilation. If on the other hand, the argument changes often, you should use <code>eval</code> instead of <code>if 1</code>. This isn't much better anyway, in terms of arguments. There's less likelyhood of confusion about what's passed and what's not, because you're using a special syntax. Also this is helpful in case you want to use variable substitution before returning a code block: as in <code>set strategy \"$localvar %x\"</code>. </p>\n\n<p>Fortunately, tcl 8.5 has <a href=\"http://www.tcl.tk/man/tcl8.5/TclCmd/apply.htm\" rel=\"nofollow noreferrer\">true anonymous functions</a>, using the <code>apply</code> command. The first word to the apply command would be a list of the arguments and body, as if those arguments to <code>proc</code> had been lifted out. The remaining arguments are passed to the anonymous command as arguments immediately. </p>\n\n<pre><code>set strategy [list {x} {\n puts $x\n}]\n\napply $strategy \"Hello\"\n</code></pre>\n"
},
{
"answer_id": 1292509,
"author": "name",
"author_id": 158263,
"author_profile": "https://Stackoverflow.com/users/158263",
"pm_score": 1,
"selected": false,
"text": "<pre><code>% set val 4444\n4444\n\n% set pointer val\nval\n\n% eval puts $$pointer\n4444\n\n% puts [ set $pointer ]\n4444\n\n% set tmp [ set $pointer ]\n4444\n</code></pre>\n"
},
{
"answer_id": 50622878,
"author": "user1134991",
"author_id": 1134991,
"author_profile": "https://Stackoverflow.com/users/1134991",
"pm_score": 0,
"selected": false,
"text": "<p>All what stated above, although when moving from namespace to namespace, you may want to use as a passing <code>[namespace current ]::proc_name</code>, for ensuring that you don't get any breaks.<br>For OO methods, you'll need to follow what is in this thread:<a href=\"https://stackoverflow.com/questions/41737116/pass-a-method-of-a-specific-object-as-an-input-argument-in-tcl\">Pass a method of a specific object as an input argument in Tcl</a>\n<br>Godspeed.</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1541/"
] |
Working with TCL and I'd like to implement something like the [Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern). I want to pass in the "strategy" for printing output in a TCL function, so I can easily switch between printing to the screen and printing to a log file. What's the best way to do this in TCL?
|
TCL allows you to store the name of a procedure in a variable and then call the procedure using that variable; so
```
proc A { x } {
puts $x
}
set strat A
$strat Hello
```
will call the proc A and print out Hello
|
253,431 |
<p>I have a WPF control, that has a list of "Investors", and in the right column of the list, a "Delete" button.</p>
<p>I could either waste some time making an image of an "x" in photoshop. Or, I could just use Wingdings font and set the content to "Õ" (which makes a cool looking delete button).</p>
<p>Is this appropriate? My thinking is... while not every font family is on every computer, I'm pretty sure that it's safe to say that if you're running my WPF Windows Forms program, then you have Wingdings.</p>
<p>What do you think? Please try to give statistics (not just feelings) on the matter. Should I worry about font size? etc.</p>
|
[
{
"answer_id": 253444,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 5,
"selected": true,
"text": "<p>Honestly, if you're using WPF, it's probably just as easy to use a path to make an 'x' shape:</p>\n\n<pre><code> <Style x:Key=\"DeleteButtonStyle\" TargetType=\"{x:Type Button}\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Stretch\"/>\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Center\"/>\n <Setter Property=\"VerticalAlignment\" Value=\"Stretch\"/>\n <Setter Property=\"VerticalContentAlignment\" Value=\"Center\"/>\n <Setter Property=\"Cursor\" Value=\"Hand\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Button}\">\n <Grid HorizontalAlignment=\"Center\" VerticalAlignment=\"Center\">\n <Path Name=\"Circle\" Data=\"F1 M 0 7.5 A 7.5 7.5 0 1 1 15 7.5 A 7.5 7.5 0 1 1 0 7.5\"/>\n <Path Fill=\"White\" Data=\"F1 M 7.5 6 L 10.5,3 12,4.5 9,7.5 12,10.5 10.5,12 7.5,9 4.5,12 3,10.5 6,7.5 3,4.5 4.5,3 Z\"/>\n </Grid>\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsMouseOver\" Value=\"True\">\n <Setter Property=\"Fill\" TargetName=\"Circle\" Value=\"SlateGray\"/>\n </Trigger>\n <Trigger Property=\"IsMouseOver\" Value=\"False\">\n <Setter Property=\"Fill\" TargetName=\"Circle\" Value=\"DarkGray\"/>\n </Trigger>\n <DataTrigger Binding=\"{Binding}\" Value=\"{x:Null}\">\n <Setter Property=\"Visibility\" Value=\"Hidden\"/>\n </DataTrigger>\n </ControlTemplate.Triggers>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n <Setter Property=\"ToolTip\" Value=\"Delete This Item\"/>\n </Style>\n</code></pre>\n\n<p>Just apply this style to a button, and you get an instant \"delete\" button!</p>\n"
},
{
"answer_id": 253453,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming you can display Unicode, there are plenty of glyphs in many fonts for what you're trying to do.</p>\n\n<p>For example, this is a unicode character in (probably) Arial: ✖</p>\n\n<p>I took the character reference from <a href=\"http://www1.tip.nl/~t876506/UnicodeDisplay.html\" rel=\"nofollow noreferrer\">http://www1.tip.nl/~t876506/UnicodeDisplay.html</a> but I'm sure there are better places to find out than this</p>\n"
},
{
"answer_id": 253457,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry, but I can't think of anything that makes an application look more amateurish than the use of wingding characters for controls.</p>\n"
},
{
"answer_id": 253483,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should be fine, especially with WPF. I don't know if Wingdings font in particular is on every Windows machine (probably yes), but I do know characters from Marlett font are used in Win XP UI. </p>\n"
},
{
"answer_id": 852476,
"author": "Tomáš Kafka",
"author_id": 38729,
"author_profile": "https://Stackoverflow.com/users/38729",
"pm_score": 2,
"selected": false,
"text": "<p>I think that nice solution would be taking the glyphs you like from Wingdings, and converting them to WPF shapes, as resources of your app. This will add just a few kB to your app and you won't be dependent on Wingdings.</p>\n"
},
{
"answer_id": 1981969,
"author": "imam kuncoro",
"author_id": 241120,
"author_profile": "https://Stackoverflow.com/users/241120",
"pm_score": 0,
"selected": false,
"text": "<p>Most of the problem was forgetting to add the byte size. </p>\n\n<p>In C# (Winform) I use:</p>\n\n<pre><code>static Font wingdings2 = new Font(\"Wingdings 2\", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(2)));\n</code></pre>\n\n<p>So I can :</p>\n\n<pre><code>myTextBoxt.Font = wingdings2;\n</code></pre>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11917/"
] |
I have a WPF control, that has a list of "Investors", and in the right column of the list, a "Delete" button.
I could either waste some time making an image of an "x" in photoshop. Or, I could just use Wingdings font and set the content to "Õ" (which makes a cool looking delete button).
Is this appropriate? My thinking is... while not every font family is on every computer, I'm pretty sure that it's safe to say that if you're running my WPF Windows Forms program, then you have Wingdings.
What do you think? Please try to give statistics (not just feelings) on the matter. Should I worry about font size? etc.
|
Honestly, if you're using WPF, it's probably just as easy to use a path to make an 'x' shape:
```
<Style x:Key="DeleteButtonStyle" TargetType="{x:Type Button}">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
<Path Name="Circle" Data="F1 M 0 7.5 A 7.5 7.5 0 1 1 15 7.5 A 7.5 7.5 0 1 1 0 7.5"/>
<Path Fill="White" Data="F1 M 7.5 6 L 10.5,3 12,4.5 9,7.5 12,10.5 10.5,12 7.5,9 4.5,12 3,10.5 6,7.5 3,4.5 4.5,3 Z"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Fill" TargetName="Circle" Value="SlateGray"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="False">
<Setter Property="Fill" TargetName="Circle" Value="DarkGray"/>
</Trigger>
<DataTrigger Binding="{Binding}" Value="{x:Null}">
<Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ToolTip" Value="Delete This Item"/>
</Style>
```
Just apply this style to a button, and you get an instant "delete" button!
|
253,435 |
<p>I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object.</p>
<p>Ok so tried calling the Image.Clone function. This still locks the file.</p>
<p>hmm. Next I try loading a Bitmap Image from a FileStream and load the image into memory so GDI+ doesn't lock the file. This works great except I need to generate thumbnails using Image.GetThumbnailImage method it throws an out of memory exception. Apparently I need to keep the stream open to stop this exception but if I keep the stream open then the file remains locked.</p>
<p>So no good with that method. In the end I created a copy of the file. So now I have 2 versions of the file. 1 I can lock and manipulate in my c# program. This other original file remains unlocked to which I can save modifications to. This has the bonus of allowing me to revert changes even after saving them because I'm manipulating the copy of the file which cant change.</p>
<p>Surely there is a better way of achieving this without having to have 2 versions of the image file. Any ideas?</p>
|
[
{
"answer_id": 253493,
"author": "Sciolist",
"author_id": 16045,
"author_profile": "https://Stackoverflow.com/users/16045",
"pm_score": 2,
"selected": false,
"text": "<p>Well if you're looking for other ways to do what you're asking, I reckon it should work to create a MemoryStream, and read out the FileStream to it, and load the Image from that stream...</p>\n\n<pre><code>var stream = new FileStream(\"original-image\", FileMode.Open);\nvar bufr = new byte[stream.Length];\nstream.Read(bufr, 0, (int)stream.Length);\nstream.Dispose();\n\nvar memstream = new MemoryStream(bufr);\nvar image = Image.FromStream(memstream);\n</code></pre>\n\n<p>Or something prettier to that extent.</p>\n\n<p>Whether or not that's the way you should go about solving that problem, I don't know. :) \nI've had a similar problem and wound up fixing it like this.</p>\n"
},
{
"answer_id": 262032,
"author": "Crippeoblade",
"author_id": 6204,
"author_profile": "https://Stackoverflow.com/users/6204",
"pm_score": 3,
"selected": true,
"text": "<p>I have since found an alternative method to clone the image without locking the file. <a href=\"https://web.archive.org/web/20120419185819/http://www.bobpowell.net/imagefileconvert.htm\" rel=\"nofollow noreferrer\">Bob Powell has it all plus more GDI resources</a>.</p>\n<pre><code> //open the file\n Image i = Image.FromFile(path);\n\n //create temporary\n Image t=new Bitmap(i.Width,i.Height);\n\n //get graphics\n Graphics g=Graphics.FromImage(t);\n\n //copy original\n g.DrawImage(i,0,0);\n\n //close original\n i.Dispose();\n\n //Can now save\n t.Save(path)\n</code></pre>\n"
},
{
"answer_id": 28983950,
"author": "schlafanzug93",
"author_id": 4592266,
"author_profile": "https://Stackoverflow.com/users/4592266",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar problem. But I knew, that I will save the image as a bitmap-file. So I did this:</p>\n\n<pre><code> public void SaveHeightmap(string path)\n {\n if (File.Exists(path))\n {\n Bitmap bitmap = new Bitmap(image); //create bitmap from image\n image.Dispose(); //delete image, so the file\n\n bitmap.Save(path); //save bitmap\n\n image = (Image) bitmap; //recreate image from bitmap\n }\n else\n //...\n }\n</code></pre>\n\n<p>Sure, thats not the best way, but its working :-)</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6204/"
] |
I was loading a Bitmap Image from a File. When I tried to save the Image to another file I got the following error "A generic error occurred in GDI+". I believe this is because the file is locked by the image object.
Ok so tried calling the Image.Clone function. This still locks the file.
hmm. Next I try loading a Bitmap Image from a FileStream and load the image into memory so GDI+ doesn't lock the file. This works great except I need to generate thumbnails using Image.GetThumbnailImage method it throws an out of memory exception. Apparently I need to keep the stream open to stop this exception but if I keep the stream open then the file remains locked.
So no good with that method. In the end I created a copy of the file. So now I have 2 versions of the file. 1 I can lock and manipulate in my c# program. This other original file remains unlocked to which I can save modifications to. This has the bonus of allowing me to revert changes even after saving them because I'm manipulating the copy of the file which cant change.
Surely there is a better way of achieving this without having to have 2 versions of the image file. Any ideas?
|
I have since found an alternative method to clone the image without locking the file. [Bob Powell has it all plus more GDI resources](https://web.archive.org/web/20120419185819/http://www.bobpowell.net/imagefileconvert.htm).
```
//open the file
Image i = Image.FromFile(path);
//create temporary
Image t=new Bitmap(i.Width,i.Height);
//get graphics
Graphics g=Graphics.FromImage(t);
//copy original
g.DrawImage(i,0,0);
//close original
i.Dispose();
//Can now save
t.Save(path)
```
|
253,437 |
<p>It appears that Directory.GetFiles() in C# modifies the Last access date of a file.
I've googled for hours and can't seem to find a work around for this issue. Is there anyway to keep all the MAC (Modified, Accessed, Created) attributes of a file?
I'm using Directory.GetDirectories(), Directory.GetFiles(), and FileInfo.</p>
<p>Also, the fi.LastAccessTime is giving strange results -- the date is correct, however, the time is off by 2 minutes, or a few hours.</p>
<pre><code>Time of function execution: 10/31/2008 8:35 AM
Program Shows As Last Access Time
0_PDFIndex.html - 10/31/2008 8:17:24 AM
AdvancedArithmetic.pdf - 10/31/2008 8:31:05 AM
AdvancedControlStructures.pdf - 10/30/2008 1:18:00 PM
AoAIX.pdf - 10/30/2008 1:18:00 PM
AoATOC.pdf - 10/30/2008 12:29:51 PM
AoATOC2.pdf - 10/30/2008 1:18:00 PM
Actual Last Access Time
0_PDFIndex.html - 10/31/2008 8:17 AM
AdvancedArithmetic.pdf - 10/30/2008 12:29 PM
AdvancedControlStructures.pdf - 10/30/2008 12:29 PM
AoAIX.pdf - 10/30/2008 12:29 PM
AoATOC.pdf - 10/30/2008 12:29 PM
AoATOC2.pdf - 10/30/2008 12:29 PM
</code></pre>
<p>Below is the method I'm using. If you require more information, please let me know.</p>
<p>Thanks!</p>
<pre><code>public void PopulateTreeView(string directoryValue, ref TreeNode parentNode)
{
string[] directoryArray = Directory.GetDirectories(directoryValue);
string[] fileArray = Directory.GetFiles(directoryValue, "*.*", SearchOption.AllDirectories);
try
{
#region Directories
if (directoryArray.Length != 0)
{
foreach (string directory in directoryArray)
{
DirectoryInfo di = new DirectoryInfo(directory);
TreeNode dirNode = parentNode.Nodes.Add(di.Name);
FileNode fn = new FileNode();
fn.bIsDir = true;
fn.dir = di;
dirNode.Tag = fn;
PopulateTreeView(directory, ref dirNode);
Application.DoEvents();
}
}
#endregion
#region Files
if (fileArray.Length != 0)
{
foreach (string file in fileArray)
{
FileInfo fi = new FileInfo(file);
TreeNode fileNode = parentNode.Nodes.Add(fi.Name);
FileNode fn = new FileNode();
fn.bIsDir = false;
fn.file = fi;
fileNode.Tag = fn;
fileNode.ImageIndex = 1;
Console.WriteLine(fi.Name + " - " + fi.LastAccessTime);
}
}
#endregion
}
catch (UnauthorizedAccessException)
{
parentNode.Nodes.Add("Access denied");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Application.DoEvents();
}
}
</code></pre>
<hr>
<p>i know the differences between the attributes. What i need is for the file to remain exactly the same all attributes and meta-data, as if my program never touched the file; this includes the last access date.</p>
|
[
{
"answer_id": 253461,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": true,
"text": "<p>I know this is far from ideal, but u can use fsutil (provided with Windows) to disable last access time writing:</p>\n\n<pre><code>fsutil behavior set disablelastaccess 1\n</code></pre>\n\n<p>Presumably you'd set it back to 0 once done. You can invoke this using Process.Start from C#, but there must be a better programmatic way (calling into Windows API).</p>\n\n<pre><code>Process.Start(\"fsutil\", \"behavior set disablelastaccess 1\").WaitForExit();\n</code></pre>\n\n<p>Do note that this is a global Windows setting and would also affect disk access from outside your app...</p>\n"
},
{
"answer_id": 253538,
"author": "user22367",
"author_id": 22367,
"author_profile": "https://Stackoverflow.com/users/22367",
"pm_score": 1,
"selected": false,
"text": "<p>Access times are different from last write times. If you use fi.LastWriteTime I think you will find that the times are the same displayed in explorer or cmd window.</p>\n\n<p>Of course the last access and last write could be the same, but they are not necessarily the same.</p>\n"
},
{
"answer_id": 253555,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure if this is related or not, but from MSDN:</p>\n\n<blockquote>\n <p>When first called, FileSystemInfo\n calls Refresh and returns the cached\n information on APIs to get attributes\n and so on. On subsequent calls, you\n must call Refresh to get the latest\n copy of the information.</p>\n</blockquote>\n\n<p>BTW, \"LastAccessTime\" basically tells you the last time you \"looked at\" the file. In the absence of stale data, this would always be \"now\"... Not particularly useful, IMHO.</p>\n"
},
{
"answer_id": 253590,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Access time would show a read only marker, last write would show the file being modified.</p>\n"
},
{
"answer_id": 253657,
"author": "Tim Robinson",
"author_id": 32133,
"author_profile": "https://Stackoverflow.com/users/32133",
"pm_score": 1,
"selected": false,
"text": "<p>(Reposting this as a response rather than a comment...)</p>\n\n<p>I've just run this snippet of code here, and it's left the last access time alone - I can't reproduce the problem you're seeing, so Directory.GetFiles isn't broken 100% of the time.</p>\n\n<p>Filemon can check whether some other app is doing this: <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx</a></p>\n"
},
{
"answer_id": 253686,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't tried this, but Google suggests:</p>\n\n<p><a href=\"http://www.pctools.com/guides/registry/detail/50/\" rel=\"nofollow noreferrer\">Disable the NTFS Last Access Time Stamp</a></p>\n\n<p>It's a system-wide change, so be aware of that...</p>\n"
},
{
"answer_id": 253708,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "<p>If you're accessing the disk for forensic purposes then you really should be doing it with the entire hard disk write-protected at the hardware level (and hence this isn't really a programming question).</p>\n\n<p>A Google search for <code>hdd \"write protect\"</code> will reveal plenty of potential solutions.</p>\n"
},
{
"answer_id": 253942,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 1,
"selected": false,
"text": "<p>If you're doing forensics and you don't want the drive to be modified, why are you mounting it in a writable mode? You should be accessing it read-only to guarantee that you aren't accidentally changing something. Also, I would hope that you're not running your program in the OS of the person who's disk you're examining... you have just added the disk to a machine you control, right?</p>\n"
}
] |
2008/10/31
|
[
"https://Stackoverflow.com/questions/253437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33082/"
] |
It appears that Directory.GetFiles() in C# modifies the Last access date of a file.
I've googled for hours and can't seem to find a work around for this issue. Is there anyway to keep all the MAC (Modified, Accessed, Created) attributes of a file?
I'm using Directory.GetDirectories(), Directory.GetFiles(), and FileInfo.
Also, the fi.LastAccessTime is giving strange results -- the date is correct, however, the time is off by 2 minutes, or a few hours.
```
Time of function execution: 10/31/2008 8:35 AM
Program Shows As Last Access Time
0_PDFIndex.html - 10/31/2008 8:17:24 AM
AdvancedArithmetic.pdf - 10/31/2008 8:31:05 AM
AdvancedControlStructures.pdf - 10/30/2008 1:18:00 PM
AoAIX.pdf - 10/30/2008 1:18:00 PM
AoATOC.pdf - 10/30/2008 12:29:51 PM
AoATOC2.pdf - 10/30/2008 1:18:00 PM
Actual Last Access Time
0_PDFIndex.html - 10/31/2008 8:17 AM
AdvancedArithmetic.pdf - 10/30/2008 12:29 PM
AdvancedControlStructures.pdf - 10/30/2008 12:29 PM
AoAIX.pdf - 10/30/2008 12:29 PM
AoATOC.pdf - 10/30/2008 12:29 PM
AoATOC2.pdf - 10/30/2008 12:29 PM
```
Below is the method I'm using. If you require more information, please let me know.
Thanks!
```
public void PopulateTreeView(string directoryValue, ref TreeNode parentNode)
{
string[] directoryArray = Directory.GetDirectories(directoryValue);
string[] fileArray = Directory.GetFiles(directoryValue, "*.*", SearchOption.AllDirectories);
try
{
#region Directories
if (directoryArray.Length != 0)
{
foreach (string directory in directoryArray)
{
DirectoryInfo di = new DirectoryInfo(directory);
TreeNode dirNode = parentNode.Nodes.Add(di.Name);
FileNode fn = new FileNode();
fn.bIsDir = true;
fn.dir = di;
dirNode.Tag = fn;
PopulateTreeView(directory, ref dirNode);
Application.DoEvents();
}
}
#endregion
#region Files
if (fileArray.Length != 0)
{
foreach (string file in fileArray)
{
FileInfo fi = new FileInfo(file);
TreeNode fileNode = parentNode.Nodes.Add(fi.Name);
FileNode fn = new FileNode();
fn.bIsDir = false;
fn.file = fi;
fileNode.Tag = fn;
fileNode.ImageIndex = 1;
Console.WriteLine(fi.Name + " - " + fi.LastAccessTime);
}
}
#endregion
}
catch (UnauthorizedAccessException)
{
parentNode.Nodes.Add("Access denied");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Application.DoEvents();
}
}
```
---
i know the differences between the attributes. What i need is for the file to remain exactly the same all attributes and meta-data, as if my program never touched the file; this includes the last access date.
|
I know this is far from ideal, but u can use fsutil (provided with Windows) to disable last access time writing:
```
fsutil behavior set disablelastaccess 1
```
Presumably you'd set it back to 0 once done. You can invoke this using Process.Start from C#, but there must be a better programmatic way (calling into Windows API).
```
Process.Start("fsutil", "behavior set disablelastaccess 1").WaitForExit();
```
Do note that this is a global Windows setting and would also affect disk access from outside your app...
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.