qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
44,817 |
<p>Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security?</p>
|
[
{
"answer_id": 45891,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 3,
"selected": true,
"text": "this.DeferredLoadingEnabled = false;\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Order>(q => q.Payments);\ndlo.LoadWith<Order>(q => q.Customer);\nthis.LoadOptions = dlo;\n"
},
{
"answer_id": 49534,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 1,
"selected": false,
"text": "<mx:WebService id=\"myDataService\" showBusyCursor=\"true\">\n <mx:operation name=\"WebMethodName\" \n resultFormat=\"object\" \n result=\"functionFiredOnComplete();\">\n</mx:operation>\n</mx:WebService>\n\npublic function load():void\n{\n myDataService.loadWSDL( \"web method's wsdl\" );\n myDataService.WebMethodName.send( params );\n}\n\npublic function functionFiredOnComplete():void\n{ \n // get data\n var myData:Object = myDataService.WebMethodName.lastResult;\n ...\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
44,834 |
<p>I see <code>__all__</code> in <code>__init__.py</code> files. What does it do?</p>
|
[
{
"answer_id": 44842,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 11,
"selected": true,
"text": "import *"
},
{
"answer_id": 64130,
"author": "Alec Thomas",
"author_id": 7980,
"author_profile": "https://Stackoverflow.com/users/7980",
"pm_score": 10,
"selected": false,
"text": "__all__ from <module> import * foo.py bar baz __all__ = ['bar', 'baz']\n\nwaz = 5\nbar = 10\ndef baz(): return 'baz'\n from foo import *\n\nprint(bar)\nprint(baz)\n\n# The following will trigger an exception, as \"waz\" is not exported by the module\nprint(waz)\n __all__ import * __all__ from <module> import * __all__ from <module> import <member>"
},
{
"answer_id": 2838800,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 7,
"selected": false,
"text": "a = \"A\"\nb = \"B\"\nc = \"C\"\n __all__ = ['a', 'b']\n\na = \"A\"\nb = \"B\"\nc = \"C\"\n __all__"
},
{
"answer_id": 16595377,
"author": "MartinStettner",
"author_id": 81424,
"author_profile": "https://Stackoverflow.com/users/81424",
"pm_score": 8,
"selected": false,
"text": "__all__ __init__.py __all__ from xxx import * import __all__ __all__ from package import * __all__ __init__.py from package import * __all__"
},
{
"answer_id": 35710527,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 9,
"selected": false,
"text": "__all__ __init__.py __all__ __all__ import * __all__ module.py __all__ = ['foo', 'Bar']\n import * __all__ from module import * # imports foo and Bar\n __all__ __init__.py __init__.py __init__.py __all__ __init__.py __all__ __init__.py package\n├── __init__.py\n├── module_1.py\n└── module_2.py\n from pathlib import Path\n\npackage = Path('package')\npackage.mkdir()\n\n(package / '__init__.py').write_text(\"\"\"\nfrom .module_1 import *\nfrom .module_2 import *\n\"\"\")\n\npackage_module_1 = package / 'module_1.py'\npackage_module_1.write_text(\"\"\"\n__all__ = ['foo']\nimp_detail1 = imp_detail2 = imp_detail3 = None\ndef foo(): pass\n\"\"\")\n\npackage_module_2 = package / 'module_2.py'\npackage_module_2.write_text(\"\"\"\n__all__ = ['Bar']\nimp_detail1 = imp_detail2 = imp_detail3 = None\nclass Bar: pass\n\"\"\")\n import package\npackage.foo()\npackage.Bar()\n package __all__ __init__.py package\n├── __init__.py\n├── module_1\n│ ├── foo_implementation.py\n│ └── __init__.py\n└── module_2\n ├── Bar_implementation.py\n └── __init__.py\n subpackage_1 = package / 'module_1'\nsubpackage_1.mkdir()\nsubpackage_2 = package / 'module_2'\nsubpackage_2.mkdir()\n package_module_1.rename(subpackage_1 / 'foo_implementation.py')\npackage_module_2.rename(subpackage_2 / 'Bar_implementation.py')\n __init__.py __all__ (subpackage_1 / '__init__.py').write_text(\"\"\"\nfrom .foo_implementation import *\n__all__ = ['foo']\n\"\"\")\n(subpackage_2 / '__init__.py').write_text(\"\"\"\nfrom .Bar_implementation import *\n__all__ = ['Bar']\n\"\"\")\n >>> import package\n>>> package.foo()\n>>> package.Bar()\n<package.module_2.Bar_implementation.Bar object at 0x7f0c2349d210>\n __init__.py from .Bar_implementation import *\nfrom .Baz_implementation import *\n__all__ = ['Bar', 'Baz']\n Baz __init__.py from .module_1 import * # also constrained by __all__'s\nfrom .module_2 import * # in the __init__.py's\n__all__ = ['foo', 'Bar'] # further constraining the names advertised\n Baz import package\npackage.Baz()\n Baz from .module_1 import *\nfrom .module_2 import *\n__all__ = ['foo', 'Bar', 'Baz']\n _ __all__ _ import * import * _us_non_public us.py $ cat us.py\nUSALLCAPS = \"all caps\"\nus_snake_case = \"snake_case\"\n_us_non_public = \"shouldn't import\"\n$ python\nPython 3.10.0 (default, Oct 4 2021, 17:55:55) [GCC 10.3.0] on linux\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> from us import *\n>>> dir()\n['USALLCAPS', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'us_snake_case']\n ctypes/__init__.py import os as _os, sys as _sys\n _ _ __all__ __all__ __all__ _ __all__ export __all__ __all__ import sys\n\ndef export(fn):\n mod = sys.modules[fn.__module__]\n if hasattr(mod, '__all__'):\n mod.__all__.append(fn.__name__)\n else:\n mod.__all__ = [fn.__name__]\n return fn\n __all__ $ cat > main.py\nfrom lib import export\n__all__ = [] # optional - we create a list if __all__ is not there.\n\n@export\ndef foo(): pass\n\n@export\ndef bar():\n 'bar'\n\ndef main():\n print('main')\n\nif __name__ == '__main__':\n main()\n $ cat > run.py\nimport main\nmain.main()\n\n$ python run.py\nmain\n import * $ cat > run.py\nfrom main import *\nfoo()\nbar()\nmain() # expected to error here, not exported\n\n$ python run.py\nTraceback (most recent call last):\n File \"run.py\", line 4, in <module>\n main() # expected to error here, not exported\nNameError: name 'main' is not defined\n"
},
{
"answer_id": 36119040,
"author": "Bob Stein",
"author_id": 673991,
"author_profile": "https://Stackoverflow.com/users/673991",
"pm_score": 6,
"selected": false,
"text": "__all__ * from <module> import * from <package> import * .py __init__.py \"\"\" cheese.py - an example module \"\"\"\n\n__all__ = ['swiss', 'cheddar']\n\nswiss = 4.99\ncheddar = 3.99\ngouda = 10.99\n __all__ swiss cheddar gouda >>> from cheese import *\n>>> swiss, cheddar\n(4.99, 3.99)\n>>> gouda\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nNameError: name 'gouda' is not defined\n __all__ * __all__ >>> import cheese\n>>> cheese.swiss, cheese.cheddar, cheese.gouda\n(4.99, 3.99, 10.99)\n >>> from cheese import swiss, cheddar, gouda\n>>> swiss, cheddar, gouda\n(4.99, 3.99, 10.99)\n >>> import cheese as ch\n>>> ch.swiss, ch.cheddar, ch.gouda\n(4.99, 3.99, 10.99)\n __init__.py __all__ __all__ * __init__.py __all__ = [\n 'MySQLConnection', 'Connect', 'custom_error_exception',\n\n # Some useful constants\n 'FieldType', 'FieldFlag', 'ClientFlag', 'CharacterSet', 'RefreshOption',\n 'HAVE_CEXT',\n\n # Error handling\n 'Error', 'Warning',\n\n ...etc...\n\n ]\n __all__ __init__.py __all__ from sound.effects import * sound.effects sound.effects __init__.py __init__.py"
},
{
"answer_id": 36853901,
"author": "Mihai Capotă",
"author_id": 200234,
"author_profile": "https://Stackoverflow.com/users/200234",
"pm_score": 4,
"selected": false,
"text": "__all__ __all__ __all__ __all__ __all__ __all__ __all__ __all__ __all__ os.path __init__ __all__ __init__.py __all__ from package import *"
},
{
"answer_id": 49620866,
"author": "Cyker",
"author_id": 418966,
"author_profile": "https://Stackoverflow.com/users/418966",
"pm_score": 4,
"selected": false,
"text": "__all__ from <module> import * foo\n├── bar.py\n└── __init__.py\n foo/__init__.py __all__ from foo import * foo/__init__.py __all__ = [] from foo import * __all__ = [ <name1>, ... ] from foo import * _ __all__"
},
{
"answer_id": 54112742,
"author": "Eugene Yarmash",
"author_id": 244297,
"author_profile": "https://Stackoverflow.com/users/244297",
"pm_score": 3,
"selected": false,
"text": "__all__ from foo import * * from from foo import *\n * foo foo __all__ from foo __init__.py __all__ from foo import * __all__ from foo import * __init__.py __all__ import __all__ __all__ = ('some_name',)\n"
},
{
"answer_id": 56636531,
"author": "prosti",
"author_id": 5884955,
"author_profile": "https://Stackoverflow.com/users/5884955",
"pm_score": 2,
"selected": false,
"text": "from M import * __all__"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1794/"
] |
44,853 |
<p>I'm using ant to generate javadocs, but get this exception over and over - why?</p>
<p>I'm using JDK version <strong>1.6.0_06</strong>.</p>
<pre><code>[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681)
[javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184)
[javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158)
[javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301)
[javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124)
[javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42)
[javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91)
[javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
[javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128)
[javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41)
[javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
</code></pre>
|
[
{
"answer_id": 2030179,
"author": "KasthuriRengan",
"author_id": 246673,
"author_profile": "https://Stackoverflow.com/users/246673",
"pm_score": 1,
"selected": false,
"text": "// sample.java @ChannelPipeline\n //@ChannelPipeline\n ClassCastException"
},
{
"answer_id": 23737003,
"author": "Cataclysm",
"author_id": 1531064,
"author_profile": "https://Stackoverflow.com/users/1531064",
"pm_score": 0,
"selected": false,
"text": "<path id=\"build.classpath\">\n<fileset dir=\".\">\n <include name=\"libs/*.jar\" />\n</fileset>\n <target name=\"compile\" depends=\"clean, makedir\">\n<javac includeantruntime=\"false\" srcdir=\"${src.dir}\" destdir=\"${build.dir}\" classpathref=\"build.classpath\">\n <compilerarg value=\"-Xlint:unchecked\"/>\n</javac>\n <target name=\"docs\" depends=\"compile\">\n<javadoc packagenames=\"src\" sourcepath=\"${src.dir}\" destdir=\"${docs.dir}\" \n failonerror=\"no\"\n author=\"true\"\n version=\"true\"\n windowtitle=\"${Name} API\"\n doctitle=\"${Name}\"\n bottom=\"Copyright © 2014 ColayHIlls.com . All Rights Reserved.\">\n <fileset dir=\"${src.dir}\">\n <include name=\"main/java/com/colayhills/jpcenter/business/service/**\" />\n </fileset>\n</javadoc>\n<echo message=\"java docs has been generated!\"/>\n</target>\n classpathref=\"build.classpath\" <javadoc"
},
{
"answer_id": 40803470,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 1,
"selected": false,
"text": "ClassCastException java.lang.ClassCastException: com.sun.tools.javadoc.MethodDocImpl cannot be cast to com.sun.tools.javadoc.AnnotationTypeElementDocImpl /**\n ** {@link javax.annotation.Generated#value()}\n */\npublic class TestClass1 {}\n\n\n@Generated(\"sometext\")\npublic class TestClass2 {}\n TestClass1 ClassCastException TestClass2"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] |
44,903 |
<p>I have multiple selects:</p>
<pre><code><select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</code></pre>
<p>What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.</p>
<p>Here's the JS I have currently:</p>
<pre><code>$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
</code></pre>
<p>But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the <code>disabled</code> attribute on the option I want to remove, but that doesn't work with IE6.</p>
|
[
{
"answer_id": 45906,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "changeOnce $(function () {\n var $one = $(\"#one\");\n var $two = $(\"#two\");\n\n var selectOptions = [];\n $(\"select\").each(function (index) {\n selectOptions[index] = [];\n for (var i = 0; i < this.options.length; i++) {\n selectOptions[index][i] = this.options[i];\n }\n });\n\n var changeOnce = false;\n $one.change(function () {\n if (changeOnce) return;\n changeOnce = true;\n var selectedValue = $(\"option:selected\", this).val();\n filterSelect(selectedValue, $two, 1);\n changeOnce = false;\n });\n $two.change(function () {\n if (changeOnce) return;\n changeOnce = true;\n var selectedValue = $(\"option:selected\", this).val();\n filterSelect(selectedValue, $one, 0);\n changeOnce = false;\n });\n\n function filterSelect(selectedValue, $selectToFilter, selectIndex) {\n for (var i = 0; i < selectOptions[selectIndex].length; i++) {\n var exists = false;\n for (var x = 0; x < $selectToFilter[0].options.length; x++) {\n if ($selectToFilter[0].options[x].value == selectOptions[selectIndex][i].value)\n exists = true;\n }\n if (!exists)\n $selectToFilter.append(selectOptions[selectIndex][i]);\n }\n $(\"option[value='\" + selectedValue + \"']\", $selectToFilter).remove();\n sortSelect($selectToFilter[0]);\n }\n\n function sortSelect(selectToSort) {\n var arrOptions = [];\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n arrOptions[i] = [];\n arrOptions[i][0] = selectToSort.options[i].value;\n arrOptions[i][1] = selectToSort.options[i].text;\n arrOptions[i][2] = selectToSort.options[i].selected;\n }\n\n arrOptions.sort();\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n selectToSort.options[i].value = arrOptions[i][0];\n selectToSort.options[i].text = arrOptions[i][1];\n selectToSort.options[i].selected = arrOptions[i][2];\n }\n }\n});\n"
},
{
"answer_id": 48034,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 0,
"selected": false,
"text": "function hideSelected($one, $two)\n{\n $one.bind('change', function()\n {\n var val = $one.val();\n $two.find('option:not(:visible)').show().end()\n .find('option[value='+val+']').hide().end();\n })\n}\nhideSelected($one, $two);\nhideSelected($two, $one);\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
44,905 |
<p>When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.</p>
<p>For example (and yes, I know, if you're doing this sort of thing it probably means your <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">object-oriented</a> (OO) architecture is iffy - this is just a contrived example!),</p>
<pre><code> Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
</code></pre>
<p>Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.</p>
<p>Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement <em>has</em> to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?</p>
|
[
{
"answer_id": 44930,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "if (t == typeof(int))\n{\n...\n}\nelseif (t == typeof(string))\n{\n...\n}\n...\n"
},
{
"answer_id": 44936,
"author": "fryguybob",
"author_id": 4592,
"author_profile": "https://Stackoverflow.com/users/4592",
"pm_score": 0,
"selected": false,
"text": "if (t == typeof(int))"
},
{
"answer_id": 44941,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 3,
"selected": false,
"text": "var table = new Dictionary<Type, string>()\n{\n { typeof(int), \"it's an int!\" }\n { typeof(string), \"it's a string!\" }\n};\n\nType someType = typeof(int);\nConsole.WriteLine(table[someType]);\n"
},
{
"answer_id": 45596,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "Select Case"
},
{
"answer_id": 45765,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 5,
"selected": false,
"text": ".Equals() == void DoIt()\n{\n String foo = \"bar\";\n Switch(foo, foo);\n}\n\nvoid Switch(String val1, String val2)\n{\n switch (\"bar\")\n {\n // The compiler will not know that val1 and val2 are not distinct\n case val1:\n // Is this case block selected?\n break;\n case val2:\n // Or this one?\n break;\n case \"bar\":\n // Or perhaps this one?\n break;\n }\n}\n"
},
{
"answer_id": 48259,
"author": "Ivan Hamilton",
"author_id": 4729,
"author_profile": "https://Stackoverflow.com/users/4729",
"pm_score": 7,
"selected": false,
"text": "case 3: blah; break;\ncase 4: blah; break;\ncase 5: blah; break;\n case 10: blah; break;\ncase 200: blah; break;\ncase 3000: blah; break;\n Generic.Dictionary<string,int32> Generic.Dictionary jmp ds:300025F0[eax*4]\n cmp ebx, 79Eh\n jg 3000352B\n cmp ebx, 654h\n jg 300032BB\n …\n cmp ebx, 0F82h\n jz 30005EEE\n"
},
{
"answer_id": 952967,
"author": "Roman Starkov",
"author_id": 33080,
"author_profile": "https://Stackoverflow.com/users/33080",
"pm_score": 3,
"selected": false,
"text": "switch (true) {\n case a == 5:\n ...\n break;\n case b == 10:\n ...\n break;\n}\n if-else"
},
{
"answer_id": 2396963,
"author": "Dave Swersky",
"author_id": 34796,
"author_profile": "https://Stackoverflow.com/users/34796",
"pm_score": 2,
"selected": false,
"text": "Dictionary<Type, Func<T> Dictionary<Type, Func<object, string, string>> typeTable = new Dictionary<Type, Func<object, string, string>>();\ntypeTable.Add(typeof(int), (o, s) =>\n {\n return string.Format(\"{0}: {1}\", s, o.ToString());\n });\n"
},
{
"answer_id": 42305628,
"author": "dimaaan",
"author_id": 1802286,
"author_profile": "https://Stackoverflow.com/users/1802286",
"pm_score": 3,
"selected": false,
"text": "switch(shape)\n{\ncase Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\ncase Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\ncase Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\ndefault:\n WriteLine(\"<unknown shape>\");\n break;\ncase null:\n throw new ArgumentNullException(nameof(shape));\n}\n"
},
{
"answer_id": 60015525,
"author": "smolchanovsky",
"author_id": 10433685,
"author_profile": "https://Stackoverflow.com/users/10433685",
"pm_score": 0,
"selected": false,
"text": "public string GetTypeName(object obj)\n{\n return obj switch\n {\n int i => \"Int32\",\n string s => \"String\",\n { } => \"Unknown\",\n _ => throw new ArgumentNullException(nameof(obj))\n };\n}\n Console.WriteLine(GetTypeName(obj: 1)); // Int32\nConsole.WriteLine(GetTypeName(obj: \"string\")); // String\nConsole.WriteLine(GetTypeName(obj: 1.2)); // Unknown\nConsole.WriteLine(GetTypeName(obj: null)); // System.ArgumentNullException\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
44,912 |
<p>Does the Java language have delegate features, similar to how C# has support for delegates?</p>
|
[
{
"answer_id": 44916,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 5,
"selected": false,
"text": "delegate multicast"
},
{
"answer_id": 2075606,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 2,
"selected": false,
"text": "static private final Method COUNT =Callback.getMethod(Xxx.class,\"callback_count\",true,File.class,File.class);\n\n...\n\nIoUtil.processDirectory(root,new Callback(this,COUNT),selector);\n\n...\n\nprivate void callback_count(File dir, File fil) {\n if(fil!=null) { // file is null for processing a directory\n fileTotal++;\n if(fil.length()>fileSizeLimit) {\n throw new Abort(\"Failed\",\"File size exceeds maximum of \"+TextUtil.formatNumber(fileSizeLimit)+\" bytes: \"+fil);\n }\n }\n progress(\"Counting\",dir,fileTotal);\n }\n /**\n * Process a directory using callbacks. To interrupt, the callback must throw an (unchecked) exception.\n * Subdirectories are processed only if the selector is null or selects the directories, and are done\n * after the files in any given directory. When the callback is invoked for a directory, the file\n * argument is null;\n * <p>\n * The callback signature is:\n * <pre> void callback(File dir, File ent);</pre>\n * <p>\n * @return The number of files processed.\n */\nstatic public int processDirectory(File dir, Callback cbk, FileSelector sel) {\n return _processDirectory(dir,new Callback.WithParms(cbk,2),sel);\n }\n\nstatic private int _processDirectory(File dir, Callback.WithParms cbk, FileSelector sel) {\n int cnt=0;\n\n if(!dir.isDirectory()) {\n if(sel==null || sel.accept(dir)) { cbk.invoke(dir.getParent(),dir); cnt++; }\n }\n else {\n cbk.invoke(dir,(Object[])null);\n\n File[] lst=(sel==null ? dir.listFiles() : dir.listFiles(sel));\n if(lst!=null) {\n for(int xa=0; xa<lst.length; xa++) {\n File ent=lst[xa];\n if(!ent.isDirectory()) {\n cbk.invoke(dir,ent);\n lst[xa]=null;\n cnt++;\n }\n }\n for(int xa=0; xa<lst.length; xa++) {\n File ent=lst[xa];\n if(ent!=null) { cnt+=_processDirectory(ent,cbk,sel); }\n }\n }\n }\n return cnt;\n }\n"
},
{
"answer_id": 3953773,
"author": "Michael",
"author_id": 478586,
"author_profile": "https://Stackoverflow.com/users/478586",
"pm_score": 4,
"selected": false,
"text": "obj.registerHandler(new Handler() {\n public void handleIt(Event ev) {\n methodOne(ev);\n }\n } );\n void processState(final T1 p1, final T2 dispatch) { \n final int a1 = someCalculation();\n\n m_obj.registerHandler(new Handler() {\n public void handleIt(Event ev) {\n dispatch.methodOne(a1, ev, p1);\n }\n } );\n}\n"
},
{
"answer_id": 9232634,
"author": "Dominic Fox",
"author_id": 995737,
"author_profile": "https://Stackoverflow.com/users/995737",
"pm_score": 3,
"selected": false,
"text": " public static class TestClass {\n public String knockKnock() {\n return \"who's there?\";\n }\n }\n\n private final TestClass testInstance = new TestClass();\n\n @Test public void\n can_delegate_a_single_method_interface_to_an_instance() throws Exception {\n Delegator<TestClass, Callable<String>> knockKnockDelegator = Delegator.ofMethod(\"knockKnock\")\n .of(TestClass.class)\n .to(Callable.class);\n Callable<String> callable = knockKnockDelegator.delegateTo(testInstance);\n assertThat(callable.call(), is(\"who's there?\"));\n }\n"
},
{
"answer_id": 10137808,
"author": "Dave Cousineau",
"author_id": 621316,
"author_profile": "https://Stackoverflow.com/users/621316",
"pm_score": 6,
"selected": false,
"text": "// C#\npublic delegate void SomeFunction();\n // Java\npublic interface ISomeBehaviour {\n void SomeFunction();\n}\n // Java\npublic class TypeABehaviour implements ISomeBehaviour {\n public void SomeFunction() {\n // TypeA behaviour\n }\n}\n\npublic class TypeBBehaviour implements ISomeBehaviour {\n public void SomeFunction() {\n // TypeB behaviour\n }\n}\n SomeFunction ISomeBehaviour // C#\nSomeFunction doSomething = SomeMethod;\ndoSomething();\ndoSomething = SomeOtherMethod;\ndoSomething();\n\n// Java\nISomeBehaviour someBehaviour = new TypeABehaviour();\nsomeBehaviour.SomeFunction();\nsomeBehaviour = new TypeBBehaviour();\nsomeBehaviour.SomeFunction();\n // Java\npublic void SomeMethod(ISomeBehaviour pSomeBehaviour) {\n ...\n}\n\n...\n\nSomeMethod(new ISomeBehaviour() { \n @Override\n public void SomeFunction() {\n // your implementation\n }\n});\n // Java 8\nSomeMethod(() -> { /* your implementation */ });\n"
},
{
"answer_id": 56787211,
"author": "53c",
"author_id": 10630142,
"author_profile": "https://Stackoverflow.com/users/10630142",
"pm_score": 2,
"selected": false,
"text": "delegate private interface SingleFunc {\n void printMe();\n}\n\npublic static void main(String[] args) {\n SingleFunc sf = () -> {\n System.out.println(\"Hello, I am a simple single func.\");\n };\n SingleFunc sfComplex = () -> {\n System.out.println(\"Hello, I am a COMPLEX single func.\");\n };\n delegate(sf);\n delegate(sfComplex);\n}\n\nprivate static void delegate(SingleFunc f) {\n f.printMe();\n}\n SingleFunc printMe() delegate(SingleFunc) printMe()"
},
{
"answer_id": 62166461,
"author": "Devanshu",
"author_id": 9133555,
"author_profile": "https://Stackoverflow.com/users/9133555",
"pm_score": 0,
"selected": false,
"text": " class Class1 {\n public void show(String s) { System.out.println(s); }\n }\n\n class Class2 {\n public void display(String s) { System.out.println(s); }\n }\n\n // allows static method as well\n class Class3 {\n public static void staticDisplay(String s) { System.out.println(s); }\n }\n\n public class TestDelegate {\n public static final Class[] OUTPUT_ARGS = { String.class };\n public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);\n\n public void main(String[] args) {\n Delegate[] items = new Delegate[3];\n\n items[0] = DO_SHOW .build(new Class1(),\"show,);\n items[1] = DO_SHOW.build (new Class2(),\"display\");\n items[2] = DO_SHOW.build(Class3.class, \"staticDisplay\");\n\n for(int i = 0; i < items.length; i++) {\n items[i].invoke(\"Hello World\");\n }\n }\n }\n"
},
{
"answer_id": 63777276,
"author": "Hervian",
"author_id": 6095334,
"author_profile": "https://Stackoverflow.com/users/6095334",
"pm_score": 1,
"selected": false,
"text": " Delegate.With1Param<String, String> greetingsDelegate = new Delegate.With1Param<>();\n greetingsDelegate.add(str -> \"Hello \" + str);\n greetingsDelegate.add(str -> \"Goodbye \" + str);\n\n DelegateInvocationResult<String> invocationResult = \n greetingsDelegate.invokeAndAggregateExceptions(\"Sir\");\n\n invocationResult.getFunctionInvocationResults().forEach(funInvRes -> \n\n System.out.println(funInvRes.getResult()));\n //prints: \"Hello sir\" and \"Goodbye Sir\"\n //Create a private Delegate. Make sure it is private so only *you* can invoke it.\n private static Delegate.With0Params<String> trimDelegate = new Delegate.With0Params<>();\n\n //Create a public Event using the delegate you just created.\n public static Event.With0Params<String> trimEvent= new Event.With0Params<>(trimDelegate)\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3498/"
] |
44,914 |
<p>My app has many controls on its surface, and more are added dynamically at runtime.</p>
<p>Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).</p>
<p>What are your tips and tricks to improve WinForms app performance?</p>
|
[
{
"answer_id": 44933,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 1,
"selected": false,
"text": "SuspendLayout() ResumeLayout()"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1587/"
] |
44,917 |
<p>Is there any efficiency difference in an explicit vs implicit inner join?
For example:</p>
<pre><code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code></pre>
<p>vs.</p>
<pre><code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code></pre>
|
[
{
"answer_id": 44932,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": true,
"text": "IMPLICIT OUTER JOIN IMPLICIT INNER JOIN"
},
{
"answer_id": 44982,
"author": "deadbug",
"author_id": 4646,
"author_profile": "https://Stackoverflow.com/users/4646",
"pm_score": 3,
"selected": false,
"text": "select a.*, b.* \nfrom table a, table b \nwhere a.id *= b.id;\n"
},
{
"answer_id": 10308304,
"author": "Matt Fenwick",
"author_id": 894284,
"author_profile": "https://Stackoverflow.com/users/894284",
"pm_score": 6,
"selected": false,
"text": "mysql> explain select * from table1 a inner join table2 b on a.pid = b.pid;\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |\n| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n2 rows in set (0.02 sec)\n\nmysql> explain select * from table1 a, table2 b where a.pid = b.pid;\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |\n| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |\n+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+\n2 rows in set (0.00 sec)\n table1 table2"
},
{
"answer_id": 55950981,
"author": "Michele La Ferla",
"author_id": 1116216,
"author_profile": "https://Stackoverflow.com/users/1116216",
"pm_score": 2,
"selected": false,
"text": "SELECT * \nFROM table a, table b\nWHERE a.id = b.id (+);\n SELECT * \nFROM table a \nLEFT JOIN table b ON a.id = b.id;\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4316/"
] |
44,937 |
<p>I want to make an etag that matches what Apache produces. How does apache create it's etags?</p>
|
[
{
"answer_id": 44939,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 5,
"selected": true,
"text": "$fs = stat($file);\nheader(\"Etag: \".sprintf('\"%x-%x-%s\"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,\"0\"),10,16)));\n"
},
{
"answer_id": 6590786,
"author": "PWolanin",
"author_id": 826248,
"author_profile": "https://Stackoverflow.com/users/826248",
"pm_score": 1,
"selected": false,
"text": "sprintf('\"%x-%x-%x\"', $s['ino'], $s['size'], str_pad($s['mtime'], 16, \"0\"));\n %016x"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] |
44,942 |
<p>Can you cast a <code>List<int></code> to <code>List<string></code> somehow?</p>
<p>I know I could loop through and .ToString() the thing, but a cast would be awesome.</p>
<p>I'm in C# 2.0 (so no <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a>).</p>
|
[
{
"answer_id": 44949,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "List<T>.Convert List<int> list = new List<int>();\nlist.Add(1);\nlist.Add(2);\nlist.Add(3);\nlist.Convert(delegate (int i) { return i.ToString(); });\n"
},
{
"answer_id": 44950,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 1,
"selected": false,
"text": "List<int> List<string> List<string> List<object>"
},
{
"answer_id": 44951,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "foreach (int i in intList) stringList.Add(i.ToString());\n"
},
{
"answer_id": 44954,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 8,
"selected": true,
"text": "ConvertAll List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );\nList<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });\n"
},
{
"answer_id": 2367212,
"author": "Luke",
"author_id": 14275,
"author_profile": "https://Stackoverflow.com/users/14275",
"pm_score": 7,
"selected": false,
"text": "List<int> l1 = new List<int>(new int[] { 1,2,3 } );\nList<string> l2 = l1.ConvertAll<string>(x => x.ToString());\n"
},
{
"answer_id": 15177929,
"author": "lutecki",
"author_id": 791252,
"author_profile": "https://Stackoverflow.com/users/791252",
"pm_score": 3,
"selected": false,
"text": "List<int> items = new List<int>(new int[] { 1,2,3 } );\nList<string> s = (from i in items select i.ToString()).ToList();\n"
},
{
"answer_id": 44409533,
"author": "Jayant Rajwani",
"author_id": 3801676,
"author_profile": "https://Stackoverflow.com/users/3801676",
"pm_score": 2,
"selected": false,
"text": "result = listOfInt.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToList()"
},
{
"answer_id": 63947737,
"author": "Zuabros",
"author_id": 5045664,
"author_profile": "https://Stackoverflow.com/users/5045664",
"pm_score": 2,
"selected": false,
"text": "var stringlist = intlist.Select(x=>\"\"+x).ToList();\n var stringlist = intlist.Select(x=>$\"{x}\").ToList();\n var stringlist = intlist.Select(x=>x.ToString()).ToList();\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] |
44,961 |
<p>I've searched on the Internet for comparisons between <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a> but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p>
|
[
{
"answer_id": 44995,
"author": "Xian",
"author_id": 4642,
"author_profile": "https://Stackoverflow.com/users/4642",
"pm_score": 8,
"selected": true,
"text": "if(IsSomethingTrue() && AnotherThingTrue())\n{\n do something;\n}\n IsSomethingTrue() AnotherThingTrue()"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
44,965 |
<p>Having briefly looked at Haskell recently, what would be a <em>brief, succinct, practical</em> explanation as to what a monad essentially is?</p>
<p>I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.</p>
|
[
{
"answer_id": 45151,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 6,
"selected": false,
"text": ">>= bind return unit return >>= class Monad m where\n return :: a -> m a\n (>>=) :: forall a b . m a -> (a -> m b) -> m b\n >>= return >>= instance Monad [ ] where\n [] >>= k = []\n (x:xs) >>= k = k x ++ (xs >>= k)\n return x = [x]\n\ninstance Monad Maybe where\n Just x >>= k = k x\n Nothing >>= k = Nothing\n return x = Just x\n [] : ++ Just Nothing Maybe"
},
{
"answer_id": 71697,
"author": "Arnar",
"author_id": 10442,
"author_profile": "https://Stackoverflow.com/users/10442",
"pm_score": 8,
"selected": false,
"text": "data Wrapped a = Wrap a\n return :: a -> Wrapped a\nreturn x = Wrap x\n f :: a -> b fmap :: (a -> b) -> (Wrapped a -> Wrapped b)\nfmap f (Wrap x) = Wrap (f x)\n bind bind :: (a -> Wrapped b) -> (Wrapped a -> Wrapped b)\nbind f (Wrap x) = f x\n bind fmap fmap bind return Wrapped a return bind"
},
{
"answer_id": 86471,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": false,
"text": "Maybe IO Maybe Int Just Int Nothing Maybe Int Maybe Int Just Int Int Int Just Int Maybe Int Maybe Int Nothing Nothing Maybe Int Maybe Int Nothing Nothing Maybe IO IO IO Int Maybe"
},
{
"answer_id": 143132,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 6,
"selected": false,
"text": "T map a -> b a b T a -> T b map p q map id = id\nmap (p . q) = map p . map q\n List (a -> b) -> List a -> List b List a -> List b (a -> b) T join T (T a) -> T a unit return fork pure a -> T a join :: [[a]] -> [a]\npure :: a -> [a]\n map Join List map join bind flatMap (>>=) (=<<) join x [[[a]]] join (join x) join (map join x) pure join join (pure x) == x"
},
{
"answer_id": 194207,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 10,
"selected": false,
"text": "Array Array [1,2,3].map(x => x + 1)\n [2,3,4] [1,2,3].flatMap(x => [x + 1])\n Array flatMap [2,3,4] map flatMap [1,2,3].map(a => a + 1).filter(b => b != 3)\n [2,4] [1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])\n [2,4] [1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))\n Array<T> T flatMap() T => Array<U> Array<U> Foo<Bar> Bar => Foo<Baz> Foo<Baz> flatMap >>= [1,2,3] >>= \\a -> [a+1] >>= \\b -> if b == 3 then [] else [b] \n >>= flatMap do do a <- [1,2,3] \n b <- [a+1] \n if b == 3 then [] else [b] \n do <- Maybe Just value Nothing streetName = getStreetName (getAddress (getUser 17)) \n Nothing Nothing case getUser 17 of\n Nothing -> Nothing \n Just user ->\n case getAddress user of\n Nothing -> Nothing \n Just address ->\n getStreetName address\n Maybe do\n user <- getUser 17\n addr <- getAddress user\n getStreetName addr\n do Maybe Maybe Just value Nothing State add2 :: State Integer Integer\nadd2 = do\n -- add 1 to state\n x <- get\n put (x + 1)\n -- increment in another way\n modify (+1)\n -- return state\n get\n\n\nevalState add2 7\n=> 9\n add2 IO putStrLine readLine IO main IO IO main main IO main :: IO ()\nmain = do \n putStrLn ”Hello World”\n do () main = do\n putStrLn \"What is your name?\"\n name <- getLine\n putStrLn \"hello\" ++ name\n IO main IO Maybe Maybe IO IO IO Maybe IO Parser"
},
{
"answer_id": 885677,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "if( clause ) then block\n if"
},
{
"answer_id": 943568,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 2,
"selected": false,
"text": "a -> M<a> M<a> -> (a -> M<b>) -> M<b> a M<a> a -> M<b> M<a> -> a"
},
{
"answer_id": 3032186,
"author": "Alex",
"author_id": 125940,
"author_profile": "https://Stackoverflow.com/users/125940",
"pm_score": 3,
"selected": false,
"text": "runMyMonad monad data"
},
{
"answer_id": 4112577,
"author": "Breton",
"author_id": 51101,
"author_profile": "https://Stackoverflow.com/users/51101",
"pm_score": 6,
"selected": false,
"text": "consolestate MyConsole = new consolestate;\n consolestate FinalConsole = print(input(print(myconsole, \"Hello, what's your name?\")),\"hello, %inputbuffer%!\");\n consolestate FinalConsole = myconsole:\n print(\"Hello, what's your name?\"):\n input():\n print(\"hello, %inputbuffer%!\");\n consolestate : lift"
},
{
"answer_id": 10245311,
"author": "MathematicalOrchid",
"author_id": 1006010,
"author_profile": "https://Stackoverflow.com/users/1006010",
"pm_score": 10,
"selected": false,
"text": ">>="
},
{
"answer_id": 15733300,
"author": "snow",
"author_id": 1065942,
"author_profile": "https://Stackoverflow.com/users/1065942",
"pm_score": 1,
"selected": false,
"text": "return data (return data) >>= (return func)"
},
{
"answer_id": 20189228,
"author": "hawkeye",
"author_id": 15441,
"author_profile": "https://Stackoverflow.com/users/15441",
"pm_score": 1,
"selected": false,
"text": "\"Monads are return types that guide you through the happy path.\" -Erik Meijer\n"
},
{
"answer_id": 20707480,
"author": "samthebest",
"author_id": 1586965,
"author_profile": "https://Stackoverflow.com/users/1586965",
"pm_score": 3,
"selected": false,
"text": "trait M[+A] {\n def flatMap[B](f: A => M[B]): M[B] // AKA bind\n\n // Pseudo Meta Code\n def isValidMonad: Boolean = {\n // for every parameter the following holds\n def isAssociativeOn[X, Y, Z](x: M[X], f: X => M[Y], g: Y => M[Z]): Boolean =\n x.flatMap(f).flatMap(g) == x.flatMap(f(_).flatMap(g))\n\n // for every parameter X and x, there exists an id\n // such that the following holds\n def isAnIdentity[X](x: M[X], id: X => M[X]): Boolean =\n x.flatMap(id) == x\n }\n}\n // These could be any functions\nval f: Int => Option[String] = number => if (number == 7) Some(\"hello\") else None\nval g: String => Option[Double] = string => Some(3.14)\n\n// Observe these are identical. Since Option is a Monad \n// they will always be identical no matter what the functions are\nscala> Some(7).flatMap(f).flatMap(g)\nres211: Option[Double] = Some(3.14)\n\nscala> Some(7).flatMap(f(_).flatMap(g))\nres212: Option[Double] = Some(3.14)\n\n\n// As Option is a Monad, there exists an identity:\nval id: Int => Option[Int] = x => Some(x)\n\n// Observe these are identical\nscala> Some(7).flatMap(id)\nres213: Option[Int] = Some(7)\n\nscala> Some(7)\nres214: Some[Int] = Some(7)\n map flatten"
},
{
"answer_id": 25195169,
"author": "George",
"author_id": 1612190,
"author_profile": "https://Stackoverflow.com/users/1612190",
"pm_score": 6,
"selected": false,
"text": "bind compose (>>) (x -> y) >> (y -> z) y Mb (is_OK, b) y bool bool * float bool (Ma -> Mb) >> (Mb -> Mc) compose is_OK false bind (>>=) composition compose Bind M Ma a bind M a bind a M (a -> Mb) >>= (b -> Mc) Mb >>= (b -> Mc) shell and content bind M bind a -> Mb Mb 0 monad a Ma a -> b a -> Mb bind M let return a = [a]\nlet lift f a = return (f a)\n bind M_ \nreturn = (a -> Ma)\nf = (a -> Mb)\ng = (b -> Mc)\n Left Identity : (return a) >>= f === f a\nRight Identity : Ma >>= return === Ma\nAssociative : Ma >>= (f >>= g) === Ma >>= ((fun x -> f x) >>= g)\n Associativity bind bind Associativity binding f g Ma bind Ma f g"
},
{
"answer_id": 28924364,
"author": "Jordan",
"author_id": 972499,
"author_profile": "https://Stackoverflow.com/users/972499",
"pm_score": 3,
"selected": false,
"text": "f(<x, messages>) := <x, messages \"called f. \">\ng(<x, messages>) := <x, messages \"called g. \">\nwrap(x) := <x, \"\">\n f <x, messages> \"called f. \" g f(g(wrap(x)))\n= f(g(<x, \"\">))\n= f(<x, \"called g. \">)\n= <x, \"called g. called f. \">\n f g f g f(x) := <x, \"called f. \">\ng(x) := <x, \"called g. \">\nwrap(x) := <x, \"\">\n f(g(wrap(x)))\n= f(g(<x, \"\">))\n= f(<<x, \"\">, \"called g. \">)\n= <<<x, \"\">, \"called g. \">, \"called f. \">\n feed(f, feed(g, wrap(x)))\n= feed(f, feed(g, <x, \"\">))\n= feed(f, <x, \"called g. \">)\n= <x, \"called g. called f. \">\n feed(f, m) m f <x, messages> f x f <y, message> f <y, messages message> feed(f, <x, messages>) := let <y, message> = f(x)\n in <y, messages message>\n feed(f, wrap(x))\n= feed(f, <x, \"\">)\n= let <y, message> = f(x)\n in <y, \"\" message>\n= let <y, message> = <x, \"called f. \">\n in <y, \"\" message>\n= <x, \"\" \"called f. \">\n= <x, \"called f. \">\n= f(x)\n wrap feed(wrap, <x, messages>)\n= let <y, message> = wrap(x)\n in <y, messages message>\n= let <y, message> = <x, \"\">\n in <y, messages message>\n= <x, messages \"\">\n= <x, messages>\n x g(x) f h(x) := feed(f, g(x))\n feed(h, <x, messages>)\n= let <y, message> = h(x)\n in <y, messages message>\n= let <y, message> = feed(f, g(x))\n in <y, messages message>\n= let <y, message> = feed(f, <x, \"called g. \">)\n in <y, messages message>\n= let <y, message> = let <z, msg> = f(x)\n in <z, \"called g. \" msg>\n in <y, messages message>\n= let <y, message> = let <z, msg> = <x, \"called f. \">\n in <z, \"called g. \" msg>\n in <y, messages message>\n= let <y, message> = <x, \"called g. \" \"called f. \">\n in <y, messages message>\n= <x, messages \"called g. \" \"called f. \">\n= feed(f, <x, messages \"called g. \">)\n= feed(f, feed(g, <x, messages>))\n g f <x, \"called f. \"> x x t t M t M M M _ M int M string <M, feed, wrap> <M, feed, wrap> M feed t M u M t M u wrap v M v t u v t t feed(f, wrap(x)) = f(x) M t wrap M t feed(wrap, m) = m M t m t g M u n g n f m g n g n f feed(h, m) = feed(f, feed(g, m)) h(x) := feed(f, g(x)) feed bind >>= wrap return"
},
{
"answer_id": 34162489,
"author": "theoski",
"author_id": 598807,
"author_profile": "https://Stackoverflow.com/users/598807",
"pm_score": 2,
"selected": false,
"text": "//JavaScript is 'Practical'\nvar getAllThree = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n return bind(getThird, function(third){ \n var fancyResult = // And now make do fancy \n // with first, second,\n // and third \n return RETURN(fancyResult);\n });});}); \n {bind,RETURN,maybe others I don't know...} var fancyResultReferenceOutsideOfMonad = \n getAllThree(someKindOfInputAcceptableToOurGetFunctionsButProbablyAString); \n\n//Ignore this please, throwing away types, yay JavaScript:\n// RETURN = K\n// bind = \\getterFn,cb -> \n// \\in -> let(result,newState) = getterFn(in) in cb(result)(newState)\n var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(fancyResult2){ \n return bind(getThird, function(third){ \n var fancyResult3 = // And now make do fancy \n // with fancyResult2,\n // and third \n return RETURN(fancyResult3);\n });});\n var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(____dontCare____NotGonnaUse____){ \n return bind(getThird, function(three){ \n var fancyResult3 = // And now make do fancy \n // with `three` only!\n return RETURN(fancyResult3);\n });});\n var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(_){ \n return bind(getThird, function(three){ \n return RETURN(three);\n });});\n var getFirstTwo = \n bind(getFirst, function(first){ \n return bind(getSecond,function(second){ \n var fancyResult2 = // And now make do fancy \n // with first and second\n return RETURN(fancyResult2);\n });})\n , getAllThree = \n bind(getFirstTwo, function(_){ \n return getThird;\n });\n var getAllThree = \n bind(getFirst, function(first_dontCareNow){ \n return bind(getSecond,function(second_dontCareNow){ \n return getThird;\n });});\n chars spaces upperChars digits"
},
{
"answer_id": 37225431,
"author": "Simon",
"author_id": 742404,
"author_profile": "https://Stackoverflow.com/users/742404",
"pm_score": -1,
"selected": false,
"text": "Maybe null null Maybe object Maybe(object value, Func<object,object> function)\n{\n if(value==null)\n return null;\n\n return function(value);\n}\n var x = Maybe(x, x2 => Maybe(y, y2 => Add(x2, y2)));\n Add x y null null interface"
},
{
"answer_id": 42147263,
"author": "trevor cook",
"author_id": 5198575,
"author_profile": "https://Stackoverflow.com/users/5198575",
"pm_score": 2,
"selected": false,
"text": "{| a |m} a (I got an a!)\n / \n {| a |m}\n f a (Hi f! What should I be?)\n /\n(You?. Oh, you'll be /\n that data there.) /\n / / (I got a b.)\n| -------------- |\n| / |\nf a |\n |--later-> {| b |m}\n f (Hmm, how do I get that a?)\n o (Get lost buddy.\no Wrong type.)\no /\nf {| a |m}\n f a >>= (Muaahaha. How you \n like me now!?) \n (Better.) \\\n | (Give me that a.)\n(Fine, well ok.) |\n \\ |\n {| a |m} >>= f\n f >>= (Yah got an a for me?) \n(Yeah, but hey | \n listen. I got |\n something to |\n tell you first |\n ...) \\ /\n | /\n {| a |m} >>= f\n data Maybe a = Nothing | Just a\n Just a (Yah what is it?) \n(... hm? Oh, |\nforget about it. |\nHey a, yr up.) | \n \\ |\n(Evaluation \\ |\ntime already? \\ |\nHows my hair?) | |\n | / |\n | (It's |\n | fine.) /\n | / / \n {| a |m} >>= f\n Nothing (Yah what is it?) \n(... There |\nis no a. ) |\n | (No a?)\n(No a.) |\n | (Ok, I'll deal\n | with this.)\n \\ |\n \\ (Hey f, get lost.) \n \\ | ( Where's my a? \n \\ | I evaluate a)\n \\ (Not any more |\n \\ you don't. |\n | We're returning\n | Nothing.) /\n | | /\n | | /\n | | /\n {| a |m} >>= f (I got a b.)\n | (This is \\\n | such a \\\n | sham.) o o \\\n | o|\n |--later-> {| b |m}\n a f (Ok, here's your a. Well, its\n a bunch of them, actually.)\n |\n | (Thanks, no problem. Ok\n | f, here you go, an a.)\n | |\n | | (Thank's. See\n | | you later.)\n | (Whoa. Hold up f, |\n | I got another |\n | a for you.) |\n | | (What? No, sorry.\n | | Can't do it. I \n | | have my hands full\n | | with all these \"b\" \n | | I just made.) \n | (I'll hold those, |\n | you take this, and /\n | come back for more /\n | when you're done / \n | and we'll do it / \n | again.) /\n \\ | ( Uhhh. All right.)\n \\ | / \n \\ \\ /\n{| a |m} >>= f \n >>= f >>= a f a IO a a State st st f f a Reader r State st f r >>= f Nothing f Nothing >>= f Nothing f Maybe a Maybe b Maybe"
},
{
"answer_id": 43565185,
"author": "icc97",
"author_id": 327074,
"author_profile": "https://Stackoverflow.com/users/327074",
"pm_score": 2,
"selected": false,
"text": "map map flatMap bind flatMap concat([[1], [4], [9]]) = [1, 4, 9]\n def flatMap(func, lst):\n return concat(map(func, lst))\n\ndef concat(lst):\n return sum(lst, [])\n func lambda x: [x*x]\n concat [] + [1] + [4] + [9] = [1, 4, 9] concat map >>> list(map(lambda x: [x*x], [1,2,3]))\n[[1], [4], [9]]\n >>> flatMap(lambda x: [x*x], [1,2,3])\n[1, 4, 9]\n then flatMap instance Monad [] where \n return x = [x] \n xs >>= f = concat (map f xs) \n fail _ = [] \n return >>= flatMap fail xs >>= f = concat (map f xs)\n def flatMap(f, xs):\n return concat(map(f, xs))\n"
},
{
"answer_id": 45480927,
"author": "Jonas",
"author_id": 3741667,
"author_profile": "https://Stackoverflow.com/users/3741667",
"pm_score": 3,
"selected": false,
"text": "Monad g :: Int -> String f :: String -> Bool (f . g) x f (g x) x Int g f Maybe Int Int IO String String g1 :: Int -> Maybe String f1 :: String -> Maybe Bool g1 f1 g f (f1 . g1) x f1 (g1 x) x Int g1 f1 f g . f1 g1 . g1 f1 (f1 OPERATOR g1) x g1 f1 <=< >>= g1 x >>= f1 g1 x Maybe Int >>= Int f1 f1 Maybe Bool >>= Monad Monad >>= Eq == /= Monad >>= Monad"
},
{
"answer_id": 49086086,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "{-# LANGUAGE InstanceSigs #-}\n\nnewtype Id t = Id t\n\ninstance Monad Id where\n return :: t -> Id t\n return = Id\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n f =<< (Id x) = f x\n $ forall a b. a -> b\n ($) :: (a -> b) -> a -> b\nf $ x = f x\n\ninfixr 0 $\n f x infixl 10 . $ (.) :: (b -> c) -> (a -> b) -> (a -> c)\nf . g = \\ x -> f $ g x\n\ninfixr 9 .\n forall f g h. f . id = f :: c -> d Right identity\n id . g = g :: b -> c Left identity\n(f . g) . h = f . (g . h) :: a -> d Associativity\n . id f * -> * {-# LANGUAGE KindSignatures #-}\n\nclass Functor (f :: * -> *) where\n map :: (a -> b) -> (f a -> f b)\n forall f g. map id = id :: f t -> f t Identity\nmap f . map g = map (f . g) :: f a -> f c Composition / short cut fusion\n forall f t. Functor f => f t\n c r r c forall m a b. Functor m => a -> m b\n a m b forall m. Functor m => (m, return, (=<<))\n class Functor m => Monad m where\n return :: t -> m t\n (=<<) :: (a -> m b) -> m a -> m b\n\ninfixr 1 =<<\n return t m =<< a -> m b m a <=< (<=<) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)\nf <=< g = \\ x -> f =<< g x\n\ninfixr 1 <=<\n <=< forall f g h. f <=< return = f :: c -> m d Right identity\n return <=< g = g :: b -> m c Left identity\n(f <=< g) <=< h = f <=< (g <=< h) :: a -> m d Associativity\n <=< return type Id t = t\n Id :: * -> *\n return :: t -> Id t\n= id :: t -> t\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n= ($) :: (a -> b) -> a -> b\n\n (<=<) :: (b -> Id c) -> (a -> Id b) -> (a -> Id c)\n= (.) :: (b -> c) -> (a -> b) -> (a -> c)\n newtype Id t = Id t\n\ninstance Functor Id where\n map :: (a -> b) -> Id a -> Id b\n map f (Id x) = Id (f x)\n\ninstance Monad Id where\n return :: t -> Id t\n return = Id\n\n (=<<) :: (a -> Id b) -> Id a -> Id b\n f =<< (Id x) = f x\n data Maybe t = Nothing | Just t\n Maybe t t instance Functor Maybe where\n map :: (a -> b) -> (Maybe a -> Maybe b)\n map f (Just x) = Just (f x)\n map _ Nothing = Nothing\n\ninstance Monad Maybe where\n return :: t -> Maybe t\n return = Just\n\n (=<<) :: (a -> Maybe b) -> Maybe a -> Maybe b\n f =<< (Just x) = f x\n _ =<< Nothing = Nothing\n a -> Maybe b Maybe a newtype Nat = Nat Int\n toNat :: Int -> Maybe Nat\ntoNat i | i >= 0 = Just (Nat i)\n | otherwise = Nothing\n (-?) :: Nat -> Nat -> Maybe Nat\n(Nat n) -? (Nat m) = toNat (n - m)\n\ninfixl 6 -?\n (-? 20) <=< toNat :: Int -> Maybe Nat\n data [] t = [] | t : [t]\n\ninfixr 5 :\n (++) :: [t] -> [t] -> [t]\n(x : xs) ++ ys = x : xs ++ ys\n[] ++ ys = ys\n\ninfixr 5 ++\n [t] 0, 1, ... t instance Functor [] where\n map :: (a -> b) -> ([a] -> [b])\n map f (x : xs) = f x : map f xs\n map _ [] = []\n\ninstance Monad [] where\n return :: t -> [t]\n return = (: [])\n\n (=<<) :: (a -> [b]) -> [a] -> [b]\n f =<< (x : xs) = f x ++ (f =<< xs)\n _ =<< [] = []\n =<< ++ [b] f x a -> [b] [a] [b] n divisors :: Integral t => t -> [t]\ndivisors n = filter (`divides` n) [2 .. n - 1]\n\ndivides :: Integral t => t -> t -> Bool\n(`divides` n) = (== 0) . (n `rem`)\n forall n. let { f = f <=< divisors } in f n = []\n =<< >>= class Applicative m => Monad m where\n (>>=) :: forall a b. m a -> (a -> m b) -> m b\n\n (>>) :: forall a b. m a -> m b -> m b\n m >> k = m >>= \\ _ -> k\n {-# INLINE (>>) #-}\n\n return :: a -> m a\n return = pure\n class Functor f\nclass Functor m => Monad m\n class Functor f\nclass Functor p => Applicative p\nclass Applicative m => Monad m\n for a in (1, ..., 10)\n for b in (1, ..., 10)\n p <- a * b\n if even(p)\n yield p\n do a <- [1 .. 10]\n b <- [1 .. 10]\n let p = a * b\n guard (even p)\n return p\n [ p | a <- [1 .. 10], b <- [1 .. 10], let p = a * b, even p ]\n [1 .. 10] >>= (\\ a ->\n [1 .. 10] >>= (\\ b ->\n let p = a * b in\n guard (even p) >> -- [ () | even p ] >>\n return p\n )\n )\n let x = v in e = (\\ x -> e) $ v = v & (\\ x -> e)\ndo { r <- m; c } = (\\ r -> c) =<< m = m >>= (\\ r -> c)\n (&) :: a -> (a -> b) -> b\n(&) = flip ($)\n\ninfixl 0 &\n guard :: Additive m => Bool -> m ()\nguard True = return ()\nguard False = fail\n data () = ()\n class Monad m => Additive m where\n fail :: m t\n (<|>) :: m t -> m t -> m t\n\ninfixl 3 <|>\n\ninstance Additive Maybe where\n fail = Nothing\n\n Nothing <|> m = m\n m <|> _ = m\n\ninstance Additive [] where\n fail = []\n (<|>) = (++)\n fail <|> forall k l m. k <|> fail = k\n fail <|> l = l\n(k <|> l) <|> m = k <|> (l <|> m)\n fail _ =<< fail = fail\n guard (even p) >> return p\n even p [()] >> \\ _ -> return p\n () fail [] >> p forall st t. st -> (t, st)\n st t st type State st t = st -> (t, st)\n * -> * State st forall st a b. a -> (State st) b\n newtype State st t = State { stateProc :: st -> (t, st) }\n\ninstance Functor (State st) where\n map :: (a -> b) -> ((State st) a -> (State st) b)\n map f (State p) = State $ \\ s0 -> let (x, s1) = p s0\n in (f x, s1)\n\ninstance Monad (State st) where\n return :: t -> (State st) t\n return x = State $ \\ s -> (x, s)\n\n (=<<) :: (a -> (State st) b) -> (State st) a -> (State st) b\n f =<< (State p) = State $ \\ s0 -> let (x, s1) = p s0\n in stateProc (f x) s1\n run :: State st t -> st -> (t, st)\nrun = stateProc\n\neval :: State st t -> st -> t\neval = fst . run\n\nexec :: State st t -> st -> st\nexec = snd . run\n get put {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}\n\nclass Monad m => Stateful m st | m -> st where\n get :: m st\n put :: st -> m ()\n m -> st st m State t t instance Stateful (State st) st where\n get :: State st st\n get = State $ \\ s -> (s, s)\n\n put :: st -> State st ()\n put s = State $ \\ _ -> ((), s)\n void modify :: Stateful m st => (st -> st) -> m ()\nmodify f = do\n s <- get\n put (f s)\n\ngets :: Stateful m st => (st -> t) -> m t\ngets f = do\n s <- get\n return (f s)\n gets let s0 = 34\n s1 = (+ 1) s0\n n = (* 12) s1\n s2 = (+ 7) s1\nin (show n, s2)\n s0 :: Int (flip run) 34\n (do\n modify (+ 1)\n n <- gets (* 12)\n modify (+ 7)\n return (show n)\n )\n modify (+ 1) State Int () return () (flip run) 34\n (modify (+ 1) >>\n gets (* 12) >>= (\\ n ->\n modify (+ 7) >>\n return (show n)\n )\n )\n >>= forall m f g. (m >>= f) >>= g = m >>= (\\ x -> f x >>= g)\n do { do { do {\n r1 <- do { x <- m; r0 <- m;\n r0 <- m; = do { = r1 <- f r0;\n f r0 r1 <- f x; g r1\n }; g r1 }\n g r1 }\n} }\n for :: Monad m => (a -> m b) -> [a] -> m ()\nfor f = foldr ((>>) . f) (return ())\n\nwhile :: Monad m => m Bool -> m t -> m ()\nwhile c m = do\n b <- c\n if b then m >> while c m\n else return ()\n\nforever :: Monad m => m t\nforever m = m >> forever m\n data World\n type IO t = World -> (t, World)\n getChar :: IO Char\nputChar :: Char -> IO ()\nreadFile :: FilePath -> IO String\nwriteFile :: FilePath -> String -> IO ()\nhSetBuffering :: Handle -> BufferMode -> IO ()\nhTell :: Handle -> IO Integer\n. . . . . .\n IO IO IO unsafePerformIO :: IO t -> t\n main :: IO ()\nmain = putStrLn \"Hello, World!\"\n World -> ((), World)\n Hask T C D C D Tobj : Obj(C) -> Obj(D)\n f :: * -> *\n C D Tmor : HomC(X, Y) -> HomD(Tobj(X), Tobj(Y))\n map :: (a -> b) -> (f a -> f b)\n X Y C HomC(X, Y) X -> Y C C D Tmor Tobj\n\n T(id) = id : T(X) -> T(X) Identity\nT(f) . T(g) = T(f . g) : T(X) -> T(Z) Composition\n C <T, eta, _*>\n T : C -> C\n f eta return * =<< Hask f : X -> T(Y)\n f :: a -> m b\n (_)* : Hom(X, T(Y)) -> Hom(T(X), T(Y))\n (=<<) :: (a -> m b) -> (m a -> m b)\n Hask f* : T(X) -> T(Y)\n(f =<<) :: m a -> m b\n .T f .T g = f* . g : X -> T(Z)\nf <=< g = (f =<<) . g :: a -> m c\n eta .T g = g : Y -> T(Z) Left identity\n return <=< g = g :: b -> m c\n\n f .T eta = f : Z -> T(U) Right identity\n f <=< return = f :: c -> m d\n\n (f .T g) .T h = f .T (g .T h) : X -> T(U) Associativity\n(f <=< g) <=< h = f <=< (g <=< h) :: a -> m d\n eta .T g = g\n eta* . g = g By definition of .T\n eta* . g = id . g forall f. id . f = f\n eta* = id forall f g h. f . h = g . h ==> f = g\n\n(f .T g) .T h = f .T (g .T h)\n(f* . g)* . h = f* . (g* . h) By definition of .T\n(f* . g)* . h = f* . g* . h . is associative\n (f* . g)* = f* . g* forall f g h. f . h = g . h ==> f = g\n eta* = id : T(X) -> T(X) Left identity\n (return =<<) = id :: m t -> m t\n\n f* . eta = f : Z -> T(U) Right identity\n (f =<<) . return = f :: c -> m d\n\n (f* . g)* = f* . g* : T(X) -> T(Z) Associativity\n(((f =<<) . g) =<<) = (f =<<) . (g =<<) :: m a -> m c\n mu join mu C T : C -> C\n f :: * -> *\n eta : Id -> T\nreturn :: t -> f t\n\n mu : T . T -> T\n join :: f (f t) -> f t\n mu . T(mu) = mu . mu : T . T . T -> T . T Associativity\n join . map join = join . join :: f (f (f t)) -> f t\n\n mu . T(eta) = mu . eta = id : T -> T Identity\njoin . map return = join . return = id :: f t -> f t\n class Functor m => Monad m where\n return :: t -> m t\n join :: m (m t) -> m t\n mu instance Monad Maybe where\n return = Just\n\n join (Just m) = m\n join Nothing = Nothing\n concat concat :: [[a]] -> [a]\nconcat (x : xs) = x ++ concat xs\nconcat [] = []\n join instance Monad [] where\n return :: t -> [t]\n return = (: [])\n\n (=<<) :: (a -> [b]) -> ([a] -> [b])\n (f =<<) = concat . map f\n join mu = id* : T . T -> T\n join = (id =<<) :: m (m t) -> m t\n mu f* = mu . T(f) : T(X) -> T(Y)\n(f =<<) = join . map f :: m a -> m b\n"
},
{
"answer_id": 49341047,
"author": "Regis Kuckaertz",
"author_id": 2631185,
"author_profile": "https://Stackoverflow.com/users/2631185",
"pm_score": 0,
"selected": false,
"text": "a -> b\n a b (b -> c) -> (a -> b) -> (a -> c)\n a -> f b\n a b f (b -> f c) -> (a -> f b) -> (a -> f c)\n"
},
{
"answer_id": 50564327,
"author": "lsmor",
"author_id": 9271266,
"author_profile": "https://Stackoverflow.com/users/9271266",
"pm_score": -1,
"selected": false,
"text": "f g f g f g f g f:: AnyType -> Context[Sometype] g:: Sometype -> Context[AnyOtherType]"
},
{
"answer_id": 51680729,
"author": "schuelermine",
"author_id": 8025936,
"author_profile": "https://Stackoverflow.com/users/8025936",
"pm_score": 0,
"selected": false,
"text": "join Monad m => m (m a) -> m a return return :: Monad m => a -> m a join return join Monad m => m a -> a Monad m => m (m a) m a (>>=) fmap join x >>= f = join (fmap f x)\n(>>=) :: Monad m => (a -> m b) -> m a -> m b\n fmap join = (>>= id) IO IO getLine :: IO String IO getLine :: IO String IO a const \"üp§\" getLine const const a b = a getLine a IO a IO a IO a (>>=) >>= getLine >>= putStrLn :: IO ()\n-- putStrLn :: String -> IO ()\n do do line <- getLine\n putStrLn line\n do do x <- a\n y <- b\n z <- f x y\n w <- g z\n h x\n k <- h z\n l k w\n a >>= \\x ->\nb >>= \\y ->\nf x y >>= \\z ->\ng z >>= \\w ->\nh x >>= \\_ ->\nh z >>= \\k ->\nl k w\n >> m >>= \\_ -> f a >> b = a >>= const b const a b = a return a IO a return(a) f >>= return >>= g f >>= g Monad [] (>>=) Prelude> [1, 2, 3] >>= replicate 3 -- Simple binding\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude> concat (map (replicate 3) [1, 2, 3]) -- Same operation, more explicit\n[1, 1, 1, 2, 2, 2, 3, 3, 3]\nPrelude> [1, 2, 3] >> \"uq\"\n\"uququq\"\nPrelude> return 2 :: [Int]\n[2]\nPrelude> join [[1, 2], [3, 4]]\n[1, 2, 3, 4]\n join a = concat a\na >>= f = join (fmap f a)\nreturn a = [a] -- or \"= (:[])\"\n Nothing a >>= f a >>= f Nothing Nothing join Nothing = Nothing\njoin (Just Nothing) = Nothing\njoin (Just x) = x\na >>= f = join (fmap f a)\n Nothing >>= _ = Nothing\n(Just x) >>= f = f x\n s -> (a, s) >>= :: a -> s -> (a, s) State pop :: [a] -> (a , [a])\npop (h:t) = (h, t)\nsPop = state pop -- The module for State exports no State constructor,\n -- only a state function\n\npush :: a -> [a] -> ((), [a])\npush x l = ((), x : l)\nsPush = state push\n\nswap = do a <- sPop\n b <- sPop\n sPush a\n sPush b\n\nget2 = do a <- sPop\n b <- sPop\n return (a, b)\n\ngetswapped = do swap\n get2\n Main*> runState swap [1, 2, 3]\n((), [2, 1, 3])\nMain*> runState get2 [1, 2, 3]\n((1, 2), [1, 2, 3]\nMain*> runState (swap >> get2) [1, 2, 3]\n((2, 1), [2, 1, 3])\nMain*> runState getswapped [1, 2, 3]\n((2, 1), [2, 1, 3])\n Prelude> runState (return 0) 1\n(0, 1)\n"
},
{
"answer_id": 51768485,
"author": "Joakim Ahnfelt-Rønne",
"author_id": 4506902,
"author_profile": "https://Stackoverflow.com/users/4506902",
"pm_score": 3,
"selected": false,
"text": "Monad Applicative Functor join join join :: Monad m => m (m a) -> m a\n m m m join a m a join :: [[a]] -> [a] -- for lists, or nondeterministic values\njoin :: Maybe (Maybe a) -> Maybe a -- for Maybe, or optional values\njoin :: IO (IO a) -> IO a -- for I/O-produced values\n join m m a m a >>= fmap join (ma >>= k) == join (fmap k ma)\n{-\n ma :: m a -- `m`-computation which produces `a`-type values\n k :: a -> m b -- create new `m`-computation from an `a`-type value\n fmap k ma :: m ( m b ) -- `m`-computation of `m`-computation of `b`-type values\n (m >>= k) :: m b -- `m`-computation which produces `b`-type values\n-}\n join join mma == join (fmap id mma) == mma >>= id id ma = ma m do do { x <- mx ; y <- my ; return (f x y) } -- x :: a , mx :: m a\n -- y :: b , my :: m b\nmx >>= (\\x -> -- nested\n my >>= (\\y -> -- lambda\n return (f x y) )) -- functions\n mx x do <- m a a m do return x m x m return liftA2 :: Applicative m => (a -> b -> c) -> m a -> m b -> m c pure :: Applicative m => a -> m a fmap :: Functor m => (a -> b) -> m a -> m b liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c\nreturn :: Monad m => a -> m a\nliftM :: Monad m => (a -> b) -> m a -> m b\n pure a = return a\nfmap f ma = do { a <- ma ; return (f a) }\nliftA2 f ma mb = do { a <- ma ; b <- mb ; return (f a b) }\n(ma >>= k) = do { a <- ma ; b <- k a ; return b }\n"
},
{
"answer_id": 72264847,
"author": "Srivathsa Harish Venkataramana",
"author_id": 1301703,
"author_profile": "https://Stackoverflow.com/users/1301703",
"pm_score": 0,
"selected": false,
"text": "bool ReturnTrueorFalse(SomeObject input)\n{\n if(input.Property1 is invalid)\n {\n return false;\n }\n\n if(input.Property2 is invalid)\n {\n return false;\n }\n\n DoSomething();\n return true;\n}\n Monad<bool> ReturnTrueorFalse(SomeObject input) =>\n from isProperty1Valid in input.Property1\n from isProperty2Valid in input.Property2\n select Monad.Create(isProperty1Valid && isProperty2Valid);\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
44,973 |
<p>Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? </p>
|
[
{
"answer_id": 44986,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "igem"
},
{
"answer_id": 488664,
"author": "Jirapong",
"author_id": 28843,
"author_profile": "https://Stackoverflow.com/users/28843",
"pm_score": 1,
"selected": false,
"text": "c:\\> set GEM_PATH=c:\\ruby\\lib\\ruby\\gems\\1.8\n c:\\> igem.bat\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4642/"
] |
44,980 |
<p>How can one determine, in code, how long the machine is locked?</p>
<p>Other ideas outside of C# are also welcome.</p>
<hr>
<p>I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.</p>
<p>I'll write it up anyway and see if it works. Thanks everyone!</p>
|
[
{
"answer_id": 44987,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "System.Runtime.InteropServices [DllImport(\"user32\", EntryPoint = \"OpenDesktopA\", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]\nprivate static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);\n\n[DllImport(\"user32\", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]\nprivate static extern Int32 CloseDesktop(Int32 hDesktop);\n\n[DllImport(\"user32\", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]\nprivate static extern Int32 SwitchDesktop(Int32 hDesktop);\n\npublic static bool IsWorkstationLocked()\n{\n const int DESKTOP_SWITCHDESKTOP = 256;\n int hwnd = -1;\n int rtn = -1;\n\n hwnd = OpenDesktop(\"Default\", 0, false, DESKTOP_SWITCHDESKTOP);\n\n if (hwnd != 0)\n {\n rtn = SwitchDesktop(hwnd);\n if (rtn == 0)\n {\n // Locked\n CloseDesktop(hwnd);\n return true;\n }\n else\n {\n // Not locked\n CloseDesktop(hwnd);\n }\n }\n else\n {\n // Error: \"Could not access the desktop...\"\n }\n\n return false;\n}\n"
},
{
"answer_id": 45134,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 5,
"selected": false,
"text": "protected override void OnSessionChange(SessionChangeDescription changeDescription)\n{\n if (changeDescription.Reason == SessionChangeReason.SessionLock)\n { \n //I left my desk\n }\n else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)\n { \n //I returned to my desk\n }\n}\n"
},
{
"answer_id": 52102,
"author": "adeel825",
"author_id": 324,
"author_profile": "https://Stackoverflow.com/users/324",
"pm_score": 4,
"selected": false,
"text": "[DllImport(\"wtsapi32.dll\")]\nprivate static extern bool WTSRegisterSessionNotification(IntPtr hWnd,\nint dwFlags);\n\n[DllImport(\"wtsapi32.dll\")]\nprivate static extern bool WTSUnRegisterSessionNotification(IntPtr\nhWnd);\n\nprivate const int NotifyForThisSession = 0; // This session only\n\nprivate const int SessionChangeMessage = 0x02B1;\nprivate const int SessionLockParam = 0x7;\nprivate const int SessionUnlockParam = 0x8;\n\nprotected override void WndProc(ref Message m)\n{\n // check for session change notifications\n if (m.Msg == SessionChangeMessage)\n {\n if (m.WParam.ToInt32() == SessionLockParam)\n OnSessionLock(); // Do something when locked\n else if (m.WParam.ToInt32() == SessionUnlockParam)\n OnSessionUnlock(); // Do something when unlocked\n }\n\n base.WndProc(ref m);\n return;\n}\n\nvoid OnSessionLock() \n{\n Debug.WriteLine(\"Locked...\");\n}\n\nvoid OnSessionUnlock() \n{\n Debug.WriteLine(\"Unlocked...\");\n}\n\nprivate void Form1Load(object sender, EventArgs e)\n{\n WTSRegisterSessionNotification(this.Handle, NotifyForThisSession);\n}\n\n// and then when we are done, we should unregister for the notification\n// WTSUnRegisterSessionNotification(this.Handle);\n"
},
{
"answer_id": 604042,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 8,
"selected": true,
"text": "Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);\n\nvoid SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)\n{\n if (e.Reason == SessionSwitchReason.SessionLock)\n { \n //I left my desk\n }\n else if (e.Reason == SessionSwitchReason.SessionUnlock)\n { \n //I returned to my desk\n }\n}\n"
},
{
"answer_id": 36596656,
"author": "Robert",
"author_id": 199111,
"author_profile": "https://Stackoverflow.com/users/199111",
"pm_score": 3,
"selected": false,
"text": "static class SessionInfo {\n private const Int32 FALSE = 0;\n\n private static readonly IntPtr WTS_CURRENT_SERVER = IntPtr.Zero;\n\n private const Int32 WTS_SESSIONSTATE_LOCK = 0;\n private const Int32 WTS_SESSIONSTATE_UNLOCK = 1;\n\n private static bool _is_win7 = false;\n\n static SessionInfo() {\n var os_version = Environment.OSVersion;\n _is_win7 = (os_version.Platform == PlatformID.Win32NT && os_version.Version.Major == 6 && os_version.Version.Minor == 1);\n }\n\n [DllImport(\"wtsapi32.dll\")]\n private static extern Int32 WTSQuerySessionInformation(\n IntPtr hServer,\n [MarshalAs(UnmanagedType.U4)] UInt32 SessionId,\n [MarshalAs(UnmanagedType.U4)] WTS_INFO_CLASS WTSInfoClass,\n out IntPtr ppBuffer,\n [MarshalAs(UnmanagedType.U4)] out UInt32 pBytesReturned\n );\n\n [DllImport(\"wtsapi32.dll\")]\n private static extern void WTSFreeMemoryEx(\n WTS_TYPE_CLASS WTSTypeClass,\n IntPtr pMemory,\n UInt32 NumberOfEntries\n );\n\n private enum WTS_INFO_CLASS {\n WTSInitialProgram = 0,\n WTSApplicationName = 1,\n WTSWorkingDirectory = 2,\n WTSOEMId = 3,\n WTSSessionId = 4,\n WTSUserName = 5,\n WTSWinStationName = 6,\n WTSDomainName = 7,\n WTSConnectState = 8,\n WTSClientBuildNumber = 9,\n WTSClientName = 10,\n WTSClientDirectory = 11,\n WTSClientProductId = 12,\n WTSClientHardwareId = 13,\n WTSClientAddress = 14,\n WTSClientDisplay = 15,\n WTSClientProtocolType = 16,\n WTSIdleTime = 17,\n WTSLogonTime = 18,\n WTSIncomingBytes = 19,\n WTSOutgoingBytes = 20,\n WTSIncomingFrames = 21,\n WTSOutgoingFrames = 22,\n WTSClientInfo = 23,\n WTSSessionInfo = 24,\n WTSSessionInfoEx = 25,\n WTSConfigInfo = 26,\n WTSValidationInfo = 27,\n WTSSessionAddressV4 = 28,\n WTSIsRemoteSession = 29\n }\n\n private enum WTS_TYPE_CLASS {\n WTSTypeProcessInfoLevel0,\n WTSTypeProcessInfoLevel1,\n WTSTypeSessionInfoLevel1\n }\n\n public enum WTS_CONNECTSTATE_CLASS {\n WTSActive,\n WTSConnected,\n WTSConnectQuery,\n WTSShadow,\n WTSDisconnected,\n WTSIdle,\n WTSListen,\n WTSReset,\n WTSDown,\n WTSInit\n }\n\n public enum LockState {\n Unknown,\n Locked,\n Unlocked\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX {\n public UInt32 Level;\n public UInt32 Reserved; /* I have observed the Data field is pushed down by 4 bytes so i have added this field as padding. */\n public WTSINFOEX_LEVEL Data;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX_LEVEL {\n public WTSINFOEX_LEVEL1 WTSInfoExLevel1;\n }\n\n [StructLayout(LayoutKind.Sequential)]\n private struct WTSINFOEX_LEVEL1 {\n public UInt32 SessionId;\n public WTS_CONNECTSTATE_CLASS SessionState;\n public Int32 SessionFlags;\n\n /* I can't figure out what the rest of the struct should look like but as i don't need anything past the SessionFlags i'm not going to. */\n\n }\n\n public static LockState GetSessionLockState(UInt32 session_id) {\n IntPtr ppBuffer;\n UInt32 pBytesReturned;\n\n Int32 result = WTSQuerySessionInformation(\n WTS_CURRENT_SERVER,\n session_id,\n WTS_INFO_CLASS.WTSSessionInfoEx,\n out ppBuffer,\n out pBytesReturned\n );\n\n if (result == FALSE)\n return LockState.Unknown;\n\n var session_info_ex = Marshal.PtrToStructure<WTSINFOEX>(ppBuffer);\n\n if (session_info_ex.Level != 1)\n return LockState.Unknown;\n\n var lock_state = session_info_ex.Data.WTSInfoExLevel1.SessionFlags;\n WTSFreeMemoryEx(WTS_TYPE_CLASS.WTSTypeSessionInfoLevel1, ppBuffer, pBytesReturned);\n\n if (_is_win7) {\n /* Ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ee621019(v=vs.85).aspx\n * Windows Server 2008 R2 and Windows 7: Due to a code defect, the usage of the WTS_SESSIONSTATE_LOCK\n * and WTS_SESSIONSTATE_UNLOCK flags is reversed. That is, WTS_SESSIONSTATE_LOCK indicates that the\n * session is unlocked, and WTS_SESSIONSTATE_UNLOCK indicates the session is locked.\n * */\n switch (lock_state) {\n case WTS_SESSIONSTATE_LOCK:\n return LockState.Unlocked;\n\n case WTS_SESSIONSTATE_UNLOCK:\n return LockState.Locked;\n\n default:\n return LockState.Unknown;\n }\n }\n else {\n switch (lock_state) {\n case WTS_SESSIONSTATE_LOCK:\n return LockState.Locked;\n\n case WTS_SESSIONSTATE_UNLOCK:\n return LockState.Unlocked;\n\n default:\n return LockState.Unknown;\n }\n }\n }\n}"
},
{
"answer_id": 42634766,
"author": "Abdul Rahman Kayali",
"author_id": 236384,
"author_profile": "https://Stackoverflow.com/users/236384",
"pm_score": 3,
"selected": false,
"text": "true CanHandleSessionChangeEvent = true;\n InvalidOperationException"
},
{
"answer_id": 47080750,
"author": "granadaCoder",
"author_id": 214977,
"author_profile": "https://Stackoverflow.com/users/214977",
"pm_score": 2,
"selected": false,
"text": "public interface IMyServiceContract\n{\n void Start();\n\n void Stop();\n\n void SessionChanged(Topshelf.SessionChangedArguments args);\n}\n\n\n\npublic class MyService : IMyServiceContract\n{\n\n public void Start()\n {\n }\n\n public void Stop()\n {\n\n }\n\n public void SessionChanged(SessionChangedArguments e)\n {\n Console.WriteLine(e.ReasonCode);\n } \n}\n IMyServiceContract myServiceObject = new MyService(); /* container.Resolve<IMyServiceContract>(); */\n\n\n HostFactory.Run(x =>\n {\n x.Service<IMyServiceContract>(s =>\n {\n s.ConstructUsing(name => myServiceObject);\n s.WhenStarted(sw => sw.Start());\n s.WhenStopped(sw => sw.Stop());\n s.WhenSessionChanged((csm, hc, chg) => csm.SessionChanged(chg)); /* THIS IS MAGIC LINE */\n });\n\n x.EnableSessionChanged(); /* THIS IS MAGIC LINE */\n\n /* use command line variables for the below commented out properties */\n /*\n x.RunAsLocalService();\n x.SetDescription(\"My Description\");\n x.SetDisplayName(\"My Display Name\");\n x.SetServiceName(\"My Service Name\");\n x.SetInstanceName(\"My Instance\");\n */\n\n x.StartManually(); // Start the service manually. This allows the identity to be tweaked before the service actually starts\n\n /* the below map to the \"Recover\" tab on the properties of the Windows Service in Control Panel */\n x.EnableServiceRecovery(r =>\n {\n r.OnCrashOnly();\n r.RestartService(1); ////first\n r.RestartService(1); ////second\n r.RestartService(1); ////subsequents\n r.SetResetPeriod(0);\n });\n\n x.DependsOnEventLog(); // Windows Event Log\n x.UseLog4Net();\n\n x.EnableShutdown();\n\n x.OnException(ex =>\n {\n /* Log the exception */\n /* not seen, I have a log4net logger here */\n });\n }); \n <package id=\"log4net\" version=\"2.0.5\" targetFramework=\"net45\" />\n <package id=\"Topshelf\" version=\"4.0.3\" targetFramework=\"net461\" />\n <package id=\"Topshelf.Log4Net\" version=\"4.0.3\" targetFramework=\"net461\" />\n"
},
{
"answer_id": 63944711,
"author": "Nathan",
"author_id": 294317,
"author_profile": "https://Stackoverflow.com/users/294317",
"pm_score": 0,
"selected": false,
"text": "on workstation lock on workstation unlock"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] |
44,989 |
<p>I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?</p>
<pre><code>string[] sa = {"one", "two", "three"};
sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
</code></pre>
|
[
{
"answer_id": 44991,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 5,
"selected": true,
"text": "[] System.Collections.Generic.IEnumerable<T> GetEnumerator() ElementAt(int)"
},
{
"answer_id": 45944,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "//works because under the hood the C# compiler has converted var to string[]\nvar arrayVar = {\"one\", \"two\", \"three\"};\narrayVar[1].Dump();\n\n//now let's try\nvar selectVar = arrayVar.Select( (a,i) => new { Line = a });\n\n//or this (I find this syntax easier, but either works)\nvar selectVar =\n from s in arrayVar \n select new { Line = s };\n selectVar IEnumerable<'a> //convert it to a List<'a>\nvar aList = selectVar.ToList();\n\n//convert it to a 'a[]\nvar anArray = selectVar.ToArray();\n\n//or even a Dictionary<string,'a>\nvar aDictionary = selectVar.ToDictionary( x => x.Line );\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] |
44,999 |
<p>I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. </p>
<p>I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.</p>
<p>I'm doing some nested "if's" and <code>string.Replace()</code> on the url, is there a better way?</p>
<p>All manipulations are done on the server.</p>
<p><strong>p.s.</strong> Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues.</p>
|
[
{
"answer_id": 45028,
"author": "chrisntr",
"author_id": 4455,
"author_profile": "https://Stackoverflow.com/users/4455",
"pm_score": 0,
"selected": false,
"text": "booleanVar = !booleanVar;"
},
{
"answer_id": 45034,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 3,
"selected": true,
"text": "<asp:HiddenField ID=\"ShowAll\" Value=\"False\" runat=\"server\" /> protected void ToggleState(object sender, EventArgs e)\n{\n //parse string as boolean, invert, and convert back to string\n ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString();\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] |
45,004 |
<p>Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for <a href="http://drupal.org" rel="noreferrer">http://drupal.org</a>. The output renders like this: </p>
<pre><code><ul class="menu">
<li>
<a class="active">Active Page</a>
</li>
<li>
<a>Some Other Page</a>
</li>
</ul>
</code></pre>
<p>My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.</p>
<p>Just to be clear, I want to apply a style to the list item, not the anchor.</p>
|
[
{
"answer_id": 45008,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 8,
"selected": true,
"text": "// JavaScript code:\ndocument.getElementsByClassName(\"active\")[0].parentNode;\n\n// jQuery code:\n$('.active').parent().get(0); // This would be the <a>'s parent <li>.\n"
},
{
"answer_id": 45530,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 8,
"selected": false,
"text": "OL > LI:only-child\n $OL > LI:only-child\n"
},
{
"answer_id": 3446316,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 5,
"selected": false,
"text": "<ul> <span> <li> :has $(\"ul\").has(\"#someId\")\n ul $(\"li\").has(\".active\")\n"
},
{
"answer_id": 7601165,
"author": "Brian",
"author_id": 168645,
"author_profile": "https://Stackoverflow.com/users/168645",
"pm_score": 4,
"selected": false,
"text": "$li > a.active OL > LI:only-child $OL > LI:only-child"
},
{
"answer_id": 7936364,
"author": "John Drefahl",
"author_id": 624790,
"author_profile": "https://Stackoverflow.com/users/624790",
"pm_score": 1,
"selected": false,
"text": ".parent() .parent .parent() .live .click $('#testTab1 .tabLink').live('click', function() {\n $('#modal ul.tabs li').removeClass(\"current\"); //Remove any \"current\" class\n $(this).parent().addClass(\"current\"); //Add \"current\" class to selected tab\n $('#modal div#testTab1 .tabContent').hide();\n $(this).next('.tabContent').fadeIn(); \n return false;\n})\n$('#testTab2 .tabLink').live('click', function() {\n $('#modal ul.tabs li').removeClass(\"current\"); //Remove any \"current\" class\n $(this).parent().addClass(\"current\"); //Add \"current\" class to selected tab\n $('#modal div#testTab2 .tabContent').hide();\n $(this).next('.tabContent').fadeIn(); \n return false;\n})\n <div id=\"tabView1\" style=\"display:none;\">\n <!-- start: the code for tabView 1 -->\n <div id=\"testTab1\" style=\"width:1080px; height:640px; position:relative;\">\n <h1 class=\"Bold_Gray_45px\">Modal Header</h1>\n <div class=\"tabBleed\"></div>\n <ul class=\"tabs\">\n <li class=\"current\"> <a href=\"#\" class=\"tabLink\" id=\"link1\">Tab Title Link</a>\n <div class=\"tabContent\" id=\"tabContent1-1\">\n <div class=\"modalCol\">\n <p>Your Tab Content</p>\n <p><a href=\"#\" class=\"tabShopLink\">tabBased Anchor Link</a> </p>\n </div>\n <div class=\"tabsImg\"> </div>\n </div>\n </li>\n <li> <a href=\"#\" class=\"tabLink\" id=\"link2\">Tab Title Link</a>\n <div class=\"tabContent\" id=\"tabContent1-2\">\n <div class=\"modalCol\">\n <p>Your Tab Content</p>\n <p><a href=\"#\" class=\"tabShopLink\">tabBased Anchor Link</a> </p>\n </div>\n <div class=\"tabsImg\"> </div>\n </div>\n </li>\n </ul>\n </div>\n</div>\n"
},
{
"answer_id": 9111040,
"author": "Jared",
"author_id": 1184883,
"author_profile": "https://Stackoverflow.com/users/1184883",
"pm_score": 0,
"selected": false,
"text": "a.active {\n position:absolute;\n display:block;\n width:100%;\n height:100%;\n top:0em;\n left:0em;\n background-color: whatever;\n border: whatever;\n}\n/* will also need to make sure the parent li is a positioned element so... */\nul.menu li {\n position:relative;\n} \n getElementsByClass active_li = getElementsByClass(\"active\",\"a\");\nactive_li[0].parentNode.style.whatever=\"whatever\";\n\nfunction getElementsByClass(node,searchClass,tag) {\n var classElements = new Array();\n var els = node.getElementsByTagName(tag); // use \"*\" for all elements\n var elsLen = els.length;\n var pattern = new RegExp(\"\\\\b\"+searchClass+\"\\\\b\");\n for (i = 0, j = 0; i < elsLen; i++) {\n if ( pattern.test(els[i].className) ) {\n classElements[j] = els[i];\n j++;\n }\n}\nreturn classElements;\n}\n"
},
{
"answer_id": 11020342,
"author": "Matt Wagner",
"author_id": 1445647,
"author_profile": "https://Stackoverflow.com/users/1445647",
"pm_score": 4,
"selected": false,
"text": ":has li:has(a:active) {\n /* ... */\n}\n ul * a {\n property:value;\n}\n ul>li a {\n property:value;\n}\n ul.menu > li a.active {\n property:value;\n}\n"
},
{
"answer_id": 13506287,
"author": "Praveen Kumar Purushothaman",
"author_id": 462627,
"author_profile": "https://Stackoverflow.com/users/462627",
"pm_score": 5,
"selected": false,
"text": "$ul li:hover{\n background: #fff;\n}\n"
},
{
"answer_id": 14556845,
"author": "ggedde",
"author_id": 2017192,
"author_profile": "https://Stackoverflow.com/users/2017192",
"pm_score": 1,
"selected": false,
"text": "jQuery li li $(\"li ul\").parent().addClass('has-sub');\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
] |
45,015 |
<p>Given a string of JSON data, how can I safely turn that string into a JavaScript object?</p>
<p>Obviously I can do this unsafely with something like:</p>
<pre><code>var obj = eval("(" + json + ')');
</code></pre>
<p>but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.</p>
|
[
{
"answer_id": 45019,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "new Ajax.Request('/some_url', {\n method:'get',\n requestHeaders: {Accept: 'application/json'},\n onSuccess: function(transport){\n var json = transport.responseText.evalJSON(true);\n }\n});\n evalJSON()"
},
{
"answer_id": 45020,
"author": "John",
"author_id": 2168,
"author_profile": "https://Stackoverflow.com/users/2168",
"pm_score": 7,
"selected": false,
"text": "JSON.parse(jsonString)"
},
{
"answer_id": 233630,
"author": "Leanan",
"author_id": 22390,
"author_profile": "https://Stackoverflow.com/users/22390",
"pm_score": 4,
"selected": false,
"text": "$.getJSON(url, function(data) { });\n data.key1.something\ndata.key1.something_else\n"
},
{
"answer_id": 2778898,
"author": "Prahlad",
"author_id": 190477,
"author_profile": "https://Stackoverflow.com/users/190477",
"pm_score": 4,
"selected": false,
"text": "$.ajax({\n url: url,\n dataType: 'json',\n data: data,\n success: callback\n});\n $.parseJSON()"
},
{
"answer_id": 3627901,
"author": "Alex V",
"author_id": 327934,
"author_profile": "https://Stackoverflow.com/users/327934",
"pm_score": 10,
"selected": false,
"text": "let jsonObject = JSON.parse(jsonString);\n jQuery.parseJSON( jsonString );\n"
},
{
"answer_id": 5686237,
"author": "Jonathan.",
"author_id": 191463,
"author_profile": "https://Stackoverflow.com/users/191463",
"pm_score": 12,
"selected": true,
"text": "JSON.parse(jsonString)"
},
{
"answer_id": 16273454,
"author": "Cody",
"author_id": 1153121,
"author_profile": "https://Stackoverflow.com/users/1153121",
"pm_score": 5,
"selected": false,
"text": "JSON.parsable JSON.parse \"Error: unexpected token 'x'\" var data;\n\ntry {\n data = JSON.parse(jqxhr.responseText);\n} catch (_error) {}\n\ndata || (data = {\n message: 'Server error, please retry'\n});\n"
},
{
"answer_id": 20601233,
"author": "Ronald Coarite",
"author_id": 2154661,
"author_profile": "https://Stackoverflow.com/users/2154661",
"pm_score": 6,
"selected": false,
"text": "var jsontext = '{\"firstname\":\"Jesper\",\"surname\":\"Aaberg\",\"phone\":[\"555-0100\",\"555-0120\"]}';\nvar contact = JSON.parse(jsontext);\n var str = JSON.stringify(arr);\n"
},
{
"answer_id": 24765981,
"author": "GPrathap",
"author_id": 1574779,
"author_profile": "https://Stackoverflow.com/users/1574779",
"pm_score": 3,
"selected": false,
"text": "Data='{result:true,count:1} try {\n eval('var obj=' + Data);\n console.log(obj.count);\n}\ncatch(e) {\n console.log(e.message);\n}\n"
},
{
"answer_id": 26377600,
"author": "lessisawesome",
"author_id": 2651695,
"author_profile": "https://Stackoverflow.com/users/2651695",
"pm_score": 4,
"selected": false,
"text": " jsonObject = (new Function('return ' + jsonFormatData))()\n"
},
{
"answer_id": 28585014,
"author": "Dorian",
"author_id": 407213,
"author_profile": "https://Stackoverflow.com/users/407213",
"pm_score": 3,
"selected": false,
"text": "try data = JSON.parse(jqxhr.responseText)\ndata ||= { message: 'Server error, please retry' }\n var data;\n\ntry {\n data = JSON.parse(jqxhr.responseText);\n} catch (_error) {}\n\ndata || (data = {\n message: 'Server error, please retry'\n});\n"
},
{
"answer_id": 29793524,
"author": "Barath Kumar",
"author_id": 2920768,
"author_profile": "https://Stackoverflow.com/users/2920768",
"pm_score": 4,
"selected": false,
"text": "JSON.parse var jsonRes = '{ \"students\" : [' +\n '{ \"firstName\":\"Michel\" , \"lastName\":\"John\" ,\"age\":18},' +\n '{ \"firstName\":\"Richard\" , \"lastName\":\"Joe\",\"age\":20 },' +\n '{ \"firstName\":\"James\" , \"lastName\":\"Henry\",\"age\":15 } ]}';\nvar studentObject = JSON.parse(jsonRes);\n"
},
{
"answer_id": 35517811,
"author": "Jorgesys",
"author_id": 250260,
"author_profile": "https://Stackoverflow.com/users/250260",
"pm_score": 3,
"selected": false,
"text": "parse() var response = '{\"result\":true,\"count\":1}';\nvar JsonObject= JSON.parse(response);\n var myResponseResult = JsonObject.result;\nvar myResponseCount = JsonObject.count;\n jQuery.parseJSON() JSON.parse(jsonString);\n"
},
{
"answer_id": 40949422,
"author": "Pushkar Kathuria",
"author_id": 2171599,
"author_profile": "https://Stackoverflow.com/users/2171599",
"pm_score": 2,
"selected": false,
"text": "JSON.parse() var response = '{\"result\":true,\"count\":1}'; //sample json object(string form)\nJSON.parse(response); //converts passed string to JSON Object.\n console.log(JSON.parse(response));\n {result: true, count: 1} obj var obj = JSON.parse(response);\n obj . console.log(obj.result);\n"
},
{
"answer_id": 41223251,
"author": "Shekhar Tyagi",
"author_id": 7250429,
"author_profile": "https://Stackoverflow.com/users/7250429",
"pm_score": 2,
"selected": false,
"text": "JSON.parse(jsonString);\n"
},
{
"answer_id": 42235893,
"author": "Tahsin Turkoz",
"author_id": 3618397,
"author_profile": "https://Stackoverflow.com/users/3618397",
"pm_score": 3,
"selected": false,
"text": "JSON.safeParse = function (input, def) {\n // Convert null to empty object\n if (!input) {\n return def || {};\n } else if (Object.prototype.toString.call(input) === '[object Object]') {\n return input;\n }\n try {\n return JSON.parse(input);\n } catch (e) {\n return def || {};\n }\n};\n"
},
{
"answer_id": 44635628,
"author": "Liuver Reynier Durán Pérez",
"author_id": 6827370,
"author_profile": "https://Stackoverflow.com/users/6827370",
"pm_score": 2,
"selected": false,
"text": "JSON.parse(JSON.stringify(object))\n"
},
{
"answer_id": 45322136,
"author": "Durgpal Singh",
"author_id": 1759015,
"author_profile": "https://Stackoverflow.com/users/1759015",
"pm_score": 1,
"selected": false,
"text": "reviver var data = JSON.parse(jsonString, function reviver(key, value) {\n //your code here to filter\n});\n JSON.parse"
},
{
"answer_id": 47897689,
"author": "Salomon Zhang",
"author_id": 6031990,
"author_profile": "https://Stackoverflow.com/users/6031990",
"pm_score": 2,
"selected": false,
"text": "JSON.parse() reviver JSON.parse(text[, reviver])\n text reviver (optional)"
},
{
"answer_id": 48858463,
"author": "Codebeat",
"author_id": 565244,
"author_profile": "https://Stackoverflow.com/users/565244",
"pm_score": 1,
"selected": false,
"text": "new Function() var oData = 'test1:\"This is my object\",test2:\"This is my object\"';\n\n if( typeof oData !== 'object' )\n try {\n oData = (new Function('return {'+oData+'};'))();\n }\n catch(e) { oData=false; }\n\n if( typeof oData !== 'object' )\n { alert( 'Error in code' ); }\n else {\n alert( oData.test1 );\n alert( oData.test2 );\n }\n"
},
{
"answer_id": 50597756,
"author": "Supun Dharmarathne",
"author_id": 1644446,
"author_profile": "https://Stackoverflow.com/users/1644446",
"pm_score": -1,
"selected": false,
"text": "export function safeJsonParse(str: string) {\n try {\n return JSON.parse(str);\n } catch (e) {\n return str;\n }\n}\n"
},
{
"answer_id": 51814506,
"author": "Amitesh Bharti",
"author_id": 2745436,
"author_profile": "https://Stackoverflow.com/users/2745436",
"pm_score": 3,
"selected": false,
"text": "JSON.parse() JSON.parse(jsonString)\n '{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}'\n var obj = JSON.parse('{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}'); \n obj { \"name\":\"John\", \"age\":30, \"city\":\"New York\"}\n . obj.name // John\nobj.age //30\n JSON.stringify()"
},
{
"answer_id": 51907405,
"author": "Willem van der Veen",
"author_id": 8059459,
"author_profile": "https://Stackoverflow.com/users/8059459",
"pm_score": 1,
"selected": false,
"text": "JSON JSON JSON.parse() JSON JSON.stringify() JSON JSON JSON let arr1 = [1, 2, [3 ,4]];\nlet newArr = arr1.slice();\n\narr1[2][0] = 'changed'; \nconsole.log(newArr); // not a deep clone\n\nlet arr2 = [1, 2, [3 ,4]];\nlet newArrDeepclone = JSON.parse(JSON.stringify(arr2));\n\narr2[2][0] = 'changed'; \nconsole.log(newArrDeepclone); // A deep clone, values unchanged"
},
{
"answer_id": 55178226,
"author": "Hamid Araghi",
"author_id": 4411896,
"author_profile": "https://Stackoverflow.com/users/4411896",
"pm_score": 2,
"selected": false,
"text": "\"{\\\"status\\\":1,\\\"token\\\":\\\"65b4352b2dfc4957a09add0ce5714059\\\"}\"\n JSON.parse var sampleString = \"{\\\"status\\\":1,\\\"token\\\":\\\"65b4352b2dfc4957a09add0ce5714059\\\"}\"\nvar jsonString= JSON.parse(sampleString)\nvar jsonObject= JSON.parse(jsonString)\n // instead of last JSON.parse:\nvar { status, token } = JSON.parse(jsonString);\n status = 1 and token = 65b4352b2dfc4957a09add0ce5714059\n"
},
{
"answer_id": 60359491,
"author": "MOnkey",
"author_id": 7414166,
"author_profile": "https://Stackoverflow.com/users/7414166",
"pm_score": 1,
"selected": false,
"text": "var obj = JSON.parse('{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}');\n var myArr = JSON.parse(this.responseText);\nconsole.log(myArr[0]);\n var text = '{ \"name\":\"John\", \"birth\":\"1986-12-14\", \"city\":\"New York\"}';\nvar obj = JSON.parse(text);\nobj.birth = new Date(obj.birth);\n var text = '{ \"name\":\"John\", \"age\":\"function () {return 30;}\", \"city\":\"New York\"}';\nvar obj = JSON.parse(text);\nobj.age = eval(\"(\" + obj.age + \")\");\n"
},
{
"answer_id": 63989306,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "eval/Function eval JSON.parse let obj_ShallowSmall = {\n field0: false,\n field1: true,\n field2: 1,\n field3: 0,\n field4: null,\n field5: [],\n field6: {},\n field7: \"text7\",\n field8: \"text8\",\n}\n\nlet obj_DeepSmall = {\n level0: {\n level1: {\n level2: {\n level3: {\n level4: {\n level5: {\n level6: {\n level7: {\n level8: {\n level9: [[[[[[[[[['abc']]]]]]]]]],\n }}}}}}}}},\n};\n\nlet obj_ShallowBig = Array(1000).fill(0).reduce((a,c,i) => (a['field'+i]=getField(i),a) ,{});\n\n\nlet obj_DeepBig = genDeepObject(1000);\n\n\n\n// ------------------\n// Show objects\n// ------------------\n\nconsole.log('obj_ShallowSmall:',JSON.stringify(obj_ShallowSmall));\nconsole.log('obj_DeepSmall:',JSON.stringify(obj_DeepSmall));\nconsole.log('obj_ShallowBig:',JSON.stringify(obj_ShallowBig));\nconsole.log('obj_DeepBig:',JSON.stringify(obj_DeepBig));\n\n\n\n\n// ------------------\n// HELPERS\n// ------------------\n\nfunction getField(k) {\n let i=k%10;\n if(i==0) return false;\n if(i==1) return true;\n if(i==2) return k;\n if(i==3) return 0;\n if(i==4) return null;\n if(i==5) return [];\n if(i==6) return {}; \n if(i>=7) return \"text\"+k;\n}\n\nfunction genDeepObject(N) {\n // generate: {level0:{level1:{...levelN: {end:[[[...N-times...['abc']...]]] }}}...}}}\n let obj={};\n let o=obj;\n let arr = [];\n let a=arr;\n\n for(let i=0; i<N; i++) {\n o['level'+i]={};\n o=o['level'+i];\n let aa=[];\n a.push(aa);\n a=aa;\n }\n\n a[0]='abc';\n o['end']=arr;\n return obj;\n} // src: https://stackoverflow.com/q/45015/860099\nfunction A(json) {\n return eval(\"(\" + json + ')');\n}\n\n// https://stackoverflow.com/a/26377600/860099\nfunction B(json) {\n return (new Function('return ('+json+')'))()\n}\n\n\n// improved https://stackoverflow.com/a/26377600/860099\nfunction C(json) {\n return Function('return ('+json+')')()\n}\n\n// src: https://stackoverflow.com/a/5686237/860099\nfunction D(json) {\n return JSON.parse(json);\n}\n\n// src: https://stackoverflow.com/a/233630/860099\nfunction E(json) {\n return $.parseJSON(json)\n}\n\n\n\n \n// --------------------\n// TEST\n// --------------------\n\nlet json = '{\"a\":\"abc\",\"b\":\"123\",\"d\":[1,2,3],\"e\":{\"a\":1,\"b\":2,\"c\":3}}';\n\n[A,B,C,D,E].map(f=> { \n console.log(\n f.name + ' ' + JSON.stringify(f(json))\n )}) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\nThis shippet only presents functions used in performance tests - it not perform tests itself!"
},
{
"answer_id": 73305592,
"author": "tebe.app",
"author_id": 17773570,
"author_profile": "https://Stackoverflow.com/users/17773570",
"pm_score": 0,
"selected": false,
"text": "const json = '{ \"fruit\": \"pineapple\", \"fingers\": 10 }'\nlet j0s,j1s,j2s,j3s\nconsole.log(`{ \"${j0s=\"fruit\"}\": \"${j1s=\"pineapple\"}\", \"${j2s=\"fingers\"}\": ${j3s=\"10\"} }`)"
},
{
"answer_id": 73799088,
"author": "S M Samnoon Abrar",
"author_id": 8188682,
"author_profile": "https://Stackoverflow.com/users/8188682",
"pm_score": 2,
"selected": false,
"text": "JSON.parse() JSON $.parseJSON() JSON.parse() const json = '{ \"city\": \"Boston\", \"population\": 500000 }';\nconst object = JSON.parse(json);\nconsole.log(object.city, object.population);"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
45,030 |
<p>I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.</p>
<p>I was kind of hoping that this would work</p>
<pre><code>int? val = stringVal as int?;
</code></pre>
<p>But that won't work, so the way I'm doing it now is I've written this extension method</p>
<pre><code>public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
</code></pre>
<p>Is there a better way of doing this?</p>
<p><strong>EDIT:</strong> Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>
|
[
{
"answer_id": 45037,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 10,
"selected": true,
"text": "int.TryParse public static int? ToNullableInt(this string s)\n{\n int i;\n if (int.TryParse(s, out i)) return i;\n return null;\n}\n int.TryParse int.Parse"
},
{
"answer_id": 45039,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 3,
"selected": false,
"text": "public static int? ParseNullableInt(this string value)\n{\n int intValue;\n if (int.TryParse(value, out intValue))\n return intValue;\n return null;\n}\n"
},
{
"answer_id": 45066,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 8,
"selected": false,
"text": "null TryParse int tempVal;\nint? val = Int32.TryParse(stringVal, out tempVal) ? tempVal : (int?)null;\n int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;\n"
},
{
"answer_id": 241962,
"author": "Duckboy",
"author_id": 2724,
"author_profile": "https://Stackoverflow.com/users/2724",
"pm_score": 5,
"selected": false,
"text": "if return int? ToNullableInt (string val)\n => int.TryParse (val, out var i) ? (int?) i : null;\n int Int32"
},
{
"answer_id": 1391080,
"author": "umbyersw",
"author_id": 267578,
"author_profile": "https://Stackoverflow.com/users/267578",
"pm_score": 0,
"selected": false,
"text": "NullableParser.TryParseInt(ViewState[\"Id\"] as string);\n public class NullableParser\n {\n public delegate T ParseDelegate<T>(string input) where T : struct;\n public delegate bool TryParseDelegate<T>(string input, out T outtie) where T : struct;\n private static T? Parse<T>(string input, ParseDelegate<T> DelegateTheParse) where T : struct\n {\n if (string.IsNullOrEmpty(input)) return null;\n return DelegateTheParse(input);\n }\n private static T? TryParse<T>(string input, TryParseDelegate<T> DelegateTheTryParse) where T : struct\n {\n T x;\n if (DelegateTheTryParse(input, out x)) return x;\n return null;\n }\n public static int? ParseInt(string input)\n {\n return Parse<int>(input, new ParseDelegate<int>(int.Parse));\n }\n public static int? TryParseInt(string input)\n {\n return TryParse<int>(input, new TryParseDelegate<int>(int.TryParse));\n }\n public static bool? TryParseBool(string input)\n {\n return TryParse<bool>(input, new TryParseDelegate<bool>(bool.TryParse));\n }\n public static DateTime? TryParseDateTime(string input)\n {\n return TryParse<DateTime>(input, new TryParseDelegate<DateTime>(DateTime.TryParse));\n }\n }\n"
},
{
"answer_id": 1613379,
"author": "John Dauphine",
"author_id": 195302,
"author_profile": "https://Stackoverflow.com/users/195302",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Globalization;\nnamespace SomeNamespace\n{\n /// <summary>\n /// A parser for nullable types. Will return null when parsing fails.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n ///\n public static class NullableParser<T> where T : struct\n {\n public delegate bool TryParseDelegate(string s, out T result);\n /// <summary>\n /// A generic Nullable Parser. Supports parsing of all types that implements the tryParse method;\n /// </summary>\n /// <param name=\"text\">Text to be parsed</param>\n /// <param name=\"result\">Value is true for parse succeeded</param>\n /// <returns>bool</returns>\n public static bool TryParse(string s, out Nullable<T> result)\n {\n bool success = false;\n try\n {\n if (string.IsNullOrEmpty(s))\n {\n result = null;\n success = true;\n }\n else\n {\n IConvertible convertableString = s as IConvertible;\n if (convertableString != null)\n {\n result = new Nullable<T>((T)convertableString.ToType(typeof(T),\n CultureInfo.CurrentCulture));\n success = true;\n }\n else\n {\n success = false;\n result = null;\n }\n }\n }\n catch\n {\n success = false;\n result = null;\n }\n return success;\n }\n }\n}\n"
},
{
"answer_id": 2426218,
"author": "Leigh Bowers",
"author_id": 1415041,
"author_profile": "https://Stackoverflow.com/users/1415041",
"pm_score": 0,
"selected": false,
"text": "(Nullable<int>)int.Parse(stringVal);\n"
},
{
"answer_id": 2603590,
"author": "Daniel Ballinger",
"author_id": 54026,
"author_profile": "https://Stackoverflow.com/users/54026",
"pm_score": 2,
"selected": false,
"text": " public static bool TryParseStruct<T>(this string value, out Nullable<T> result)\n where T: struct \n {\n if (string.IsNullOrEmpty(value))\n {\n result = new Nullable<T>();\n\n return true;\n }\n\n result = default(T);\n try\n {\n IConvertible convertibleString = (IConvertible)value;\n result = new Nullable<T>((T)convertibleString.ToType(typeof(T), System.Globalization.CultureInfo.CurrentCulture));\n }\n catch(InvalidCastException)\n {\n return false;\n }\n catch (FormatException)\n {\n return false;\n }\n\n return true;\n }\n string parseOne = \"1\";\n int? resultOne;\n bool successOne = parseOne.TryParseStruct<int>(out resultOne);\n Assert.IsTrue(successOne);\n Assert.AreEqual(1, resultOne);\n\n string parseEmpty = string.Empty;\n int? resultEmpty;\n bool successEmpty = parseEmpty.TryParseStruct<int>(out resultEmpty);\n Assert.IsTrue(successEmpty);\n Assert.IsFalse(resultEmpty.HasValue);\n\n string parseNull = null;\n int? resultNull;\n bool successNull = parseNull.TryParseStruct<int>(out resultNull);\n Assert.IsTrue(successNull);\n Assert.IsFalse(resultNull.HasValue);\n\n string parseInvalid = \"FooBar\";\n int? resultInvalid;\n bool successInvalid = parseInvalid.TryParseStruct<int>(out resultInvalid);\n Assert.IsFalse(successInvalid);\n"
},
{
"answer_id": 5392671,
"author": "mortb",
"author_id": 599842,
"author_profile": "https://Stackoverflow.com/users/599842",
"pm_score": 4,
"selected": false,
"text": "public static int? ParseToNullableInt(this string value)\n{\n return String.IsNullOrEmpty(value) ? null : (int.Parse(value) as int?);\n}\n"
},
{
"answer_id": 5420250,
"author": "orcun",
"author_id": 67756,
"author_profile": "https://Stackoverflow.com/users/67756",
"pm_score": 1,
"selected": false,
"text": "var result = \"123\".ParseBy(int.Parse);\n\nvar result2 = \"123\".ParseBy<int>(int.TryParse);\n public static class NullableParse\n{\n public static Nullable<T> ParseBy<T>(this string input, Func<string, T> parser)\n where T : struct\n {\n try\n {\n return parser(input);\n }\n catch (Exception exc)\n {\n return null;\n }\n }\n\n public delegate bool TryParseDelegate<T>(string input, out T result);\n\n public static Nullable<T> ParseBy<T>(this string input, TryParseDelegate<T> parser)\n where T : struct\n {\n T t;\n if (parser(input, out t)) return t;\n return null;\n }\n}\n"
},
{
"answer_id": 6424685,
"author": "Lyskespark",
"author_id": 808355,
"author_profile": "https://Stackoverflow.com/users/808355",
"pm_score": 3,
"selected": false,
"text": "public static T? NullableParse<T>(string s) where T : struct\n{\n try\n {\n return (T)typeof(T).GetMethod(\"Parse\", new[] {typeof(string)}).Invoke(null, new[] { s });\n }\n catch (Exception)\n {\n return null;\n }\n}\n"
},
{
"answer_id": 6474962,
"author": "Michael",
"author_id": 222748,
"author_profile": "https://Stackoverflow.com/users/222748",
"pm_score": 4,
"selected": false,
"text": "public static T Parse<T>(object value)\n{\n try { return (T)System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value.ToString()); }\n catch { return default(T); }\n}\n enum Fruit { Orange, Apple }\nvar res1 = Parse<Fruit>(\"Apple\");\nvar res2 = Parse<Fruit?>(\"Banana\");\nvar res3 = Parse<int?>(\"100\") ?? 5; //use this for non-zero default\nvar res4 = Parse<Unit>(\"45%\");\n"
},
{
"answer_id": 8077089,
"author": "Pavel Hodek",
"author_id": 519856,
"author_profile": "https://Stackoverflow.com/users/519856",
"pm_score": 3,
"selected": false,
"text": "string value = null;\nint? x = value.ConvertOrDefault();\n object obj = 1; \n\nstring value = null;\nint x = 5;\nif (value.TryConvert(out x))\n Console.WriteLine(\"TryConvert example: \" + x); \n\nbool boolean = \"false\".ConvertOrDefault();\nbool? nullableBoolean = \"\".ConvertOrDefault();\nint integer = obj.ConvertOrDefault();\nint negativeInteger = \"-12123\".ConvertOrDefault();\nint? nullableInteger = value.ConvertOrDefault();\nMyEnum enumValue = \"SecondValue\".ConvertOrDefault();\n\nMyObjectBase myObject = new MyObjectClassA();\nMyObjectClassA myObjectClassA = myObject.ConvertOrDefault();\n"
},
{
"answer_id": 20065814,
"author": "Qi Luo",
"author_id": 2514803,
"author_profile": "https://Stackoverflow.com/users/2514803",
"pm_score": 2,
"selected": false,
"text": "public static Nullable<T> ParseNullable<T>(string s, Func<string, T> parser) where T : struct\n{\n if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) return null;\n else return parser(s);\n}\n\nstatic void Main(string[] args)\n{\n Nullable<int> i = ParseNullable(\"-1\", int.Parse);\n Nullable<float> dt = ParseNullable(\"3.14\", float.Parse);\n}\n"
},
{
"answer_id": 29169616,
"author": "wmoecke",
"author_id": 3058222,
"author_profile": "https://Stackoverflow.com/users/3058222",
"pm_score": 0,
"selected": false,
"text": "private static bool TryParseNullableInt(this string s, out int? result)\n{\n int i;\n result = int.TryParse(s, out i) ? (int?)i : null;\n return result != null;\n}\n"
},
{
"answer_id": 33022412,
"author": "Crivelli",
"author_id": 1549600,
"author_profile": "https://Stackoverflow.com/users/1549600",
"pm_score": 1,
"selected": false,
"text": " public static void Main(string[] args)\n {\n\n var myString = \"abc\";\n\n int? myInt = ParseOnlyInt(myString);\n // null\n\n myString = \"1234\";\n\n myInt = ParseOnlyInt(myString);\n // 1234\n }\n private static int? ParseOnlyInt(string s)\n {\n return int.TryParse(s, out var i) ? i : (int?)null;\n }\n"
},
{
"answer_id": 33628246,
"author": "lison",
"author_id": 1182712,
"author_profile": "https://Stackoverflow.com/users/1182712",
"pm_score": 0,
"selected": false,
"text": "public static class Utils { \npublic static bool TryParse<Tin, Tout>(this Tin obj, Func<Tin, Tout> onConvert, Action<Tout> onFill, Action<Exception> onError) {\n Tout value = default(Tout);\n bool ret = true;\n try {\n value = onConvert(obj);\n }\n catch (Exception exc) {\n onError(exc);\n ret = false;\n }\n if (ret)\n onFill(value);\n return ret;\n}\n\npublic static bool TryParse(this string str, Action<int?> onFill, Action<Exception> onError) {\n return Utils.TryParse(str\n , s => string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)\n , onFill\n , onError);\n}\npublic static bool TryParse(this string str, Action<int> onFill, Action<Exception> onError) {\n return Utils.TryParse(str\n , s => int.Parse(s)\n , onFill\n , onError);\n}\n}\n string ageStr = AgeTextBox.Text;\nUtils.TryParse(ageStr, i => person.Age = i, exc => { MessageBox.Show(exc.Message); });\n AgeTextBox.Text.TryParse(i => person.Age = i, exc => { MessageBox.Show(exc.Message); });\n"
},
{
"answer_id": 49231363,
"author": "Aleksandr Neizvestnyi",
"author_id": 4768299,
"author_profile": "https://Stackoverflow.com/users/4768299",
"pm_score": 2,
"selected": false,
"text": "public static int ParseInt(this string value, int defaultIntValue = 0)\n {\n return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;\n }\n\npublic static int? ParseNullableInt(this string value)\n {\n if (string.IsNullOrEmpty(value))\n return null;\n\n return value.ParseInt();\n }\n"
},
{
"answer_id": 52969952,
"author": "SomeDeveloper",
"author_id": 9557852,
"author_profile": "https://Stackoverflow.com/users/9557852",
"pm_score": 5,
"selected": false,
"text": "var result = int.TryParse(foo, out var f) ? f : default;\n"
},
{
"answer_id": 70716864,
"author": "Jeremy Leff",
"author_id": 3348326,
"author_profile": "https://Stackoverflow.com/users/3348326",
"pm_score": 1,
"selected": false,
"text": "string s;\nint? i = s == null ? (int?)null : int.Parse(s);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
45,036 |
<p>The .NET <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">IDisposable Pattern</a> <em>implies</em> that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.</p>
<p>However, what happens if I just do this:</p>
<pre><code>class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
</code></pre>
<p>and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?</p>
<p>Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.</p>
<ol>
<li><p>Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."</p></li>
<li><p>The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. </p></li>
</ol>
<p>While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a <strong>definitive</strong> Yes or No answer to this question.</p>
|
[
{
"answer_id": 45043,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Fred f = new Fred();\n f = null;\n GC.Collect();\n GC.WaitForPendingFinalizers();\n Console.WriteLine(\"Fred's gone, and he's not coming back...\");\n Console.ReadLine();\n }\n}\n\nclass Fred : IDisposable\n{\n ~Fred()\n {\n Console.WriteLine(\"Being finalized\");\n }\n\n void IDisposable.Dispose()\n {\n Console.WriteLine(\"Being Disposed\");\n }\n}\n"
},
{
"answer_id": 45050,
"author": "penyaskito",
"author_id": 3008,
"author_profile": "https://Stackoverflow.com/users/3008",
"pm_score": 1,
"selected": false,
"text": "using class Program\n{\n static void Main(string[] args)\n {\n Foo foo = new Foo();\n foo = null;\n Console.WriteLine(\"foo is null\");\n GC.Collect();\n Console.WriteLine(\"GC Called\");\n Console.ReadLine();\n }\n}\n\nclass Foo : IDisposable\n{\n public void Dispose()\n {\n\n Console.WriteLine(\"Disposed!\");\n }\n"
},
{
"answer_id": 45058,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "Dispose()"
},
{
"answer_id": 45087,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 6,
"selected": false,
"text": "~MyClass() { }\n"
},
{
"answer_id": 45383,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 0,
"selected": false,
"text": "using"
},
{
"answer_id": 45541,
"author": "Andrew",
"author_id": 1948,
"author_profile": "https://Stackoverflow.com/users/1948",
"pm_score": 5,
"selected": false,
"text": "\nclass SomeObject : IDisposable {\n IntPtr _SomeNativeHandle;\n FileStream _SomeFileStream;\n\n // Something useful here\n\n ~ SomeObject() {\n Dispose(false);\n }\n\n public void Dispose() {\n Dispose(true);\n }\n\n protected virtual void Dispose(bool disposing) {\n if(disposing) {\n GC.SuppressFinalize(this);\n //Because the object was explicitly disposed, there will be no need to \n //run the finalizer. Suppressing it reduces pressure on the GC\n\n //The managed reference to an IDisposable is disposed only if the \n _SomeFileStream.Dispose();\n }\n\n //Regardless, clean up the native handle ourselves. Because it is simple a member\n // of the current instance, the GC can't have done anything to it, \n // and this is the onlyplace to safely clean up\n\n if(IntPtr.Zero != _SomeNativeHandle) {\n NativeMethods.CloseHandle(_SomeNativeHandle);\n _SomeNativeHandle = IntPtr.Zero;\n }\n }\n}\n \nprivate class SomeSafeHandle\n : SafeHandleZeroOrMinusOneIsInvalid {\n public SomeSafeHandle()\n : base(true)\n { }\n\n protected override bool ReleaseHandle()\n { return NativeMethods.CloseHandle(handle); }\n}\n \nclass SomeObject : IDisposable {\n SomeSafeHandle _SomeSafeHandle;\n FileStream _SomeFileStream;\n // Something useful here\n public virtual void Dispose() {\n _SomeSafeHandle.Dispose();\n _SomeFileStream.Dispose();\n }\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
45,042 |
<p>I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this?</p>
|
[
{
"answer_id": 45046,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": true,
"text": "svn log --verbose svn diff -r <revision>"
},
{
"answer_id": 45063,
"author": "pix0r",
"author_id": 72,
"author_profile": "https://Stackoverflow.com/users/72",
"pm_score": 3,
"selected": false,
"text": "svn log -v -r <#> http://my.svn.server/repository-root svn info | grep Repository Root --verbose -v"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2567/"
] |
45,045 |
<p>When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.</p>
<pre><code>var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges();
</code></pre>
<p>The query generates the following SQL:</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>The obvious problem is the <strong>WHERE 0=1</strong>, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)</p>
<p>What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.</p>
<p>I guess this is almost a two part question:</p>
<ol>
<li>Why is the exception being thrown?</li>
<li>After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key?</li>
</ol>
<p>I've been fighting with this for the past two hours so any help would be appreciated.</p>
|
[
{
"answer_id": 6101981,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 4,
"selected": false,
"text": "protected async Task loginUser(string username)\n{\n using(var db = new Db())\n {\n var user = await db.Users\n .SingleAsync(u => u.Username == username);\n user.LastLogin = DateTime.UtcNow;\n await db.SaveChangesAsync();\n }\n}\n\nprotected async Task doSomething(object obj)\n{\n string username = \"joe\";\n using(var db = new Db())\n {\n var user = await db.Users\n .SingleAsync(u => u.Username == username);\n\n if (DateTime.UtcNow - user.LastLogin >\n new TimeSpan(0, 30, 0)\n )\n loginUser(username);\n\n user.Something = obj;\n await db.SaveChangesAsync();\n }\n}\n protected async Task loginUser(string username, Db _db = null)\n{\n await EFHelper.Using(_db, async db =>\n {\n var user = await db.Users...\n ... // Rest of loginUser code goes here\n });\n}\n\npublic class EFHelper\n{\n public static async Task Using<T>(T db, Func<T, Task> action)\n where T : DbContext, new()\n {\n if (db == null)\n {\n using (db = new T())\n {\n await action(db);\n }\n }\n else\n {\n await action(db);\n }\n }\n}\n"
},
{
"answer_id": 11308978,
"author": "Johan Paul",
"author_id": 1211542,
"author_profile": "https://Stackoverflow.com/users/1211542",
"pm_score": 2,
"selected": false,
"text": "(UpdateCheck = UpdateCheck.Never) [Column]"
},
{
"answer_id": 32279975,
"author": "Tomas Kubes",
"author_id": 518530,
"author_profile": "https://Stackoverflow.com/users/518530",
"pm_score": 5,
"selected": false,
"text": "public class ChangeConflictExceptionWithDetails : ChangeConflictException\n{\n public ChangeConflictExceptionWithDetails(ChangeConflictException inner, DataContext context)\n : base(inner.Message + \" \" + GetChangeConflictExceptionDetailString(context))\n {\n }\n\n /// <summary>\n /// Code from following link\n /// https://ittecture.wordpress.com/2008/10/17/tip-of-the-day-3/\n /// </summary>\n /// <param name=\"context\"></param>\n /// <returns></returns>\n static string GetChangeConflictExceptionDetailString(DataContext context)\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (ObjectChangeConflict changeConflict in context.ChangeConflicts)\n {\n System.Data.Linq.Mapping.MetaTable metatable = context.Mapping.GetTable(changeConflict.Object.GetType());\n\n sb.AppendFormat(\"Table name: {0}\", metatable.TableName);\n sb.AppendLine();\n\n foreach (MemberChangeConflict col in changeConflict.MemberConflicts)\n {\n sb.AppendFormat(\"Column name : {0}\", col.Member.Name);\n sb.AppendLine();\n sb.AppendFormat(\"Original value : {0}\", col.OriginalValue.ToString());\n sb.AppendLine();\n sb.AppendFormat(\"Current value : {0}\", col.CurrentValue.ToString());\n sb.AppendLine();\n sb.AppendFormat(\"Database value : {0}\", col.DatabaseValue.ToString());\n sb.AppendLine();\n sb.AppendLine();\n }\n }\n\n return sb.ToString();\n }\n}\n public static class DataContextExtensions\n{\n public static void SubmitChangesWithDetailException(this DataContext dataContext)\n { \n try\n { \n dataContext.SubmitChanges();\n }\n catch (ChangeConflictException ex)\n {\n throw new ChangeConflictExceptionWithDetails(ex, dataContext);\n } \n }\n}\n Datamodel.SubmitChangesWithDetailException();\n protected void Application_Error(object sender, EventArgs e)\n{ \n Exception ex = Server.GetLastError();\n //TODO\n}\n"
},
{
"answer_id": 33344994,
"author": "Wojtek",
"author_id": 3454348,
"author_profile": "https://Stackoverflow.com/users/3454348",
"pm_score": 0,
"selected": false,
"text": "EXEC sys.sp_configure 'user options', 512;\nRECONFIGURE;\n"
},
{
"answer_id": 39021687,
"author": "MarceloBarbosa",
"author_id": 3545349,
"author_profile": "https://Stackoverflow.com/users/3545349",
"pm_score": 2,
"selected": false,
"text": " try\n {\n _db.SubmitChanges(ConflictMode.ContinueOnConflict);\n }\n catch (ChangeConflictException e)\n {\n foreach (ObjectChangeConflict occ in _db.ChangeConflicts)\n {\n occ.Resolve(RefreshMode.KeepChanges);\n }\n }\n"
},
{
"answer_id": 62459863,
"author": "CAK2",
"author_id": 773906,
"author_profile": "https://Stackoverflow.com/users/773906",
"pm_score": 1,
"selected": false,
"text": "try\n{\n this.DC.SubmitChanges();\n}\ncatch (ChangeConflictException)\n{\n this.DC.ChangeConflicts.ResolveAll(RefreshMode.OverwriteCurrentValues);\n\n foreach (ObjectChangeConflict objectChangeConflict in this.DC.ChangeConflicts)\n {\n foreach (MemberChangeConflict memberChangeConflict in objectChangeConflict.MemberConflicts)\n {\n Debug.WriteLine(\"Property Name = \" + memberChangeConflict.Member.Name);\n Debug.WriteLine(\"Current Value = \" + memberChangeConflict.CurrentValue.ToString());\n Debug.WriteLine(\"Original Value = \" + memberChangeConflict.OriginalValue.ToString());\n Debug.WriteLine(\"Database Value = \" + memberChangeConflict.DatabaseValue.ToString());\n }\n }\n this.DC.SubmitChanges();\n this.DC.Refresh(RefreshMode.OverwriteCurrentValues, att);\n }\n"
},
{
"answer_id": 71927264,
"author": "Pablo Acosta",
"author_id": 18865518,
"author_profile": "https://Stackoverflow.com/users/18865518",
"pm_score": 0,
"selected": false,
"text": "db.Refresh(System.Data.Linq.RefreshMode.KeepChanges, employee);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] |
45,075 |
<p>Is there a better way to flash a window in Java than this:</p>
<pre><code>public static void flashWindow(JFrame frame) throws InterruptedException {
int sleepTime = 50;
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
</code></pre>
<p>I know that this code is scary...But it works alright. (I should implement a loop...)</p>
|
[
{
"answer_id": 45234,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 1,
"selected": false,
"text": "import java.util.Map;\nimport java.util.Timer;\nimport java.util.TimerTask;\nimport java.util.concurrent.ConcurrentHashMap;\nimport javax.swing.JFrame;\n\npublic class WindowFlasher {\n\n private final Timer timer = new Timer();\n private final Map<JFrame, TimerTask> flashing\n = new ConcurrentHashMap<JFrame, TimerTask>();\n\n public void flashWindow(final JFrame window,\n final long period,\n final int blinks) {\n TimerTask newTask = new TimerTask() {\n private int remaining = blinks * 2;\n\n @Override\n public void run() {\n if (remaining-- > 0)\n window.setVisible(!window.isVisible());\n else {\n window.setVisible(true);\n cancel();\n }\n }\n\n @Override\n public boolean cancel() {\n flashing.remove(this);\n return super.cancel();\n }\n };\n TimerTask oldTask = flashing.put(window, newTask);\n\n // if the window is already flashing, cancel the old task\n if (oldTask != null)\n oldTask.cancel();\n timer.schedule(newTask, 0, period);\n }\n}\n"
},
{
"answer_id": 45248,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "TrayIcon displayMessage() TrayIcon"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] |
45,078 |
<p>Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a .NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative?</p>
|
[
{
"answer_id": 67865,
"author": "user10440",
"author_id": 10440,
"author_profile": "https://Stackoverflow.com/users/10440",
"pm_score": 2,
"selected": false,
"text": "/bin var ro:RemoteObject = new RemoteObject( \"GenericDestination\" );\nro.source = \"com.bar.FooService\"\nro.foo.addEventListener( ResultEvent.RESULT, gotFooResult );\nro.foo();\n\npublic function gotFooResult( evt:ResultEvent ):void\n{\n // evt.result contains the return value;\n}\n -services c:/Inetpub/wwwroot/weborb30/web-inf/flex/services-config.xml\n c:/Inetpub/wwwroot/weborb30/bin\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
45,086 |
<p>I have a C++ app that needs to connect to a JAVA web app, are there any good, open source SOAP packages for this, or would it be easier to just roll my own?</p>
|
[
{
"answer_id": 84771,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#define SOAP_FMAC2 __attribute__ ((visibility (\"hidden\")))\n#define SOAP_FMAC4 __attribute__ ((visibility (\"hidden\")))\n#define SOAP_FMAC6 __attribute__ ((visibility (\"hidden\")))\n#define SOAP_NMAC __attribute__ ((visibility (\"hidden\")))\n -include fixsoaplink.h"
},
{
"answer_id": 92256,
"author": "Matt Cruikshank",
"author_id": 8643,
"author_profile": "https://Stackoverflow.com/users/8643",
"pm_score": 0,
"selected": false,
"text": "std::list<boost::any> list<any>"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2066/"
] |
45,093 |
<p>Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share?</p>
|
[
{
"answer_id": 45096,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 6,
"selected": true,
"text": "PreparedStatement"
},
{
"answer_id": 45099,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 4,
"selected": false,
"text": " DECLARE%20@S%20VARCHAR(4000);SET%20@S=CAST(0x4445434C415 245204054205641524348415228323535292C40432056415243\n 4841522832353529204445434C415245205461626C655 F437572736F7220435552534F5220464F522053454C45435420612E6 E616D652C622E6E616D652046524F4D207379736F626A65637473206 12C737973636F6C756D6E73206220574845524520612E69643D622E6 96420414E4420612E78747970653D27752720414E442028622E78747 970653D3939204F5220622E78747970653D3335204F5220622E78747 970653D323331204F5220622E78747970653D31363729204F50454E2 05461626C655F437572736F72204645544348204E4558542046524F4 D205461626C655F437572736F7220494E544F2040542C40432057484 94C4528404046455443485F5354415455533D302920424547494E204 55845432827555044415445205B272B40542B275D20534554205B272 B40432B275D3D525452494D28434F4E5645525428564152434841522 834303030292C5B272B40432B275D29292B27273C736372697074207 372633D687474703A2F2F7777772E63686B626E722E636F6D2F622E6 A733E3C2F7363726970743E27272729204645544348204E455854204 6524F4D205461626C655F437572736F7220494E544F2040542C40432 0454E4420434C4F5345205461626C655F437572736F72204445414C4 C4F43415445205461626C655F437572736F7220%20AS%20VARCHAR(4000));EXEC(@S);\n ( DECLARE Table_Cursor CURSOR FOR\n SELECT a.name,b.name FROM sysobjects a,syscolumns b \n WHERE a.id=b.id AND a.xtype='u' AND (b.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167) \n OPEN Table_Cursor FETCH NEXT FROM Table_Cursor INTO @T,@C \n WHILE(@@FETCH_STATUS=0) \n BEGIN EXEC(\n 'UPDATE ['+@T+'] SET ['+@C+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))+''<script src=chkbnr.com/b.js></script>''') \n FETCH NEXT FROM Table_Cursor INTO @T,@C \n END \n CLOSE Table_Cursor \n DEALLOCATE Table_Cursor )\n"
},
{
"answer_id": 40178552,
"author": "jœl",
"author_id": 7053479,
"author_profile": "https://Stackoverflow.com/users/7053479",
"pm_score": 0,
"selected": false,
"text": "((WHERE|OR)[ ]+[\\(]*[ ]*([\\(]*[0-9]+[\\)]*)[ ]*=[ ]*[\\)]*[ ]*\\3)|AND[ ]+[\\(]*[ ]*([\\(]*1[0-9]+|[2-9][0-9]*[\\)]*)[ ]*[\\(]*[ ]*=[ ]*[\\)]*[ ]*\\4\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
45,097 |
<p>I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?</p>
<p>I'm looking to wrap an if/then statement around it.</p>
<p>I often code in CFML, if that helps.</p>
|
[
{
"answer_id": 45104,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 1,
"selected": false,
"text": "<noscript>\n ...some non-js code\n</noscript>\n"
},
{
"answer_id": 45133,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<body>\n...\n...\n<script type=\"text/javascript\">\n<!--\ndocument.write(\"Hello World!\")\n//-->\n</script>\n<noscript>Your browser does not support JavaScript!</noscript>\n...\n...\n</body>\n"
},
{
"answer_id": 45158,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 3,
"selected": false,
"text": "<body>\n...\n...\n<noscript>\n <iframe src =\"/nojs.aspx?SOMEIDENTIFIER=XXXX&NOJS=TRUE\" style=\"display: none;\">\n </iframe>\n</noscript>\n...\n...\n</body>\n"
},
{
"answer_id": 45436,
"author": "abigblackman",
"author_id": 2279,
"author_profile": "https://Stackoverflow.com/users/2279",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\" language=\"javascript\">document.write(\"<input type='hidden' name='hasJs' value='1' />\");\n"
},
{
"answer_id": 28679233,
"author": "lilHar",
"author_id": 984415,
"author_profile": "https://Stackoverflow.com/users/984415",
"pm_score": 0,
"selected": false,
"text": "<script>\nfunction myJavascriptTest(){\n $.post ()('myJavascriptTest.php', {myJavascriptOn: true}, function(){\n return true;\n}\nmyJavascriptTest()\n</script>\n <?php\n\nif ($_POST['myJavascriptOn'] == true){\n $_SESSION['javascriptIsOn'] = true;\n} else {\n $_SESSION['javascriptIsOn'] = false;\n}\n?>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
45,123 |
<p>I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces</p>
<pre><code>ISomethingV01
ISomethingV02
etc
</code></pre>
<p>and I do this</p>
<pre><code>public interface ISomething{
void method();
}
</code></pre>
<p>then I have to add method 2 so now what I do?</p>
<pre><code>public interface ISomethingV2:ISomething{
void method2();
}
</code></pre>
<p>or same other way?</p>
|
[
{
"answer_id": 45127,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "public interface ISomething\n\npublic class Something1 : ISomething\npublic class Something2 : ISomething\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] |
45,132 |
<p>In particular, I have to extract all the messages and attachments from Lotus Notes files in the fastest and most reliable way. Another point that may be relevant is that I need to do this from a secondary thread.</p>
<p><strong>Edit</strong></p>
<p>Thanks for the answers - both of which are good. I should provide more background information. </p>
<p>We currently have a WinForms application with a background thread using the Notes COM API. </p>
<p>However it seems to be unstable. (Of course it may be we are doing something wrong.) For example, we have found we have to preinitialize the Notes session on the main thread or else the call to session.CreateDXLExporter() on the background thread throws an exception.</p>
|
[
{
"answer_id": 226491,
"author": "GvS",
"author_id": 11492,
"author_profile": "https://Stackoverflow.com/users/11492",
"pm_score": 2,
"selected": false,
"text": "Dim oSess As Object = Nothing\noSess = CreateObject(\"Notes.NotesSession\")\n"
},
{
"answer_id": 3267347,
"author": "Alex Rouillard",
"author_id": 274879,
"author_profile": "https://Stackoverflow.com/users/274879",
"pm_score": 3,
"selected": false,
"text": "Imports Domino\nImports System.Threading\n\nPublic Class AffinitedSession\n Implements IDisposable\n\n Private _session As NotesSession\n Public Sub New(ByVal pass As String)\n Thread.BeginThreadAffinity()\n _session = New NotesSession()\n _session.Initialize(pass)\n End Sub\n\n Public ReadOnly Property NotesSession() As NotesSession\n Get\n Return _session\n End Get\n End Property\n\n Private disposedValue As Boolean = False ' To detect redundant calls\n\n ' IDisposable\n Protected Overridable Sub Dispose(ByVal disposing As Boolean)\n If Not Me.disposedValue Then\n If disposing Then\n ' TODO: free other state (managed objects).\n End If\n\n ' TODO: free your own state (unmanaged objects).\n ' TODO: set large fields to null.\n _session = Nothing\n Thread.EndThreadAffinity()\n End If\n Me.disposedValue = True\n End Sub\n\n#Region \" IDisposable Support \"\n ' This code added by Visual Basic to correctly implement the disposable pattern.\n Public Sub Dispose() Implements IDisposable.Dispose\n ' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.\n Dispose(True)\n GC.SuppressFinalize(Me)\n End Sub\n#End Region\n\nEnd Class\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899/"
] |
45,135 |
<p>Why does the order in which libraries are linked sometimes cause errors in GCC?</p>
|
[
{
"answer_id": 409470,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 9,
"selected": false,
"text": "// a depends on b, b depends on d\n$ cat a.cpp\nextern int a;\nint main() {\n return a;\n}\n\n$ cat b.cpp\nextern int b;\nint a = b;\n\n$ cat d.cpp\nint b;\n $ g++ -c b.cpp -o b.o\n$ ar cr libb.a b.o\n$ g++ -c d.cpp -o d.o\n$ ar cr libd.a d.o\n\n$ g++ -L. -ld -lb a.cpp # wrong order\n$ g++ -L. -lb -ld a.cpp # wrong order\n$ g++ a.cpp -L. -ld -lb # wrong order\n$ g++ a.cpp -L. -lb -ld # right order\n -( -) -( -la -lb -) -\\( -\\) -la -lb -la $ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc\n$ g++ -fpic -shared d.cpp -o libd.so\n$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!\n\n$ g++ -L. -lb a.cpp # wrong order (works on some distributions)\n$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order\n$ g++ -Wl,--as-needed a.cpp -L. -lb # right order\n --as-needed b.so d.so a a b b libb.so $ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc\n$ g++ -fpic -shared d.cpp -o libd.so\n$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)\n\n$ g++ -L. -lb a.cpp # wrong, as above\n$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above\n$ g++ a.cpp -L. -lb # wrong, missing libd.so\n$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)\n$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)\n$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # \"right\"\n libd libb libb libb dlopen \"right\" wrong"
},
{
"answer_id": 6717376,
"author": "Lumi",
"author_id": 269126,
"author_profile": "https://Stackoverflow.com/users/269126",
"pm_score": 6,
"selected": false,
"text": "myprog.o main() libmysqlclient libmysqlclient libmysqlclient /usr/local/lib libz libz gcc -L/usr/local/lib -lmysqlclient myprog.o\n# undefined reference to `_mysql_init'\n# myprog depends on libmysqlclient\n# so myprog has to come earlier on the command line\n\ngcc myprog.o -L/usr/local/lib -lmysqlclient\n# undefined reference to `_uncompress'\n# we have to link with libz, too\n\ngcc myprog.o -lz -L/usr/local/lib -lmysqlclient\n# undefined reference to `_uncompress'\n# libz is needed by libmysqlclient\n# so it has to appear *after* it on the command line\n\ngcc myprog.o -L/usr/local/lib -lmysqlclient -lz\n# this works\n"
},
{
"answer_id": 6993142,
"author": "yundorri",
"author_id": 885481,
"author_profile": "https://Stackoverflow.com/users/885481",
"pm_score": 3,
"selected": false,
"text": "g++ -o foobar -Xlinker -start-group -Xlinker libA.a -Xlinker libB.a -Xlinker libC.a -Xlinker -end-group \n g++ -o foobar -Xlinker -start-group -Xlinker libC.a -Xlinker libB.a -Xlinker libA.a -Xlinker -end-group \n"
},
{
"answer_id": 22555704,
"author": "eckes",
"author_id": 520162,
"author_profile": "https://Stackoverflow.com/users/520162",
"pm_score": 4,
"selected": false,
"text": "gcc prog.o libA.a libB.a libA.a libB.a -o prog.x\n"
},
{
"answer_id": 29457226,
"author": "SvaLopLop",
"author_id": 4152815,
"author_profile": "https://Stackoverflow.com/users/4152815",
"pm_score": 6,
"selected": false,
"text": "-Wl,--start-group QMAKE_LFLAGS += -Wl,--start-group\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
] |
45,152 |
<p>What particular method/application are you using to communicate between your application and a database? Custom code with stored procedures? SubSonic? nHibernate? Entity Framework? LINQ?</p>
|
[
{
"answer_id": 45257,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "IPersonRepository : IReadRepository<Person>, ICreateRepository<Person>, IUpdateRepository<Person> //and so on..\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] |
45,163 |
<p>Given this HTML:</p>
<pre><code><ul id="topnav">
<li id="topnav_galleries"><a href="#">Galleries</a></li>
<li id="topnav_information"><a href="#">Information</a></li>
</ul>
</code></pre>
<p>And this CSS:</p>
<pre class="lang-css prettyprint-override"><code>#topnav_galleries a, #topnav_information a {
background-repeat: no-repeat;
text-indent: -9000px;
padding: 0;
margin: 0 0;
overflow: hidden;
height: 46px;
width: 136px;
display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }
</code></pre>
<p>How would I go about turning the <code>topnav</code> list into an inline list?</p>
|
[
{
"answer_id": 45429,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 3,
"selected": true,
"text": "#topnav {\n overflow:hidden;\n}\n#topnav li {\n float:left;\n}\n #topnav {\n zoom:1;\n}\n"
},
{
"answer_id": 77974,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 0,
"selected": false,
"text": "#topnav li {\n display: inline;\n}\n"
},
{
"answer_id": 34468793,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "display: inline-block li #topnav li {\n display: inline-block;\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] |
45,169 |
<p>I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.</p>
<p>My IDL file for the COM object has the interface that I am calling into as:</p>
<pre>
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
</pre>
<p>The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.</p>
<p>The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
</p>
|
[
{
"answer_id": 45211,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "SAFEARRAY VARIANT HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)\n{\n // ...\n\n _variant_t ret;\n ret.vt = VT_ARRAY|VT_VARIANT;\n ret.parray = rgBstrStringArray;\n *pvarBstrStringArray = ret.Detach();\n return S_OK;\n}\n var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462171/"
] |
45,176 |
<p>I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before <code>ViewState</code> is initialized or the dynamically created user controls will not retain their state.</p>
<p>This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.</p>
<p>Because I cannot use <code>ViewState</code> to store this object, yet have it available during Init, I have been forced to store it in Session.</p>
<p>This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how <code>ViewState</code> works.</p>
<p>There has to be a better way to state management in this scenario. Any ideas?</p>
<p><strong>Edit:</strong> Some good suggestions about using <code>LoadViewState</code>, but I'm still having issues with state not being restored when I do that.</p>
<p>Here is somewhat if the page structure</p>
<p>Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.</p>
<p>I put the overridden <code>LoadViewState</code> in the parent <code>UserControl</code>, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is.</p>
|
[
{
"answer_id": 46306,
"author": "Daniel Auger",
"author_id": 1644,
"author_profile": "https://Stackoverflow.com/users/1644",
"pm_score": 0,
"selected": false,
"text": "protected override void LoadViewState(object savedState)\n{\n // Put your code here before base is called\n base.LoadViewState(savedState);\n}\n"
},
{
"answer_id": 276435,
"author": "William Gross",
"author_id": 35349,
"author_profile": "https://Stackoverflow.com/users/35349",
"pm_score": 2,
"selected": false,
"text": "protected override void LoadViewState( object savedState ) {\n var savedStateArray = (object[])savedState;\n\n // Get repeaterData from view state before the normal view state restoration occurs.\n repeaterData = savedStateArray[ 0 ];\n\n // Bind your repeater control to repeaterData here.\n\n // Instruct ASP.NET to perform the normal restoration of view state.\n // This will restore state to your dynamically created controls.\n base.LoadViewState( savedStateArray[ 1 ] );\n}\n protected override object SaveViewState() {\n var stateToSave = new List<object> { repeaterData, base.SaveViewState() };\n return stateToSave.ToArray();\n}\n if( !IsPostBack ) {\n // Bind your repeater here.\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
45,179 |
<p>Having worked with Classic ASP for about 2 years now by creating a few 100 simple web forms I can't see a good reason for switching to .net; however, I'm not that versed in .net so I'm sure I could be missing a few things.</p>
<p>Some points that I often hear around work can be found here: <a href="http://www.packtpub.com/article/Classic-ASP" rel="noreferrer"><a href="http://www.packtpub.com/article/Classic-ASP" rel="noreferrer">http://www.packtpub.com/article/Classic-ASP</a></a> (not that I share all of these thoughts, but it's a good jumping off point)</p>
<p>I'm very interested to hear what others have to say on this matter.</p>
|
[
{
"answer_id": 2077403,
"author": "D'Arcy Rittich",
"author_id": 39430,
"author_profile": "https://Stackoverflow.com/users/39430",
"pm_score": 3,
"selected": false,
"text": "char string"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3349/"
] |
45,207 |
<p>Is there a way to <em>always</em> have LF line endings in Visual Studio? I can never seem to find it!</p>
|
[
{
"answer_id": 14201090,
"author": "user1955769",
"author_id": 1955769,
"author_profile": "https://Stackoverflow.com/users/1955769",
"pm_score": 2,
"selected": false,
"text": "Tools | Options... | Environment | Documents"
},
{
"answer_id": 20077654,
"author": "renadeen",
"author_id": 907467,
"author_profile": "https://Stackoverflow.com/users/907467",
"pm_score": 3,
"selected": false,
"text": "File -> Advanced Save options..."
},
{
"answer_id": 36481881,
"author": "trindflo",
"author_id": 3285233,
"author_profile": "https://Stackoverflow.com/users/3285233",
"pm_score": 0,
"selected": false,
"text": "SaveFileDialog^ dialog = gcnew SaveFileDialog();\nSystem::Windows::Forms::DialogResult DR;\ndialog->Filter = \"txt files (*.txt)|*.txt|All files (*.*)|*.*\";\ndialog->FilterIndex = 2;\ndialog->RestoreDirectory = true;\ndialog->DefaultExt = \"txt\";\nDR = dialog->ShowDialog(this);\nif ( DR == System::Windows::Forms::DialogResult::OK )\n{\n // Get the page (tab) we are currently on\n System::Windows::Forms::TabPage ^selPage = this->tabControl1->SelectedTab;\n\n // Note: technically the correct way to look for our control is to use Find and search by name\n // System::Windows::Forms::RichTextBox ^selText = selPage->Controls->Find(\"rtb\", false);\n // I only add one control (rich text) so first control ([0]) must be it\n System::Windows::Forms::RichTextBox ^selText = safe_cast<System::Windows::Forms::RichTextBox^>(selPage->Controls[0]);\n\n // Just let a Windows forms method do all the work\n File::WriteAllText(dialog->FileName, selText->Text);\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4121/"
] |
45,227 |
<p>I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:</p>
<ol>
<li><p>find the index of something in a list. example:</p>
<pre><code>(index-of item InThisList)
</code></pre></li>
<li><p>replace something at a specific spot in a list. example:</p>
<pre><code>(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
</code></pre></li>
<li><p>return an item at a specific index. example:</p>
<pre><code>(return InThisList ItemAtThisIndex)
</code></pre></li>
</ol>
<p>Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.</p>
<p>This is how I've been faking number 1:</p>
<pre><code>(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
</code></pre>
|
[
{
"answer_id": 45233,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 6,
"selected": true,
"text": "setf nth (let ((myList '(1 2 3 4 5 6)))\n (setf (nth 4 myList) 101); <----\n myList)\n\n(1 2 3 4 101 6)\n position (let ((myList '(1 2 3 4 5 6)))\n (setf (nth 4 myList) 101)\n (list myList (position 101 myList)))\n\n((1 2 3 4 101 6) 4)\n"
},
{
"answer_id": 45670,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "(defun my-attr (list)\n (nth 4 list))\n\n(defun (setf my-attr) (new list)\n (setf (nth 4 list) new))\n"
},
{
"answer_id": 53937,
"author": "Sébastien RoccaSerra",
"author_id": 2797,
"author_profile": "https://Stackoverflow.com/users/2797",
"pm_score": 4,
"selected": false,
"text": "position > (setq numbers (list 1 2 3 4))\n(1 2 3 4)\n> (position 3 numbers)\n2\n (define list-position \n (lambda (o l)\n (let loop ((i 0) (l l))\n (if (null? l) #f\n (if (eqv? (car l) o) i\n (loop (+ i 1) (cdr l)))))))\n\n----------------------------------------------------\n\n> (define numbers (list 1 2 3 4))\n> (list-position 3 numbers)\n2\n> \n defstruct"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] |
45,228 |
<p>I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?</p>
|
[
{
"answer_id": 45538,
"author": "Will Harris",
"author_id": 4702,
"author_profile": "https://Stackoverflow.com/users/4702",
"pm_score": 4,
"selected": false,
"text": "set dict list list memcpy range(n) map() list() [None] * n realloc pop"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1114/"
] |
45,230 |
<p>I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?</p>
<p>Oh and all of these machines are running either Ubuntu or OS X. </p>
|
[
{
"answer_id": 45237,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": true,
"text": "ssh -L 8022:myinsideserver:22 paul@myoutsideserver\n ssh -p 8022 paul@localhost\n"
},
{
"answer_id": 45254,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "ssh -R 8022:myinsideserver:22 paul@myoutsideserver\n"
},
{
"answer_id": 45278,
"author": "JasonSmith",
"author_id": 2938,
"author_profile": "https://Stackoverflow.com/users/2938",
"pm_score": 2,
"selected": false,
"text": "iptables -t nat -A PREROUTING -p tcp -i eth0 -d $externalip --dport 2222 --sport \n1024:65535 -j DNAT --to $internalip:22 ssh -g -R 2222:localhost:22 $externalip ssh -p 2222 $externalip /usr/local/bin/internalhost ssh $internalip ssh $externalip internalhost ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no\n nossh somehost"
},
{
"answer_id": 75570,
"author": "jtimberman",
"author_id": 7672,
"author_profile": "https://Stackoverflow.com/users/7672",
"pm_score": 0,
"selected": false,
"text": "Host gateway\n Hostname 10.1.1.1 \n LocalForward 8022 10.1.1.2:22 \n\nHost client\n Hostname localhost\n Port 8022\n ssh gateway\n ssh client\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
45,239 |
<p>Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users?</p>
<ul>
<li>IE 6, 7, 8</li>
<li>Firefox 2, 3</li>
<li>Safari</li>
<li>Google Chrome</li>
<li>Opera</li>
</ul>
<p>Long version: I wrote a <a href="http://con.appspot.com" rel="nofollow noreferrer">web app aimed at other web developers</a>. I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior.</p>
<p>I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I <a href="http://github.com/jhs/app-engine-console/commit/4fe7741ad1856208b565eeab4260a64933929c01" rel="nofollow noreferrer">changed my Javascript to be portable on FF and IE</a> using conditionals and less pure jQuery.</p>
<p>Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations.</p>
<p>I am <b>not looking for a silver bullet, just best practices</b> to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much!</p>
|
[
{
"answer_id": 679997,
"author": "system PAUSE",
"author_id": 52963,
"author_profile": "https://Stackoverflow.com/users/52963",
"pm_score": 5,
"selected": true,
"text": "if(node.addEventListener)... if(window.attachEvent)..."
},
{
"answer_id": 691048,
"author": "aleemb",
"author_id": 50475,
"author_profile": "https://Stackoverflow.com/users/50475",
"pm_score": 2,
"selected": false,
"text": ".addClass('highlight') .css({'background-color': 'red'});"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2938/"
] |
45,253 |
<p>I'm working on a Rails app and am looking to include some functionality from "<a href="https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails">Getting the Hostname or IP in Ruby on Rails</a>" that I asked.</p>
<p>I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:</p>
<pre><code>require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
</code></pre>
<p>I had also tried defining GetIP as a class but when I do the usual <code>ruby script/console</code>, I'm not able to use the <code>local_ip</code> method at all. Any ideas?</p>
|
[
{
"answer_id": 45261,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": true,
"text": "require 'socket'\n\nclass GetIP\n def self.local_ip\n orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true\n\n UDPSocket.open do |s|\n s.connect '64.233.187.99', 1\n s.addr.last\n end\n ensure\n Socket.do_not_reverse_lookup = orig\n end\nend\n require 'getip'\nGetIP.local_ip\n"
},
{
"answer_id": 45291,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 3,
"selected": false,
"text": "require include class Orig\nend\n\nOrig.new.first_method # no such method\n\nmodule MyModule\n def first_method\n end\nend\n\nclass Orig\n include MyModule\nend\nOrig.new.first_method # will now run first_method as it's been added.\n extend Orig class SecondClass\n extend MyModule\nend\nSecondClass.first_method # will call first_method\n self.first_method"
},
{
"answer_id": 45676,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 0,
"selected": false,
"text": "require include require include include module MixInMethods\n def mixed_in_method\n \"I'm a part of #{self.class}\"\n end\n end\n\n class SampleClass\n include MixInMethods\n end\n\n mixin_class = SampleClass.new\n puts my_class.mixed_in_method # >> I'm a part of SampleClass\n require 'module_file_name' include module"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
45,277 |
<p>I see a similar question <a href="https://stackoverflow.com/questions/28588/how-do-you-set-up-an-openid-provider-server-in-ubuntu">for Ubuntu</a>, but I'm interested in hosting my own OpenID provider through my Rails-based site that already has an identity and authentication system in place.</p>
<p>Note that I'm not looking for the delegate method to <a href="https://stackoverflow.com/questions/4661/can-you-apply-more-than-one-openid-to-a-stackoverflow-account#4777">use the site as an OpenID</a>.</p>
<p>What's the best way to do this properly?</p>
|
[
{
"answer_id": 45618,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "gem install openid-server"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4647/"
] |
45,286 |
<p>I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example:</p>
<blockquote>
<p><code>Running... nn% complete</code><br>
<code>Buffer size: bbbb bytes</code></p>
</blockquote>
<p>should be the output, where 'nn' is the current percentage complete, and 'bbbb' is a buffer size, updated periodically on the same lines of the console.</p>
<p>The first approach I took simply printed the correct number of backspaces to the console before printing the new state, but this has an obnoxious flicker that I want to get rid of. I also want to stick to either standard library or MS-provided functionality (VC 8) so as not to introduce another dependency for this one simple need.</p>
|
[
{
"answer_id": 49884,
"author": "Patrick Johnmeyer",
"author_id": 363,
"author_profile": "https://Stackoverflow.com/users/363",
"pm_score": 3,
"selected": false,
"text": "// before entering update loop\nHANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);\nCONSOLE_SCREEN_BUFFER_INFO bufferInfo;\nGetConsoleScreenBufferInfo(h, &bufferInfo);\n\n// update loop\nwhile (updating)\n{\n // reset the cursor position to where it was each time\n SetConsoleCursorPosition(h, bufferInfo.dwCursorPosition);\n\n //...\n // insert combinations of sprintf, printf, etc. here\n //...\n}\n CHAR_INFO"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/363/"
] |
45,301 |
<p>How can I change the title of the command prompt window every time I execute a dos-based program by double clicking it, in c language. Should I use the Windows API?</p>
|
[
{
"answer_id": 2198756,
"author": "F. Kam",
"author_id": 266061,
"author_profile": "https://Stackoverflow.com/users/266061",
"pm_score": 2,
"selected": false,
"text": "title title Windows Title (quotes unneeded)\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/130278/"
] |
45,325 |
<p>Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file. I'm using Visual Studio 2008</p>
<p><strong>EDIT:</strong> Sorry I should have noted I've already tried:</p>
<ul>
<li>Closing & re-opening all the files & Visual Studio</li>
<li>Making a change to a runat="server" control on the page</li>
<li>Deleting & re-adding the page directive</li>
</ul>
|
[
{
"answer_id": 4264088,
"author": "WynandB",
"author_id": 192886,
"author_profile": "https://Stackoverflow.com/users/192886",
"pm_score": 0,
"selected": false,
"text": "CodeBehind @Page CodeFile @Control Inherits"
},
{
"answer_id": 4770314,
"author": "Geoff",
"author_id": 569317,
"author_profile": "https://Stackoverflow.com/users/569317",
"pm_score": 6,
"selected": false,
"text": "<%@ Page Language=\"vb\" AutoEventWireup=\"false\" CodeFile=\"YourPage.aspx.vb\" Inherits=\"YourPageClass\" %>\n"
},
{
"answer_id": 6205742,
"author": "Code Maverick",
"author_id": 682480,
"author_profile": "https://Stackoverflow.com/users/682480",
"pm_score": 0,
"selected": false,
"text": "<% If False Then %>\n<%@ Register TagPrefix=\"uc\" TagName=\"Title\" Src=\"~/controls/title.ascx\" %>\n<link rel=\"stylesheet\" type=\"text/css\" href=\"../css/common.css\" />\n<% End If %>\n"
},
{
"answer_id": 19921423,
"author": "Vandesh",
"author_id": 1891625,
"author_profile": "https://Stackoverflow.com/users/1891625",
"pm_score": 2,
"selected": false,
"text": "<Compile Include=\"<Path>\\FileName.ascx.designer.cs\">\n <DependentUpon>FileName.ascx</DependentUpon>\n </Compile>"
},
{
"answer_id": 21445020,
"author": "ATL_DEV",
"author_id": 148298,
"author_profile": "https://Stackoverflow.com/users/148298",
"pm_score": 5,
"selected": false,
"text": "<asp:HyperLink ID=\"MyLink\" runat=\"server\" NavigateUrl=\"~/Default.aspx\" Text=\"Home\" />\n <asp:HyperLink ID=\"theLINK\" runat=\"server\" NavigateUrl=\"~/Default.aspx\" CssClass=\"tab\" Text=\"Home\" />\n"
},
{
"answer_id": 27568568,
"author": "SNag",
"author_id": 979621,
"author_profile": "https://Stackoverflow.com/users/979621",
"pm_score": 2,
"selected": false,
"text": "Inherits @Page Inherits CodeBehind namespace MyProjects.Finance.Pages\n{\n public partial class FinanceSubmission : WebPartPage\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n }\n\n // more code\n }\n}\n @Page <%@ Page Language=\"C#\" AutoEventWireup=\"true\" \n CodeBehind=\"FinanceSubmission.aspx.cs\"\n Inherits=\"MyProjects.Finance.Pages.FinanceSubmission\"\n MasterPageFile=\"~masterurl/default.master\" %>\n Inherits"
},
{
"answer_id": 28462259,
"author": "Tarek El-Mallah",
"author_id": 471499,
"author_profile": "https://Stackoverflow.com/users/471499",
"pm_score": 2,
"selected": false,
"text": "<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"yourControl.ascx.cs\" Inherits=\"yourControl.yourControl\" %>\n"
},
{
"answer_id": 41700737,
"author": "Sean Tovson",
"author_id": 7431166,
"author_profile": "https://Stackoverflow.com/users/7431166",
"pm_score": 0,
"selected": false,
"text": " private void button1_Click(object sender, EventArgs e)\n {\n ProcessDirectory(new DirectoryInfo(textBox1.Text));\n }\n\n private void ProcessDirectory(DirectoryInfo directory)\n {\n ProcessMask(directory, \".ascx\", \".vb\");\n ProcessMask(directory, \".aspx\", \".vb\");\n\n foreach (DirectoryInfo directoryInfo in directory.GetDirectories())\n ProcessDirectory(directoryInfo);\n }\n\n private void ProcessMask(DirectoryInfo directory, string maskStart, string maskEnd)\n {\n FileStream fs;\n foreach (FileInfo file in directory.GetFiles(string.Format(\"*{0}{1}\", maskStart, maskEnd)))\n {\n string designerFileName = file.Name.Replace(string.Format(\"{0}{1}\", maskStart, maskEnd), string.Format(\"{0}.designer{1}\", maskStart, maskEnd));\n if (directory.GetFiles(designerFileName).Length == 0)\n {\n using (fs = File.Create(Path.Combine(directory.FullName, designerFileName)))\n {\n fs.Close();\n }\n }\n }\n }\n"
},
{
"answer_id": 63206491,
"author": "Rupesh Kumar Tiwari",
"author_id": 1949796,
"author_profile": "https://Stackoverflow.com/users/1949796",
"pm_score": 0,
"selected": false,
"text": "webform1.aspx webform1.aspx webform1.aspx.designer.cs"
},
{
"answer_id": 66941706,
"author": "Bimal Das",
"author_id": 4586387,
"author_profile": "https://Stackoverflow.com/users/4586387",
"pm_score": 1,
"selected": false,
"text": "None Compile .csproj <Compile Include=\"Logout.aspx.designer.cs\">\n <DependentUpon>Logout.aspx</DependentUpon>\n</Compile>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] |
45,340 |
<p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/" rel="noreferrer">http://somewhere.overtherainbow.com/userid/123424/</a></p>
<p>I want you to notice the ending path <strong>/userid/123424/</strong></p>
<p>How do you do this in ASP.NET?</p>
|
[
{
"answer_id": 406947,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 5,
"selected": false,
"text": "<system.web>\n<compilation debug=\"true\">\n <assemblies>\n …\n <add assembly=\"System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </assemblies>\n </compilation>\n…\n <httpModules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </httpModules>\n</system.web>\n<system.webServer>\n …\n <modules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </modules>\n <handlers\n… \n <add name=\"UrlRoutingHandler\" preCondition=\"integratedMode\" verb=\"*\" path=\"UrlRouting.axd\" type=\"System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </handlers>\n</system.webServer>\n void Application_Start(object sender, EventArgs e)\n{\n RegisterRoutes(RouteTable.Routes);\n}\n\npublic static void RegisterRoutes(RouteCollection routes)\n{\n routes.Add(\"UseridRoute\", new Route\n (\n \"userid/{userid}\",\n new CustomRouteHandler(\"~/users.aspx\")\n ));\n}\n using System.Web.Compilation;\nusing System.Web.UI;\nusing System.Web;\nusing System.Web.Routing;\n\npublic class CustomRouteHandler : IRouteHandler\n{\n public CustomRouteHandler(string virtualPath)\n {\n this.VirtualPath = virtualPath;\n }\n\n public string VirtualPath { get; private set; }\n\n public IHttpHandler GetHttpHandler(RequestContext\n requestContext)\n {\n // Add the querystring to the URL in the current context\n string queryString = \"?userid=\" + requestContext.RouteData.Values[\"userid\"];\n HttpContext.Current.RewritePath(\n string.Concat(\n VirtualPath,\n queryString)); \n\n var page = BuildManager.CreateInstanceFromVirtualPath\n (VirtualPath, typeof(Page)) as IHttpHandler;\n return page;\n }\n}\n protected void Page_Load(object sender, EventArgs e)\n{\n string id = Page.Request.QueryString[\"userid\"];\n switch (id)\n {\n case \"1234\":\n lblUserId.Text = id;\n lblUserName.Text = \"Bill\";\n break;\n case \"1235\":\n lblUserId.Text = id;\n lblUserName.Text = \"Claire\";\n break;\n case \"1236\":\n lblUserId.Text = id;\n lblUserName.Text = \"David\";\n break;\n default:\n lblUserId.Text = \"0000\";\n lblUserName.Text = \"Unknown\";\n break;\n}\n"
},
{
"answer_id": 407017,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 3,
"selected": false,
"text": "<system.web>\n<compilation debug=\"true\">\n <assemblies>\n …\n <add assembly=\"System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </assemblies>\n </compilation>\n…\n <httpModules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\" />\n </httpModules>\n</system.web>\n<system.webServer>\n …\n <modules>\n …\n <add name=\"UrlRoutingModule\" type=\"System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n </modules>\n <handlers\n… \n <add name=\"UrlRoutingHandler\" preCondition=\"integratedMode\" verb=\"*\" path=\"UrlRouting.axd\" type=\"System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"/>\n </handlers>\n</system.webServer>\n void Application_Start(object sender, EventArgs e)\n{\n RegisterRoutes(RouteTable.Routes);\n}\n\npublic static void RegisterRoutes(RouteCollection routes)\n{\n routes.Add(\"UseridRoute\", new Route\n (\n \"userid/{userid}\",\n new CustomRouteHandler(\"~/users.aspx\")\n ));\n}\n using System.Web.Compilation;\nusing System.Web.UI;\nusing System.Web;\nusing System.Web.Routing;\n\npublic interface IRoutablePage\n{\n RequestContext RequestContext { set; }\n}\n\npublic class CustomRouteHandler : IRouteHandler\n{\n public CustomRouteHandler(string virtualPath)\n {\n this.VirtualPath = virtualPath;\n }\n\n public string VirtualPath { get; private set; }\n\n public IHttpHandler GetHttpHandler(RequestContext\n requestContext)\n {\n var page = BuildManager.CreateInstanceFromVirtualPath\n (VirtualPath, typeof(Page)) as IHttpHandler;\n\n if (page != null)\n {\n var routablePage = page as IRoutablePage;\n\n if (routablePage != null) routablePage.RequestContext = requestContext;\n }\n\n return page;\n }\n}\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.WebControls;\nusing System.Web.Routing;\n\npublic partial class users : System.Web.UI.Page, IRoutablePage\n{\n protected RequestContext requestContext;\n\n protected object RouteValue(string key)\n {\n return requestContext.RouteData.Values[key];\n }\n\n protected void Page_Load(object sender, EventArgs e)\n {\n string id = RouteValue(\"userid\").ToString();\n switch (id)\n {\n case \"1234\":\n lblUserId.Text = id;\n lblUserName.Text = \"Bill\";\n break;\n case \"1235\":\n lblUserId.Text = id;\n lblUserName.Text = \"Claire\";\n break;\n case \"1236\":\n lblUserId.Text = id;\n lblUserName.Text = \"David\";\n break;\n default:\n lblUserId.Text = \"0000\";\n lblUserName.Text = \"Unknown\";\n break;\n }\n }\n\n #region IRoutablePage Members\n\n public RequestContext RequestContext\n {\n set { requestContext = value; }\n }\n\n #endregion\n}\n"
},
{
"answer_id": 413442,
"author": "Dominic Betts",
"author_id": 50911,
"author_profile": "https://Stackoverflow.com/users/50911",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\n\nnamespace MvcApplication1.Controllers\n{\n public class UsersController : Controller\n {\n public ActionResult Index()\n {\n return View(Models.UserDB.GetUsers());\n }\n public ActionResult userid(int id)\n {\n return View(Models.UserDB.GetUser(id));\n }\n }\n}\n <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Index.aspx.cs\" Inherits=\"MvcApplication1.Views.Index\" %>\n<%@ Import Namespace=\"MvcApplication1.Controllers\" %>\n<%@ Import Namespace=\"MvcApplication1.Models\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns=\"http://www.w3.org/1999/xhtml\" >\n<head runat=\"server\">\n <title></title>\n</head>\n<body>\n <div>\n <h2>Index of Users</h2>\n <ul>\n <% foreach (User user in (IEnumerable)ViewData.Model) { %>\n <li>\n <%= Html.ActionLink(user.name, \"userid\", new {id = user.id })%>\n </li>\n <% } %>\n </ul>\n </div>\n</body>\n</html>\n <%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"userid.aspx.cs\" Inherits=\"MvcApplication1.Views.Users.userid\" %>\n<%@ Import Namespace=\"MvcApplication1.Controllers\" %>\n<%@ Import Namespace=\"MvcApplication1.Models\" %>\n\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head runat=\"server\">\n <title></title>\n</head>\n<body>\n <div>\n <table border =\"1\">\n <tr>\n <td>\n ID\n </td>\n <td>\n <%=((User)ViewData.Model).id %>\n </td>\n </tr>\n <tr>\n <td>\n Name\n </td>\n <td>\n <%=((User)ViewData.Model).name %>\n </td>\n </tr>\n </table>\n </div>\n</body>\n</html>\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace MvcApplication1.Models\n{\n public class UserDB\n {\n private static List<User> users = new List<User>{\n new User(){id=12345, name=\"Bill\"},\n new User(){id=12346, name=\"Claire\"},\n new User(){id=12347, name=\"David\"}\n };\n\n public static List<User> GetUsers()\n {\n return users;\n }\n\n public static User GetUser(int id)\n {\n return users.First(user => user.id == id);\n }\n\n }\n\n public class User\n {\n public int id { get; set; }\n public string name { get; set; }\n }\n}\n"
},
{
"answer_id": 18045136,
"author": "Ata S.",
"author_id": 1216609,
"author_profile": "https://Stackoverflow.com/users/1216609",
"pm_score": 0,
"selected": false,
"text": "Install-Package LowercaseDashedRoute routes.Add(new LowercaseDashedRoute(\"{controller}/{action}/{id}\",\n new RouteValueDictionary(\n new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }),\n new DashedRouteHandler()\n )\n);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
45,372 |
<p>Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).</p>
<pre><code>CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
</code></pre>
<p>Is it possible to have the count column calculated for me whenever I do an insert?</p>
<p>e.g. do something like:</p>
<pre><code>INSERT INTO log (date='foo');
</code></pre>
<p>and have count calculated by mysql.</p>
<p>Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.</p>
|
[
{
"answer_id": 45382,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO log (date, count)\n SELECT DATE() as date, count(id) as count\n from foo;\n"
},
{
"answer_id": 61050,
"author": "Joe Mahoney",
"author_id": 575,
"author_profile": "https://Stackoverflow.com/users/575",
"pm_score": 4,
"selected": true,
"text": "create trigger log_date before insert on log \nfor each row begin\n set new.date = current_date()\nend;\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] |
45,399 |
<p>I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been <a href="http://en.wikipedia.org/wiki/Globally_Unique_Identifier" rel="noreferrer">GUID / UUID</a> values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs.</p>
<p>Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls?</p>
|
[
{
"answer_id": 71069249,
"author": "J Scott",
"author_id": 2932782,
"author_profile": "https://Stackoverflow.com/users/2932782",
"pm_score": 1,
"selected": false,
"text": "stackoverflow.com/questions/45399 portal.com/profile/{customerId} lastKnownCustomerCount + 1 404 - NotFound 403 - Forbidden"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
45,407 |
<p>What are the main differences (if any) between the box models of IE8 and Firefox3?</p>
<p>Are they the same now?</p>
<p>What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards?</p>
|
[
{
"answer_id": 45483,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 1,
"selected": false,
"text": "margin: 0 auto"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
45,408 |
<p>How does a virtual machine generate native machine code on the fly and execute it?</p>
<p>Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it?</p>
<p>Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?</p>
<p>Or would you generate a temporary shared library (.dll or .so or whatever) and load it into memory using standard functions like <code>LoadLibrary</code> ?</p>
|
[
{
"answer_id": 3160622,
"author": "Maruf Maniruzzaman",
"author_id": 381397,
"author_profile": "https://Stackoverflow.com/users/381397",
"pm_score": 1,
"selected": false,
"text": "void (*MyFunc)() = (void (*)()) VirtualAlloc(NULL, sizeofblock, MEM_COMMIT, PAGE_EXECUTE_READWRITE);\n\n//Now fill up the block with executable code and issue-\n\nMyFunc();\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618/"
] |
45,414 |
<p>I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the <em>Comments</em> tab enabled. The problem is that when I format a document comment that contains:</p>
<pre><code>* @see <a href="test.html">test</a>
</code></pre>
<p>the code formatter inserts a space in the closing HTML, breaking it:</p>
<pre><code>* @see <a href="test.html">test< /a>
</code></pre>
<p>Why? How do I stop this happening?</p>
<p>This is not fixed by disabling any of the options on the <em>Comments</em> tab, such as <em>Format HTML tags</em>. The only work-around I found is to disable Javadoc formatting completely by disabling both the <em>Enable Javadoc comment formatting</em> and <em>Enable block comment formatting</em> options, which means I then have to format comment blocks manually.</p>
|
[
{
"answer_id": 45574,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 1,
"selected": false,
"text": "<gcServer enabled=\"true\" /> <!-- note the space just after \"true\" -->\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] |
45,424 |
<p>I'm using <b>Struts 2</b>.</p>
<p>I'd like to return from an Action to the page which invoked it.</p>
<p>Say I'm in page <strong>x.jsp</strong>, I invoke Visual action to change CSS preferences in the session; I want to return to <strong>x.jsp</strong> rather than to a fixed page (i.e. <strong>home.jsp</strong>)<br/></p>
<p>Here's the relevant <strong>struts.xml</strong> fragment:
<br/></p>
<pre>
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="home">/pages/home.jsp</result>
</action>
</pre>
<p>Of course my <code>VisualizationAction.execute()</code> returns <strong>home</strong>.</p>
<p>Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?<br/></p>
<p>Must I use a more involved method (i.e. extracting the request page and forwarding to it)?<br/></p>
<p>T.I.A.</p>
|
[
{
"answer_id": 45595,
"author": "nikhilbelsare",
"author_id": 4705,
"author_profile": "https://Stackoverflow.com/users/4705",
"pm_score": 1,
"selected": false,
"text": "return INPUT;\n"
},
{
"answer_id": 202693,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": true,
"text": "<action\n name=\"Visual\"\n class=\"it.___.web.actions.VisualizationAction\">\n <result name=\"next\">${next}</result>\n</action>\n"
},
{
"answer_id": 447845,
"author": "pierdeux",
"author_id": 53747,
"author_profile": "https://Stackoverflow.com/users/53747",
"pm_score": 1,
"selected": false,
"text": "public interface TargetAware {\n public String getTarget();\n public void setTarget(String target);\n}\n public class SetTargetInterceptor extends MethodFilterInterceptor implements Interceptor {\n public String doIntercept(ActionInvocation invocation) {\n Object action = invocation.getAction();\n HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);\n if (action instanceof TargetAware) {\n TargetAware targetAwareAction = (TargetAware) action;\n if (targetAwareAction.getTarget() == null)\n targetAwareAction.setTarget(getCurrentUri(request));\n } \n return invocation.invoke();\n }\n\n // I'm sure we can find a better implementation of this...\n private static String getCurrentUri(HttpServletRequest request) {\n String uri = request.getRequestURI();\n String queryString = request.getQueryString();\n if (queryString != null && !queryString.equals(\"\"))\n uri += \"?\" + queryString;\n return uri;\n }\n\n public void init() { /* do nothing */ }\n public void destroy() { /* do nothing */ }\n}\n TargetAware target VisualizationAction TargetAware SUCCESS <action name=\"Visual\" class=\"it.___.web.actions.VisualizationAction\">\n <result type=\"redirect\">\n <param name=\"location\">${target}</param>\n <param name=\"parse\">true</param>\n </result>\n</action>\n redirect"
},
{
"answer_id": 447914,
"author": "JuanDeLosMuertos",
"author_id": 39339,
"author_profile": "https://Stackoverflow.com/users/39339",
"pm_score": 0,
"selected": false,
"text": "<action name=\"Visual\" class=\"it.___.web.actions.VisualizationAction\">\n <result name=\"input\">yourJspPage.jsp</result>\n</action>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] |
45,437 |
<p>I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups?</p>
|
[
{
"answer_id": 45458,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 2,
"selected": false,
"text": "public ArrayList Groups(string userDn, bool recursive)\n{\n ArrayList groupMemberships = new ArrayList();\n return AttributeValuesMultiString(\"memberOf\", userDn,\n groupMemberships, recursive);\n}\n public ArrayList AttributeValuesMultiString(string attributeName,\n string objectDn, ArrayList valuesCollection, bool recursive)\n{\n DirectoryEntry ent = new DirectoryEntry(objectDn);\n PropertyValueCollection ValueCollection = ent.Properties[attributeName];\n IEnumerator en = ValueCollection.GetEnumerator();\n\n while (en.MoveNext())\n {\n if (en.Current != null)\n {\n if (!valuesCollection.Contains(en.Current.ToString()))\n {\n valuesCollection.Add(en.Current.ToString());\n if (recursive)\n {\n AttributeValuesMultiString(attributeName, \"LDAP://\" +\n en.Current.ToString(), valuesCollection, true);\n }\n }\n }\n }\n ent.Close();\n ent.Dispose();\n return valuesCollection;\n}\n"
},
{
"answer_id": 45521,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 2,
"selected": false,
"text": "public static bool IsUserInGroup(string username, string groupname, ContextType type)\n{\n PrincipalContext context = new PrincipalContext(type);\n\n UserPrincipal user = UserPrincipal.FindByIdentity(\n context,\n IdentityType.SamAccountName,\n username);\n GroupPrincipal group = GroupPrincipal.FindByIdentity(\n context, groupname);\n\n return user.IsMemberOf(group);\n}\n"
},
{
"answer_id": 323056,
"author": "Jon DellOro",
"author_id": 36456,
"author_profile": "https://Stackoverflow.com/users/36456",
"pm_score": 0,
"selected": false,
"text": "private int validateUserActiveDirectory()\n{\n IntPtr token = IntPtr.Zero;\n int DBgroupLevel = 0;\n\n // make sure you're yourself -- recommended at msdn http://support.microsoft.com/kb/248187\n RevertToSelf();\n\n if (LogonUser(txtUserName.Value, propDomain, txtUserPass.Text, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, token) != 0) {\n // ImpersonateLoggedOnUser not required for us -- we are not doing impersonated stuff, but leave it here for completeness.\n //ImpersonateLoggedOnUser(token);\n // do impersonated stuff\n // end impersonated stuff\n\n // ensure that we are the original user\n CloseHandle(token);\n RevertToSelf();\n\n System.Security.Principal.IdentityReferenceCollection groups = Context.Request.LogonUserIdentity.Groups;\n IdentityReference translatedGroup = default(IdentityReference);\n\n foreach (IdentityReference g in groups) {\n translatedGroup = g.Translate(typeof(NTAccount));\n if (translatedGroup.Value.ToLower().Contains(\"desired group\")) {\n inDBGroup = true;\n return 1;\n }\n }\n }\n else {\n return 0;\n }\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] |
45,453 |
<p>I'm generating ICalendar (.ics) files.</p>
<p>Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar <strong><em>BUT NOT</em></strong> in MS Outlook 2007 - it just creates a second event</p>
<p>How do I get them to work for Outlook ?</p>
<p>Thanks</p>
<p>Tom</p>
|
[
{
"answer_id": 45703,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "VERSION PRODID STATUS SEQUENCE VERSION"
},
{
"answer_id": 45969,
"author": "Tom Carter",
"author_id": 2839,
"author_profile": "https://Stackoverflow.com/users/2839",
"pm_score": 6,
"selected": true,
"text": "METHOD:REQUEST ORGANIZER:xxxxxxxx UID SEQUENCE: METHOD:CANCEL BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//SYFADIS//PORTAIL FORMATION//FR\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:[email protected]\nSEQUENCE:5\nDTSTAMP:20081106T154911Z\nORGANIZER:[email protected]\nDTSTART:20081113T164907\nDTEND:20081115T170000\nSUMMARY:TestTraining\nSTATUS:CONFIRMED\nEND:VEVENT\nEND:VCALENDAR\n BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//SYFADIS//PORTAIL FORMATION//FR\nMETHOD:CANCEL\nBEGIN:VEVENT\nUID:[email protected]\nSEQUENCE:7\nDTSTAMP:20081106T154916Z\nORGANIZER:[email protected]\nDTSTART:20081113T164907\nSUMMARY:TestTraining\nSTATUS:CANCELLED\nEND:VEVENT\nEND:VCALENDAR\n"
},
{
"answer_id": 280065,
"author": "Chris",
"author_id": 13700,
"author_profile": "https://Stackoverflow.com/users/13700",
"pm_score": 3,
"selected": false,
"text": "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//WA//FRWEB//EN\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:FRICAL201\nSEQUENCE:0\nDTSTAMP:20081108T151809Z\nORGANIZER:[email protected]\nDTSTART:20081109T121200\nSUMMARY:11/9/2008 12:12:00 PM TRIP FROM JFK AIRPORT (JFK)\nLOCATION:JFK AIRPORT (JFK)\nEND:VEVENT\nEND:VCALENDAR\n BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//WA//FRWEB//EN\nMETHOD:REQUEST\nBEGIN:VEVENT\nUID:FRICAL201\nSEQUENCE:1\nDTSTAMP:20081108T161809Z\nORGANIZER:[email protected]\nDTSTART:20081109T121300\nSUMMARY:11/9/2008 12:13:00 PM TRIP FROM JFK AIRPORT (JFK)\nLOCATION:JFK AIRPORT (JFK)\nEND:VEVENT\nEND:VCALENDAR\n"
},
{
"answer_id": 472636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:www.membership-services.net\nMETHOD:REQUEST\nBEGIN:VEVENT\nDTSTART:20090126T210000\nDTEND:20090126T220000\nSUMMARY:Avondale - Thameside Away Game vs Croydon\nLOCATION:Whitgift School\nDESCRIPTION:http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=CR2+6YT \nUID:AWPC_8\nSEQUENCE:0\nDTSTAMP:20090123T112600\nEND:VEVENT\nBEGIN:VEVENT\nDTSTART:20090202T213000\nDTEND:20090202T223000\nSUMMARY:Avondale - Thameside Home Game vs Orcas\nLOCATION:Putney\nDESCRIPTION:http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&ie=UTF8&ll=51.4635,-0.2285&spn=0.005,0.009613&t=h&z=17&iwloc=lyrftr:w2t.90,0x48760f04a04b1801:0x49ebf12503a5d5a9,51.463459,-0.228674 \nUID:AWPC_10\nSEQUENCE:0\nDTSTAMP:20090123T112600\nEND:VEVENT\nEND:VCALENDAR\n"
},
{
"answer_id": 37956276,
"author": "Mark Plumpton",
"author_id": 10422,
"author_profile": "https://Stackoverflow.com/users/10422",
"pm_score": 2,
"selected": false,
"text": "X-WR-RELCALID:MyCal123 \n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839/"
] |
45,470 |
<p>Can you suggest some good MVC framework for perl -- one I am aware of is <a href="http://www.catalystframework.org/" rel="noreferrer">catalyst</a></p>
<p>The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.</p>
|
[
{
"answer_id": 70871,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "uri_for"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
45,475 |
<p>I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.</p>
<p>Clicking my links <em>DOES</em> cause a post-back but they don't seem to generate any <em>OnClick</em> events as my <em>OnClick</em> functions don't get executed. I have <code>AutoEventWireup</code> set to true and if I move the links out of the GridView they work fine.</p>
<p>I've got around the problem by creating regular anchors, appending queries to their <strong>hrefs</strong> and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?</p>
<p><strong>Update:</strong> To clarify the IDs of the controls match their <em>OnClick</em> function names.</p>
|
[
{
"answer_id": 45513,
"author": "NakedBrunch",
"author_id": 3742,
"author_profile": "https://Stackoverflow.com/users/3742",
"pm_score": 2,
"selected": false,
"text": "<HeaderTemplate> \n <asp:LinkButton ID=\"LinkButton1\" runat=\"server\" CommandName=\"sort\" CommandArgument=\"Products\" Text=\"<%# Bind('ProductName\")' />\n</HeaderTemplate>\n protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n{\n if (e.CommandName == \"sort\")\n {\n //Now sort by e.CommandArgument\n\n }\n}\n"
},
{
"answer_id": 45599,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 0,
"selected": false,
"text": "<HeaderTemplate>\n <asp:LinkButton\n ID=\"lnkHdr1\"\n Text=\"Hdr1\"\n OnCommand=\"lnkHdr1_OnCommand\"\n CommandArgument=\"Hdr1\"\n runat=\"server\"></asp:LinkButton>\n</HeaderTemplate>\n protected void lnkHdr1_OnCommand(object sender, CommandEventArgs e)\n{\n // e.CommandArgument\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4431/"
] |
45,481 |
<p>How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?</p>
|
[
{
"answer_id": 45493,
"author": "Hirvox",
"author_id": 4674,
"author_profile": "https://Stackoverflow.com/users/4674",
"pm_score": 4,
"selected": true,
"text": "void ParseURL(string strUrl)\n{\n try\n {\n using (var reader = XmlReader.Create(strUrl))\n {\n while (reader.Read())\n {\n switch (reader.NodeType)\n {\n case XmlNodeType.Element:\n var attributes = new Hashtable();\n var strURI = reader.NamespaceURI;\n var strName = reader.Name;\n if (reader.HasAttributes)\n {\n for (int i = 0; i < reader.AttributeCount; i++)\n {\n reader.MoveToAttribute(i);\n attributes.Add(reader.Name,reader.Value);\n }\n }\n StartElement(strURI,strName,strName,attributes);\n break;\n //\n //you can handle other cases here\n //\n //case XmlNodeType.EndElement:\n // Todo\n //case XmlNodeType.Text:\n // Todo\n default:\n break;\n }\n }\n }\n catch (XmlException e)\n {\n Console.WriteLine(\"error occured: \" + e.Message);\n }\n }\n }\n}\n"
},
{
"answer_id": 501922,
"author": "danny",
"author_id": 61324,
"author_profile": "https://Stackoverflow.com/users/61324",
"pm_score": 3,
"selected": false,
"text": "new Create using (var reader = new XmlReader.Create(strUrl))\n using (var reader = XmlReader.Create(strUrl))\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] |
45,485 |
<p>Are there conventions for function names when using the Perl Test::More or Test::Simple modules?</p>
<p>I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s).</p>
<p>cheers,</p>
<p>Rob</p>
|
[
{
"answer_id": 45542,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 3,
"selected": true,
"text": "BEGIN {\n # If you want to set some global db setting/file setting/INC changes etc\n}\n\n# Tests functionality 1...\n{\n # have fun .... \n}\n\n# Tests functionality 2...\n{\n # have more fun .... \n}\n\nEND {\n # Clean up the BEGIN changes\n}\n"
},
{
"answer_id": 70912,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "Test(setup) Test(teardown)"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
] |
45,494 |
<p>I have a table <code>story_category</code> in my database with corrupt entries. The next query returns the corrupt entries:</p>
<pre><code>SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
</code></pre>
<p>I tried to delete them executing:</p>
<pre><code>DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category
INNER JOIN story_category ON category_id=category.id);
</code></pre>
<p>But I get the next error: </p>
<blockquote>
<p>#1093 - You can't specify target table 'story_category' for update in FROM clause </p>
</blockquote>
<p>How can I overcome this?</p>
|
[
{
"answer_id": 45498,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 11,
"selected": true,
"text": "UPDATE tbl AS a\nINNER JOIN tbl AS b ON ....\nSET a.col = b.col\n UPDATE tbl SET col = (\n SELECT ... FROM (SELECT.... FROM) AS x);\n optimizer_switch SET optimizer_switch = 'derived_merge=off';\n"
},
{
"answer_id": 694011,
"author": "Tom Schaefer",
"author_id": 84136,
"author_profile": "https://Stackoverflow.com/users/84136",
"pm_score": 1,
"selected": false,
"text": "drop table if exists apples;\ncreate table if not exists apples(variety char(10) primary key, price int);\n\ninsert into apples values('fuji', 5), ('gala', 6);\n\ndrop table if exists apples_new;\ncreate table if not exists apples_new like apples;\ninsert into apples_new select * from apples;\n\nupdate apples_new\n set price = (select price from apples where variety = 'gala')\n where variety = 'fuji';\nrename table apples to apples_orig;\nrename table apples_new to apples;\ndrop table apples_orig;\n"
},
{
"answer_id": 947417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "inner join story_category category_id category DELETE FROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN\n story_category ON category_id=category.id);\n DELETE FROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category);\n"
},
{
"answer_id": 3624656,
"author": "sactiw",
"author_id": 416369,
"author_profile": "https://Stackoverflow.com/users/416369",
"pm_score": 4,
"selected": false,
"text": "\nUPDATE My_Table\nSET Priority=Priority + 1\nWHERE Priority >= 1\nAND (SELECT TRUE FROM (SELECT * FROM My_Table WHERE Priority=1 LIMIT 1) as t);\n"
},
{
"answer_id": 8620162,
"author": "NexusRex",
"author_id": 445500,
"author_profile": "https://Stackoverflow.com/users/445500",
"pm_score": 5,
"selected": false,
"text": "DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT cid FROM (\n SELECT DISTINCT category.id AS cid FROM category INNER JOIN story_category ON category_id=category.id\n ) AS c\n)\n"
},
{
"answer_id": 9843719,
"author": "Yehor",
"author_id": 1101589,
"author_profile": "https://Stackoverflow.com/users/1101589",
"pm_score": 9,
"selected": false,
"text": "DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT DISTINCT category.id AS cid FROM category \n INNER JOIN story_category ON category_id=category.id\n)\n DELETE FROM story_category\nWHERE category_id NOT IN (\n SELECT cid FROM (\n SELECT DISTINCT category.id AS cid FROM category \n INNER JOIN story_category ON category_id=category.id\n ) AS c\n)\n"
},
{
"answer_id": 12737534,
"author": "Pratik Khadloya",
"author_id": 238880,
"author_profile": "https://Stackoverflow.com/users/238880",
"pm_score": 7,
"selected": false,
"text": "UPDATE skills AS s, (SELECT id FROM skills WHERE type = 'Programming') AS p\nSET s.type = 'Development' \nWHERE s.id = p.id;\n"
},
{
"answer_id": 43610081,
"author": "Sequoya",
"author_id": 4389068,
"author_profile": "https://Stackoverflow.com/users/4389068",
"pm_score": 7,
"selected": false,
"text": "UPDATE table SET a=value WHERE x IN\n (SELECT x FROM table WHERE condition);\n UPDATE table SET a=value WHERE x IN\n (SELECT * FROM (SELECT x FROM table WHERE condition) as t)\n"
},
{
"answer_id": 43905253,
"author": "Melvin Angelo Jabonillo",
"author_id": 7990568,
"author_profile": "https://Stackoverflow.com/users/7990568",
"pm_score": 1,
"selected": false,
"text": "DELETE FROM story_category LEFT JOIN (SELECT category.id FROM category) cat ON story_category.id = cat.id WHERE cat.id IS NULL\n"
},
{
"answer_id": 48198876,
"author": "S.Roshanth",
"author_id": 2783908,
"author_profile": "https://Stackoverflow.com/users/2783908",
"pm_score": 3,
"selected": false,
"text": "insert into xxx_tab (trans_id) values ((select max(trans_id)+1 from xxx_tab));\n insert into xxx_tab (trans_id) values ((select max(P.trans_id)+1 from xxx_tab P));\n"
},
{
"answer_id": 48392742,
"author": "Sameer Khanal",
"author_id": 5836015,
"author_profile": "https://Stackoverflow.com/users/5836015",
"pm_score": 2,
"selected": false,
"text": "DELETE FROM story_category \nWHERE category_id NOT IN (\nSELECT DISTINCT category.id \nFROM (SELECT * FROM STORY_CATEGORY) sc;\n"
},
{
"answer_id": 56978014,
"author": "Doin",
"author_id": 999120,
"author_profile": "https://Stackoverflow.com/users/999120",
"pm_score": 4,
"selected": false,
"text": "LEFT JOIN SELECT s.* \nFROM story_category s \nLEFT JOIN category c \nON c.id=s.category_id \nWHERE c.id IS NULL;\n DELETE s story_category DELETE s \nFROM story_category s \nLEFT JOIN category c \nON c.id=s.category_id \nWHERE c.id IS NULL;\n"
},
{
"answer_id": 61138675,
"author": "GMB",
"author_id": 10676716,
"author_profile": "https://Stackoverflow.com/users/10676716",
"pm_score": 1,
"selected": false,
"text": "story_category category SELECT * \nFROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN \n story_category ON category_id=category.id\n);\n NOT IN JOIN not exists select sc.*\nfrom story_category sc\nwhere not exists (select 1 from category c where c.id = sc.category_id);\n delete delete from story_category\nwhere not exists (select 1 from category c where c.id = story_category.category_id); \n -- set-up\ncreate table story_category(category_id int);\ncreate table category (id int);\ninsert into story_category values (1), (2), (3), (4), (5);\ninsert into category values (4), (5), (6), (7);\n\n-- your original query to identify offending rows\nSELECT * \nFROM story_category \nWHERE category_id NOT IN (\n SELECT DISTINCT category.id \n FROM category INNER JOIN \n story_category ON category_id=category.id);\n -- a functionally-equivalent, simpler query for this\nselect sc.*\nfrom story_category sc\nwhere not exists (select 1 from category c where c.id = sc.category_id)\n -- the delete query\ndelete from story_category\nwhere not exists (select 1 from category c where c.id = story_category.category_id);\n\n-- outcome\nselect * from story_category;\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
45,507 |
<p>I'm looking to create <code>favicon.ico</code> files programatically from Python, but PIL only has support for reading <code>ico</code> files.</p>
|
[
{
"answer_id": 36168447,
"author": "Ronan Paixão",
"author_id": 3754432,
"author_profile": "https://Stackoverflow.com/users/3754432",
"pm_score": 6,
"selected": false,
"text": "from PIL import Image\nfilename = r'logo.png'\nimg = Image.open(filename)\nimg.save('logo.ico')\n icon_sizes = [(16,16), (32, 32), (48, 48), (64,64)]\nimg.save('logo.ico', sizes=icon_sizes)\n [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]"
},
{
"answer_id": 52333963,
"author": "Overdrivr",
"author_id": 4218017,
"author_profile": "https://Stackoverflow.com/users/4218017",
"pm_score": 2,
"selected": false,
"text": "import imageio\n\nimg = imageio.imread('logo.png')\nimageio.imwrite('logo.ico', img)\n pip install imageio\n"
},
{
"answer_id": 58770704,
"author": "Jan",
"author_id": 6590884,
"author_profile": "https://Stackoverflow.com/users/6590884",
"pm_score": 3,
"selected": false,
"text": "from pathlib import Path\nfrom PIL import Image\n\n\ndef bake_one_big_png_to_ico(sourcefile, targetfile, sizes=None):\n \"\"\"Converts one big PNG into one ICO file.\n\n args:\n sourcefile (str): Pathname of a PNG file.\n targetfile (str): Pathname of the resulting ICO file.\n sizes (list of int): Requested sizes of the resulting\n icon file, defaults to [16, 32, 48].\n\n Use this function if you have one big, square PNG file\n and don’t care about fine-tuning individual icon sizes.\n\n Example::\n\n sourcefile = \"Path/to/high_resolution_logo_512x512.png\"\n targetfile = \"Path/to/logo.ico\"\n sizes = [16, 24, 32, 48, 256]\n bake_one_big_png_to_ico(sourcefile, targetfile, sizes)\n \"\"\"\n if sizes is None:\n sizes = [16, 32, 48]\n icon_sizes = [(x, x) for x in sizes]\n Image.open(sourcefile).save(targetfile, icon_sizes=icon_sizes)\n\n\ndef bake_several_pngs_to_ico(sourcefiles, targetfile):\n \"\"\"Converts several PNG files into one ICO file.\n\n args:\n sourcefiles (list of str): A list of pathnames of PNG files.\n targetfile (str): Pathname of the resulting ICO file.\n\n Use this function if you want to have fine-grained control over\n the resulting icon file, providing each possible icon resolution\n individually.\n\n Example::\n\n sourcefiles = [\n \"Path/to/logo_16x16.png\",\n \"Path/to/logo_32x32.png\",\n \"Path/to/logo_48x48.png\"\n ]\n targetfile = \"Path/to/logo.ico\"\n bake_several_pngs_to_ico(sourcefiles, targetfile)\n \"\"\"\n\n # Write the global header\n number_of_sources = len(sourcefiles)\n data = bytes((0, 0, 1, 0, number_of_sources, 0))\n offset = 6 + number_of_sources * 16\n\n # Write the header entries for each individual image\n for sourcefile in sourcefiles:\n img = Image.open(sourcefile)\n data += bytes((img.width, img.height, 0, 0, 1, 0, 32, 0, ))\n bytesize = Path(sourcefile).stat().st_size\n data += bytesize.to_bytes(4, byteorder=\"little\")\n data += offset.to_bytes(4, byteorder=\"little\")\n offset += bytesize\n\n # Write the individual image data\n for sourcefile in sourcefiles:\n data += Path(sourcefile).read_bytes()\n\n # Save the icon file\n Path(targetfile).write_bytes(data)\n"
},
{
"answer_id": 62374154,
"author": "Mike R",
"author_id": 1621381,
"author_profile": "https://Stackoverflow.com/users/1621381",
"pm_score": 1,
"selected": false,
"text": "from PIL import Image\nicon_sizes = [(16, 16), (24, 24), (32, 32), (48, 48), (64, 64), (128, 128), (255, 255)]\nimage = Image.open('/some/path/to/logo-python/logo.png')\nfileoutpath = '/some/path/to/logo-python/'\nfor size in icon_sizes:\n print(size[0])\n fileoutname = fileoutpath + str(size[0]) + \".png\"\n new_image = image.resize(size)\n new_image.save(fileoutname)\n\nnew_logo_ico_filename = fileoutpath + \"Icon.ico\"\nnew_logo_ico = image.resize((128, 128))\nnew_logo_ico.save(new_logo_ico_filename, format=\"ICO\",quality=90)\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4203/"
] |
45,510 |
<p>I want to call a function from a .NET DLL (coded in C#) from an Inno Setup script.</p>
<p>I have:</p>
<ol>
<li>marked the <em>Register for COM interop</em> option in the project properties,</li>
<li>changed the <em>ComVisible</em> setting in the <em>AssemblyInfo.cs</em> file,</li>
<li>added these lines to the ISS script:</li>
</ol>
<blockquote>
<p>[Files]</p>
<p>Source: c:\temp\1\MyDLL.dll; Flags: dontcopy</p>
<p>[Code]</p>
<p>function MyFunction(): string;</p>
<p>external 'MyFunction@files:MyDLL.dll stdcall setuponly';</p>
</blockquote>
<p>but I still get the following error:</p>
<blockquote>
<p>Runtime Error (at -1:0):</p>
<p>Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll.</p>
</blockquote>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 45590,
"author": "Marek Grzenkowicz",
"author_id": 95,
"author_profile": "https://Stackoverflow.com/users/95",
"pm_score": 2,
"selected": false,
"text": "[Code]\nprocedure MyFunction();\nvar\n oleObject: Variant;\nbegin\n oleObject := CreateOleObject('MyDLL.MyDLL');\n\n MsgBox(oleObject.MyFunction, mbInformation, mb_Ok);\nend;\n"
},
{
"answer_id": 1705317,
"author": "Miguel Vivanco",
"author_id": 207459,
"author_profile": "https://Stackoverflow.com/users/207459",
"pm_score": 3,
"selected": false,
"text": "Var\n obj: Variant\n va: MyVariableType;\nBegin\n //Starting\n ExtractTemporaryFile('MyDll.dll');\n RegisterServer(False, ExpandConstant('{tmp}\\MyDll.dll'), False);\n obj := CreateOleObject('MyDll.MyClass');\n //Using\n va := obj.MyFunction();\n //Finishing\n UnregisterServer(False, ExpandConstant('{tmp}\\MyDll.dll'), False);\n DeleteFile('{tmp}\\MyDll.dll');\nEnd;\n"
},
{
"answer_id": 3417533,
"author": "Moissane",
"author_id": 412236,
"author_profile": "https://Stackoverflow.com/users/412236",
"pm_score": 0,
"selected": false,
"text": "[Files]\nSource: odbccp32.dll; Flags: dontcopy\n\n[Code]\nprocedure SQLConfigDataSource(hwndParent: Integer; Frequest: Integer; LpszDriver: String; lpszAttributes: String);\nexternal 'SQLConfigDataSource@files:odbccp32.dll stdcall delayload';\n"
},
{
"answer_id": 43316676,
"author": "Martin Prikryl",
"author_id": 850848,
"author_profile": "https://Stackoverflow.com/users/850848",
"pm_score": 2,
"selected": false,
"text": "DllExport using RGiesecke.DllExport;\nusing System.Runtime.InteropServices;\nusing System.Text.RegularExpressions;\n\nnamespace MyNetDll\n{\n public class MyFunctions\n {\n [DllExport(CallingConvention = CallingConvention.StdCall)]\n public static bool RegexMatch(\n [MarshalAs(UnmanagedType.LPWStr)]string pattern,\n [MarshalAs(UnmanagedType.LPWStr)]string input)\n {\n return Regex.Match(input, pattern).Success;\n }\n }\n}\n [Files]\nSource: \"MyNetDll.dll\"; Flags: dontcopy\n\n[Code]\nfunction RegexMatch(Pattern: string; Input: string): Boolean;\n external 'RegexMatch@files:MyNetDll.dll stdcall';\n if RegexMatch('[0-9]+', '123456789') then\nbegin\n Log('Matched');\nend\n else\nbegin\n Log('Not matched');\nend;\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95/"
] |
45,528 |
<p>I'm trying to find a simple way to change the colour of the text and background in <code>listview</code> and <code>treeview</code> controls in WTL or plain Win32 code.</p>
<p>I really don't want to have to implement full owner drawing for these controls, simply change the colours used.</p>
<p>I want to make sure that the images are still drawn with proper transparency.</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 49257,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 2,
"selected": false,
"text": "CListViewCtrl CTreeViewCtrl"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4591/"
] |
45,535 |
<p>I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?</p>
|
[
{
"answer_id": 45543,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "select convert(varchar(4),getdate(),100) + convert(varchar(4),year(getdate()))\n"
},
{
"answer_id": 45548,
"author": "robsoft",
"author_id": 3897,
"author_profile": "https://Stackoverflow.com/users/3897",
"pm_score": 7,
"selected": true,
"text": "SELECT \n CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) \nFROM customers\n"
},
{
"answer_id": 45603,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 7,
"selected": false,
"text": "select \ndatepart(month,getdate()) -- integer (1,2,3...)\n,datepart(year,getdate()) -- integer\n,datename(month,getdate()) -- string ('September',...)\n"
},
{
"answer_id": 446383,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "( Month(Created) + ',' + Year(Created) ) AS Date\n"
},
{
"answer_id": 446406,
"author": "Mike Geise",
"author_id": 43380,
"author_profile": "https://Stackoverflow.com/users/43380",
"pm_score": 4,
"selected": false,
"text": "SELECT \n DATENAME(mm, article.Created) AS Month, \n DATENAME(yyyy, article.Created) AS Year, \n COUNT(*) AS Total \nFROM Articles AS article \nGROUP BY \n DATENAME(mm, article.Created), \n DATENAME(yyyy, article.Created) \nORDER BY Month, Year DESC\n Month | Year | Total\n\nJanuary | 2009 | 2\n"
},
{
"answer_id": 842693,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "SELECT DATENAME(yyyy, date) AS year\nFROM Income\nGROUP BY DATENAME(yyyy, date)\n"
},
{
"answer_id": 861594,
"author": "GordyII",
"author_id": 68654,
"author_profile": "https://Stackoverflow.com/users/68654",
"pm_score": 3,
"selected": false,
"text": "Select DateName( Month, getDate() ) + ' ' + DateName( Year, getDate() )\n"
},
{
"answer_id": 2107799,
"author": "Alok Kumar",
"author_id": 255495,
"author_profile": "https://Stackoverflow.com/users/255495",
"pm_score": 0,
"selected": false,
"text": "datename(month,intime)"
},
{
"answer_id": 4244079,
"author": "don",
"author_id": 515873,
"author_profile": "https://Stackoverflow.com/users/515873",
"pm_score": 4,
"selected": false,
"text": "select datepart(mm,getdate()) --to get month value\nselect datename(mm,getdate()) --to get name of month\n"
},
{
"answer_id": 5389842,
"author": "Matteo",
"author_id": 671015,
"author_profile": "https://Stackoverflow.com/users/671015",
"pm_score": -1,
"selected": false,
"text": "date_format(date,'%Y-%c')\n"
},
{
"answer_id": 15957013,
"author": "Ron Smith",
"author_id": 2271803,
"author_profile": "https://Stackoverflow.com/users/2271803",
"pm_score": 1,
"selected": false,
"text": "declare @mytable table(mydate datetime)\ndeclare @date datetime\nset @date = '19000101'\nwhile @date < getdate() begin\n insert into @mytable values(@date)\n set @date = dateadd(day,1,@date)\nend\n\nselect count(*) total_records from @mytable\n\nselect dateadd(month,datediff(month,0,mydate),0) first_of_the_month, count(*) cnt\nfrom @mytable\ngroup by dateadd(month,datediff(month,0,mydate),0)\n"
},
{
"answer_id": 19244174,
"author": "Lalmuni Singh",
"author_id": 2857980,
"author_profile": "https://Stackoverflow.com/users/2857980",
"pm_score": 1,
"selected": false,
"text": "---Lalmuni Demos---\ncreate table Users\n(\nuserid int,date_of_birth date\n)\n---insert values---\ninsert into Users values(4,'9/10/1991')\n\nselect DATEDIFF(year,date_of_birth, getdate()) - (CASE WHEN (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()),date_of_birth)) > getdate() THEN 1 ELSE 0 END) as Years, \nMONTH(getdate() - (DATEADD(year, DATEDIFF(year, date_of_birth, getdate()), date_of_birth))) - 1 as Months, \nDAY(getdate() - (DATEADD(year, DATEDIFF(year,date_of_birth, getdate()), date_of_birth))) - 1 as Days,\nfrom users\n"
},
{
"answer_id": 19438293,
"author": "Gareth Thomas",
"author_id": 1941758,
"author_profile": "https://Stackoverflow.com/users/1941758",
"pm_score": 2,
"selected": false,
"text": "cast(cast(sq.QuotaDate as date) as varchar(7))\n"
},
{
"answer_id": 23981171,
"author": "cyber cyber1621",
"author_id": 1031692,
"author_profile": "https://Stackoverflow.com/users/1031692",
"pm_score": 3,
"selected": false,
"text": "dateadd(month,datediff(month,0,*your_date*),0)\n"
},
{
"answer_id": 27105774,
"author": "CrimsonKing",
"author_id": 4287441,
"author_profile": "https://Stackoverflow.com/users/4287441",
"pm_score": 6,
"selected": false,
"text": "SELECT FORMAT(@date, 'yyyyMM')\n"
},
{
"answer_id": 29506934,
"author": "Hammad Khan",
"author_id": 777982,
"author_profile": "https://Stackoverflow.com/users/777982",
"pm_score": 2,
"selected": false,
"text": "select convert (varchar(7), getdate(),20)\n--Typical output 2015-04\n"
},
{
"answer_id": 33643495,
"author": "khmer angkor",
"author_id": 5549082,
"author_profile": "https://Stackoverflow.com/users/5549082",
"pm_score": 0,
"selected": false,
"text": " ,datename(month,(od.SHIP_DATE)) as MONTH_\n"
},
{
"answer_id": 42681098,
"author": "RobertC",
"author_id": 1678020,
"author_profile": "https://Stackoverflow.com/users/1678020",
"pm_score": 2,
"selected": false,
"text": "March-2017 CONCAT(DATENAME(mm, GetDate()), '-', DATEPART(yy, GetDate()))\n"
},
{
"answer_id": 44340913,
"author": "GanbatSu",
"author_id": 8106226,
"author_profile": "https://Stackoverflow.com/users/8106226",
"pm_score": 0,
"selected": false,
"text": "DECLARE @pYear VARCHAR(4)\n\nDECLARE @pMonth VARCHAR(2)\n\nDECLARE @pDay VARCHAR(2)\n\nSET @pYear = RIGHT(CONVERT(CHAR(10), GETDATE(), 101), 4)\n\nSET @pMonth = LEFT(CONVERT(CHAR(10), GETDATE(), 101), 2)\n\nSET @pDay = SUBSTRING(CONVERT(CHAR(10), GETDATE(), 101), 4,2)\n\nSELECT @pYear,@pMonth,@pDay\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] |
45,540 |
<p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p>
<pre><code>from Tkinter import *
import tkMessageBox
root = Tk()
root.withdraw()
# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
</code></pre>
<p>Any idea how to check that?</p>
|
[
{
"answer_id": 46205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if 'normal' != root.state():\n tkMessageBox.showinfo(\"Key you!\", \" \".join(sys.argv[1:]))\n"
},
{
"answer_id": 47374939,
"author": "Billal Begueradj",
"author_id": 3329664,
"author_profile": "https://Stackoverflow.com/users/3329664",
"pm_score": 0,
"selected": false,
"text": "root.mainloop() import tkinter as tk\nfrom tkinter import messagebox\nimport sys\n\n\nroot = tk.Tk()\nroot.withdraw()\n\nif 'withdrawn' != root.state():\n messagebox.showinfo(\"Key you!\", sys.argv[1:])\n\n\nroot.mainloop()\n root.state(\"normal\") root.iconify()"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4717/"
] |
45,545 |
<p>How can I add horizontal scroll capabilities to the asp.net listbox control?</p>
|
[
{
"answer_id": 45549,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<div style=\"width:200px; height:100px; overflow:auto;\">\n<SELECT size=\"4\">\n<OPTION\nValue=\"1\">blahblahblahblahblahblahblahblahblahblah blahblah</OPTION>\n<OPTION Value=\"2\">2</OPTION>\n<OPTION Value=\"3\">3</OPTION>\n<OPTION Value=\"4\">4</OPTION>\n</SELECT>\n</div>\n"
},
{
"answer_id": 45554,
"author": "Codeslayer",
"author_id": 4021,
"author_profile": "https://Stackoverflow.com/users/4021",
"pm_score": 1,
"selected": false,
"text": "<div id='hello' style=\"Z-INDEX: 102; LEFT: 13px; OVERFLOW: \n auto; WIDTH: 247px; POSITION: absolute; TOP: 62px; HEIGHT: 134px\" >\n private void Page_Load(object sender, System.EventArgs e)\n{\n if (!IsPostBack)\n {\n\n int nItem = Convert.ToInt32(ListBox1.Items.Count * 17);\n ListBox1.Height = nItem; \n\n ListBox1.Width = 800; \n\n }\n}\n"
},
{
"answer_id": 29523336,
"author": "Vinicius",
"author_id": 4554703,
"author_profile": "https://Stackoverflow.com/users/4554703",
"pm_score": 2,
"selected": false,
"text": "<asp:ListBox ID=\"List\" runat=\"server\" Height=\"320px\" Width=\"100%\" style=\"overflow-x:auto;\"SelectionMode=\"Multiple\">\n</asp:ListBox>\n"
},
{
"answer_id": 31075360,
"author": "Padmanaban",
"author_id": 3753470,
"author_profile": "https://Stackoverflow.com/users/3753470",
"pm_score": 0,
"selected": false,
"text": " List<Yourclass> result = null;\n result = Objname.getResult(Parameter1, Parameter2);\n foreach (Yourclass res in result)\n {\n txtBoxUser.Text += res.Fieldname1.ToString();\n txtBoxUser.Text += \"\\r\\n\" + res.Fieldname2.ToString();\n txtBoxUser.Text += \"\\n\\n\";\n }\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] |
45,546 |
<p>I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.</p>
|
[
{
"answer_id": 45568,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 3,
"selected": false,
"text": "response.setStatus(403)"
},
{
"answer_id": 45585,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 5,
"selected": true,
"text": "<% response.setStatus( 403 ); %>\n SimpleMappingExceptionResolver PermissionDeniedException permissionDenied.jsp <bean id=\"exceptionResolver\"\n class=\"org.springframework.web.servlet.handler.SimpleMappingExceptionResolver\">\n <property name=\"exceptionMappings\">\n <props>\n <prop key=\"PermissionDeniedException\"> \n rescues/permissionDenied\n </prop>\n ... set other exception/view mappings as <prop>s here ...\n </props>\n </property>\n <property name=\"defaultErrorView\" value=\"rescues/general\" />\n</bean>\n\n<bean id=\"viewResolver\"\n class=\"org.springframework.web.servlet.view.InternalResourceViewResolver\">\n <property name=\"viewClass\" value=\"org.springframework.web.servlet.view.JstlView\" />\n <property name=\"prefix\" value=\"/WEB-INF/views/\" />\n <property name=\"suffix\" value=\".jsp\" />\n</bean>\n"
},
{
"answer_id": 45620,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 4,
"selected": false,
"text": "ExceptionResolver response.sendError(HttpServletResponse.SC_FORBIDDEN, \"AdditionalInformationIfAvailable\");"
},
{
"answer_id": 28883524,
"author": "yankee",
"author_id": 327301,
"author_profile": "https://Stackoverflow.com/users/327301",
"pm_score": 6,
"selected": false,
"text": "@ResponseStatus(HttpStatus.FORBIDDEN)\npublic class ForbiddenException extends RuntimeException {\n}\n"
},
{
"answer_id": 38467064,
"author": "Chris Ritchie",
"author_id": 2591088,
"author_profile": "https://Stackoverflow.com/users/2591088",
"pm_score": 6,
"selected": false,
"text": "org.springframework.security.access.AccessDeniedException(\"403 returned\");\n"
},
{
"answer_id": 72009693,
"author": "Largos",
"author_id": 13061563,
"author_profile": "https://Stackoverflow.com/users/13061563",
"pm_score": 3,
"selected": false,
"text": "ResponseStatusException @GetMapping(\"/demo\")\npublic String demo(){\n if (forbidden){\n throw new ResponseStatusException(HttpStatus.FORBIDDEN); \n }\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4702/"
] |
45,577 |
<p>This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident.</p>
<p>Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad.</p>
<p>Does anyone know why does happens? Better yet, anyone know how to fix it?</p>
|
[
{
"answer_id": 215482,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 1,
"selected": false,
"text": "Couldn't reformat due to line 123"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4050/"
] |
45,582 |
<p>I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods.</p>
<p>goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed. </p>
|
[
{
"answer_id": 46115,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 0,
"selected": false,
"text": "def binding = new Binding(x: 6, y: 4)\ndef shell = new GroovyShell(binding)\ndef expression = '''f = x * y'''\nshell.evaluate(expression)\nassert binding.getVariable(\"f\") == 24\n"
},
{
"answer_id": 64063,
"author": "shemnon",
"author_id": 8020,
"author_profile": "https://Stackoverflow.com/users/8020",
"pm_score": 2,
"selected": false,
"text": "class C {{println 'hi'}}\nnew C()\n new C()\n Class klass = this.getClass()\nthis.getMetaClass().getMethods().each {\n if (it.declaringClass.cachedClass == klass) {\n binding[it.name] = this.&\"$it.name\"\n }\n}\n String scriptText = ...\nScript script = shell.parse(scriptText)\ndef returnValue = script.run()\nClass klass = script.getClass()\nscript.getMetaClass().getMethods().each {\n if (it.declaringClass.cachedClass == klass) {\n shell.context[it.name] = this.&\"$it.name\"\n }\n}\n// do whatever with returnValue...\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/287/"
] |
45,600 |
<p>The <a href="http://dev.jquery.com/view/trunk/ui/demos/functional/#ui.dialog" rel="nofollow noreferrer">demos</a> for the jquery ui dialog all use the "flora" theme. I wanted a customized theme, so I used the themeroller to generate a css file. When I used it, everything seemed to be working fine, but later I found that I can't control any input element contained in the dialog (i.e, can't type into a text field, can't check checkboxes). Further investigation revealed that this happens if I set the dialog attribute "modal" to true. This doesn't happen when I use the flora theme. </p>
<p>Here is the js file:</p>
<pre><code>topMenu = {
init: function(){
$("#my_button").bind("click", function(){
$("#SERVICE03_DLG").dialog("open");
$("#something").focus();
});
$("#SERVICE03_DLG").dialog({
autoOpen: false,
modal: true,
resizable: false,
title: "my title",
overlay: {
opacity: 0.5,
background: "black"
},
buttons: {
"OK": function() {
alert("hi!");
},
"cancel": function() {
$(this).dialog("close");
}
},
close: function(){
$("#something").val("");
}
});
}
}
$(document).ready(topMenu.init);
</code></pre>
<p>Here is the html that uses the flora theme:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="flora/flora.all.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="flora">please enter something<br><br>
<label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
</code></pre>
<p>Here is the html that uses the downloaded themeroller theme:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<title>sample</title>
<script src="jquery-1.2.6.min.js" language="JavaScript"></script>
<link rel="stylesheet" href="jquery-ui-themeroller.css" type="text/css">
<script src="jquery-ui-personalized-1.5.2.min.js" language="JavaScript"></script>
<script src="TopMenu.js" language="JavaScript"></script>
</head>
<body>
<input type="button" value="click me!" id="my_button">
<div id="SERVICE03_DLG" class="ui-dialog">please enter something<br><br>
<label for="something">somthing:</label>&nbsp;<input name="something" id="something" type="text" maxlength="20" size="24">
</div>
</body>
</html>
</code></pre>
<p>As you can see, only the referenced css file and class names are different.
Anybody have a clue as to what could be wrong?</p>
<p>@David: I tried it, and it doesn't seem to work (neither on FF or IE). I tried inline css:</p>
<pre class="lang-none prettyprint-override"><code>style="z-index:5000"
</code></pre>
<p>and I've also tried it referencing an external css file:</p>
<pre class="lang-none prettyprint-override"><code>#SERVICE03_DLG{z-index:5000;}
</code></pre>
<p>But neither of these work. Am I missing something in what you suggested?</p>
<p><strong>Edit:</strong><br>
Solve by brostbeef!<br>
Since I was originally using flora, I had mistakenly assumed that I have to specify a class attribute. Turns out, this is only true when you actually use the flora theme (as in the samples). If you use the customized theme, specifying a class attribute causes that strange behaviour.</p>
|
[
{
"answer_id": 231357,
"author": "brostbeef",
"author_id": 16437,
"author_profile": "https://Stackoverflow.com/users/16437",
"pm_score": 3,
"selected": true,
"text": "<div id=\"SERVICE03_DLG\" class=\"flora\"> <div id=\"SERVICE03_DLG\" class=\"ui-dialog\">"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
] |
45,604 |
<p>C# doesn't require you to specify a generic type parameter if the compiler can infer it, for instance:</p>
<pre><code>List<int> myInts = new List<int> {0,1,1,
2,3,5,8,13,21,34,55,89,144,233,377,
610,987,1597,2584,4181,6765};
//this statement is clunky
List<string> myStrings = myInts.
Select<int,string>( i => i.ToString() ).
ToList<string>();
//the type is inferred from the lambda expression
//the compiler knows that it's taking an int and
//returning a string
List<string> myStrings = myInts.
Select( i => i.ToString() ).
ToList();
</code></pre>
<p>This is needed for anonymous types where you don't know what the type parameter would be (in intellisense it shows up as <code>'a</code>) because it's added by the compiler.</p>
<p>Class-level type parameters don't let you do this:</p>
<pre><code>//sample generic class
public class GenericDemo<T>
{
public GenericDemo ( T value )
{
GenericTypedProperty = value;
}
public T GenericTypedProperty {get; set;}
}
//why can't I do:
int anIntValue = 4181;
var item = new GenericDemo( anIntValue ); //type inference fails
//however I can create a wrapper like this:
public static GenericDemo<T> Create<T> ( T value )
{
return new GenericDemo<T> ( value );
}
//then this works - type inference on the method compiles
var item = Create( anIntValue );
</code></pre>
<p>Why doesn't C# support this class level generic type inference?</p>
|
[
{
"answer_id": 45612,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "class Foo<T> {\n public Foo<U>(U x) { }\n}\n\nvar x = new Foo(1);\n"
},
{
"answer_id": 45706,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "//your example\nvar x = new Foo( 1 );\n\n//becomes\nvar x = Foo.ctor( 1 );\n\n//your problem is valid because this would be\nvar x = Foo<T>.ctor<int>( 1 );\n//and T can't be inferred\n class Foo<T> \n{\n //<T> can't mean anything else in this context\n public Foo(T x) { }\n}\n\n//this would now throw an exception unless the\n//typeparam matches the parameter\nvar x = Foo<int>.ctor( 1 );\n\n//so why wouldn't this work?\nvar x = Foo.ctor( 1 );\n"
},
{
"answer_id": 45728,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 6,
"selected": true,
"text": "class Foo<T> {\n public Foo(T x) { … }\n}\n\n// Notice: non-generic class overload. Possible in C#!\nclass Foo {\n public static Foo<T> ctor<T>(T x) { return new Foo<T>(x); }\n}\n\nvar x = Foo.ctor(42);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
45,611 |
<p>I have a database with a few dozen tables interlinked with foreign keys. Under normal circumstances, I want the default <code>ON DELETE RESTRICT</code> behavior for those constraints. But when trying to share a snapshot of the database with a consultant, I needed to remove some sensitive data. I wish that my memory of a <code>DELETE FROM Table CASCADE</code> command hadn't been pure hallucination.</p>
<p>What I ended out doing was dumping the database, writing a script to process the dump by adding <code>ON DELETE CASCADE</code> clauses too all the foreign key constraints, restoring from that, performing my deletes, dumping again, removing the <code>ON DELETE CASCADE</code>, and finally restoring again. That was easier than writing the deletion query I'd have needed to do this in SQL -- removing whole slices of the database isn't a normal operation, so the schema isn't exactly adapted to it.</p>
<p>Does anyone have a better solution for the next time something like this comes up?</p>
|
[
{
"answer_id": 56978,
"author": "angch",
"author_id": 5386,
"author_profile": "https://Stackoverflow.com/users/5386",
"pm_score": 0,
"selected": false,
"text": "createdb -h scratchserver scratchdb\ncreatedb -h scratchserver sanitizeddb\n\npg_dump -h liveserver livedb --schema-only | psql -h scratchserver sanitizeddb\npg_dump -h scratchserver sanitizeddb | sed -e \"s/RESTRICT/CASCADE/\" | psql -h scratchserver scratchdb\n\npg_dump -h liveserver livedb --data-only | psql -h scratchserver scratchdb\npsql -h scrachserver scratchdb -f delete-sensitive.sql\n\npg_dump -h scratchserver scratchdb --data-only | psql -h scratchserver sanitizeddb\npg_dump -Fc -Z9 -h scratchserver sanitizedb > sanitizeddb.pgdump\n"
},
{
"answer_id": 155396,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE \"header\"\n(\n header_id serial NOT NULL,\n CONSTRAINT header_pkey PRIMARY KEY (header_id)\n);\n\nCREATE TABLE detail\n(\n header_id integer,\n stuff text,\n CONSTRAINT detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) MATCH SIMPLE\n ON UPDATE NO ACTION ON DELETE NO ACTION\n);\ninsert into header values(1);\ninsert into detail values(1,'stuff');\ndelete from header where header_id=1;\nalter table detail drop constraint detail_header_id_fkey;\nalter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) on delete cascade;\ndelete from header where header_id=1;\nalter table detail add constraint detail_header_id_fkey FOREIGN KEY (header_id)\n REFERENCES \"header\" (header_id) on delete restrict;\n"
},
{
"answer_id": 3010204,
"author": "user362911",
"author_id": 362911,
"author_profile": "https://Stackoverflow.com/users/362911",
"pm_score": 1,
"selected": false,
"text": "TRUNCATE table CASCADE;\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
45,613 |
<p>What could be the problem with reversing the array of DOM objects as in the following code:</p>
<pre><code>var imagesArr = new Array();
imagesArr = document.getElementById("myDivHolderId").getElementsByTagName("img");
imagesArr.reverse();
</code></pre>
<p>In Firefox 3, when I call the <code>reverse()</code> method the script stops executing and shows the following error in the console of the Web Developer Toolbar:</p>
<pre class="lang-none prettyprint-override"><code>imagesArr.reverse is not a function
</code></pre>
<p>The <code>imagesArr</code> variable can be iterated through with a for loop and elements like <code>imagesArr[i]</code> can be accessed, so why is it not seen as an array when calling the <code>reverse()</code> method?</p>
|
[
{
"answer_id": 45740,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "getElementsByTag() var listNodes = document.getElementById(\"myDivHolderId\").getElementsByTagName(\"img\");\nvar arrayNodes = Array.slice.call(listNodes, 0);\narrayNodes.reverse();\n Array.prototype.slice.call(arrayLike, 0) $.makeArray(arrayLike) Array.prototype.reverse.call(listNodes);\n"
},
{
"answer_id": 28211790,
"author": "iProDev",
"author_id": 4506730,
"author_profile": "https://Stackoverflow.com/users/4506730",
"pm_score": 3,
"selected": false,
"text": "getElementsByTag() var imagesArr = [].slice.call(document.getElementById(\"myDivHolderId\").getElementsByTagName(\"img\"), 0).reverse();\n"
},
{
"answer_id": 29168307,
"author": "Mr. X",
"author_id": 4388578,
"author_profile": "https://Stackoverflow.com/users/4388578",
"pm_score": 2,
"selected": false,
"text": "getElementsByTagName() getElementsByClassName() HTMLCollection NodeList children HTMLCollection childNodes NodeList querySelectorAll() NodeList HTMLCollection NodeList HTMLCollection querySelectorAll() HTMLCollection NodeList"
},
{
"answer_id": 68064201,
"author": "Muhammad Fahim",
"author_id": 12581164,
"author_profile": "https://Stackoverflow.com/users/12581164",
"pm_score": 3,
"selected": false,
"text": "let elements = document.querySelectorAll('button');\nelements = [...elements];\nconsole.log(elements) // Before reverse\nelements = elements.reverse(); // Now the reverse function will work\nconsole.log(elements) // After reverse <html>\n<body>\n<button>button1</button>\n<button>button2</button>\n<button>button3</button>\n<button>button4</button>\n<button>button5</button>\n</body>\n</html>"
},
{
"answer_id": 73631405,
"author": "Baz Love",
"author_id": 2845079,
"author_profile": "https://Stackoverflow.com/users/2845079",
"pm_score": 0,
"selected": false,
"text": "var Slides = document.getElementById(\"slideshow\").querySelectorAll('li');\nvar TempArr = [];\nfor (var x = Slides.length; x--;) {\n TempArr.push(Slides[x]);\n}\nSlides = TempArr;\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4723/"
] |
45,621 |
<p>Example</p>
<p>I have <code>Person</code>, <code>SpecialPerson</code>, and <code>User</code>. <code>Person</code> and <code>SpecialPerson</code> are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as <code>Person</code> and potentially <code>SpecialPerson</code>, along with a user name and password as they are registered with the site.</p>
<hr>
<p>How would you address this problem? Would you have a <code>Person</code> table which stores all data common to a person and use a key to look up their data in <code>SpecialPerson</code> (if they are a special person) and User (if they are a user) and vice-versa?</p>
|
[
{
"answer_id": 45770,
"author": "Radu094",
"author_id": 3263,
"author_profile": "https://Stackoverflow.com/users/3263",
"pm_score": 3,
"selected": false,
"text": "PERSON (personid,persontype, name,address, phone, XMLOtherProperties)\n public string StrangeProperty\n{\nget { return XMLPropertyBag[\"StrangeProperty\"];}\nset { XMLPropertyBag[\"StrangeProperty\"]= value;}\n}\n"
},
{
"answer_id": 28781045,
"author": "Oliver Williams",
"author_id": 4127646,
"author_profile": "https://Stackoverflow.com/users/4127646",
"pm_score": 2,
"selected": false,
"text": "type User credentials ( user_id, username, password) LEFT JOIN"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
45,623 |
<p>In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.</p>
<p>Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?</p>
<p>In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?</p>
|
[
{
"answer_id": 45630,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 5,
"selected": true,
"text": "SocketChannels boolean finished = false;\nint port = 10000;\nServerSocket server = new ServerSocket(port);\n\nwhile (!finished) {\n // This will block until a connection is made\n Socket s = server.accept();\n // Spawn off some thread (or use a thread pool) to handle this socket\n // Server will continue to listen\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4739/"
] |
45,624 |
<p>I use TortoiseSVN to access file based local repo. In all my commits an author is my Windows login name. Is it possible to use different name?</p>
<p>I know how to change author after commit but how to change before? Installing apache/svnserver is not an option. </p>
|
[
{
"answer_id": 45673,
"author": "Brock Boland",
"author_id": 2185,
"author_profile": "https://Stackoverflow.com/users/2185",
"pm_score": 0,
"selected": false,
"text": "msznajder file:///msznajder@localhost/some/file/path"
},
{
"answer_id": 265268,
"author": "Rômulo Ceccon",
"author_id": 23193,
"author_profile": "https://Stackoverflow.com/users/23193",
"pm_score": 5,
"selected": true,
"text": "$ svn co --username different_user_name file:///C:/path/to/your/repo\n %APPDATA%\\Subversion\\auth\\svn.username"
},
{
"answer_id": 779224,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "svn propset svn:author --revprop -r HEAD <author> file:///<path-to-repo>"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
] |
45,626 |
<p>I have a basic CRUD form that uses PageMethods to update the user details, however the Validators don't fire off, I think I need to manually initialize the validators and check whether the validation has passed in my javascript save method. Any ideas on how to do this?</p>
|
[
{
"answer_id": 49371,
"author": "Nicholas",
"author_id": 2808,
"author_profile": "https://Stackoverflow.com/users/2808",
"pm_score": 2,
"selected": true,
"text": "Page_ClientValidate() Page_ClientValidate() function Save()\n {\n var clientValidationPassed =Page_ClientValidate();\n if(clientValidationPassed)\n {\n //Save Data\n PageMethods.SaveUser(UserName,Role,SaveCustomerRequestComplete, RequestError);\n $find('editPopupExtender').hide();\n }\n else\n {\n //Do Nothing as CLient Validation messages are now displayed\n }\n return false;\n }\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2808/"
] |
45,627 |
<p>In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)</p>
<p>We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.</p>
<p>I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)</p>
<p>I am expecting your experiences, suggestions and maybe some references to tools which simplify this.</p>
|
[
{
"answer_id": 45652,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 3,
"selected": false,
"text": "vector string auto_ptr unique_ptr unique_ptr shared_ptr"
},
{
"answer_id": 45717,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 2,
"selected": false,
"text": "InitAllocCheck(ACOutput_XML)\nDeInitAllocCheck()\n"
},
{
"answer_id": 45721,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "_CrtSetDbgFlag _CrtSetBreakAlloc"
},
{
"answer_id": 45767,
"author": "Dan Shield",
"author_id": 4633,
"author_profile": "https://Stackoverflow.com/users/4633",
"pm_score": 1,
"selected": false,
"text": "_Crt*"
},
{
"answer_id": 45943,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 5,
"selected": false,
"text": "std::unique_ptr std::shared_ptr std::weak_ptr"
},
{
"answer_id": 46360,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 2,
"selected": false,
"text": "new"
},
{
"answer_id": 50095,
"author": "Dusty Campbell",
"author_id": 2174,
"author_profile": "https://Stackoverflow.com/users/2174",
"pm_score": 6,
"selected": false,
"text": "#define _CRTDBG_MAP_ALLOC\n#include <stdlib.h>\n#include <crtdbg.h>\n _CrtDumpMemoryLeaks();\n _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] |
45,634 |
<p>How do you rewrite this in Linq?</p>
<pre><code>SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....)
</code></pre>
<p>So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.</p>
|
[
{
"answer_id": 45648,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": true,
"text": "from a in TableA \nwhere (from b in TableB \n join c in TableC on b.id equals c.id\n where .. select b.id)\n.Contains(a.Id) \nselect new { a.Id, a.Name }\n"
},
{
"answer_id": 86213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "from a in TableA\nwhere (\n from b in TableB\n join c in TableC\n on b.id equals c.id\n select b.id\n).Contains(TableA.Id)\nselect new { a.Id, a.Name }\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
45,642 |
<p>I was wondering if there is an open source library or algorithm that can expand a non-numeric range. For example, if you have <code>1A</code> to <code>9A</code> you should get </p>
<pre><code>1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A.
</code></pre>
<p>I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).</p>
|
[
{
"answer_id": 47126,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 0,
"selected": false,
"text": "0-9 A-Z 1A (1,A) AA1BB2 (AA,1,BB,2) AB CDE AB CD IEnumerable<string> ExpandRange( string start, string end ) {\n // Split coordinates into component parts.\n string[] startParts = GetRangeParts( start );\n string[] endParts = GetRangeParts( end );\n\n // Expand range between parts \n // (i.e. 1->3 becomes 1,2,3; A->C becomes A,B,C).\n int length = startParts.Length;\n int[] lengths = new int[length];\n string[][] expandedParts = new string[length][];\n for( int i = 0; i < length; ++i ) {\n expandedParts[i] = ExpandRangeParts( startParts[i], endParts[i] );\n lengths[i] = expandedParts[i].Length;\n }\n\n // Return all combinations of expanded parts.\n int[] indexes = new int[length];\n do {\n var sb = new StringBuilder( );\n for( int i = 0; i < length; ++i ) {\n int partIndex = indexes[i];\n sb.Append( expandedParts[i][partIndex] );\n }\n yield return sb.ToString( );\n } while( IncrementIndexes( indexes, lengths ) );\n}\n\nreadonly Regex RangeRegex = new Regex( \"([0-9]*)([A-Z]*)\" );\nstring[] GetRangeParts( string range ) {\n // Match all alternating digit-letter components of coordinate.\n var matches = RangeRegex.Matches( range );\n var parts =\n from match in matches.Cast<Match>( )\n from matchGroup in match.Groups.Cast<Group>( ).Skip( 1 )\n let value = matchGroup.Value\n where value.Length > 0\n select value;\n return parts.ToArray( );\n}\n\nstring[] ExpandRangeParts( string startPart, string endPart ) {\n int start, end;\n Func<int, string> toString;\n\n bool isNumeric = char.IsDigit( startPart, 0 );\n if( isNumeric ) {\n // Parse regular integers directly.\n start = int.Parse( startPart );\n end = int.Parse( endPart );\n toString = ( i ) => i.ToString( );\n }\n else {\n // Convert alphabetic numbers to integers for expansion,\n // then convert back for display.\n start = AlphaNumberToInt( startPart );\n end = AlphaNumberToInt( endPart );\n toString = IntToAlphaNumber;\n }\n\n int count = end - start + 1;\n return Enumerable.Range( start, count )\n .Select( toString )\n .Where( s => s.Length > 0 )\n .ToArray( );\n}\n\nbool IncrementIndexes( int[] indexes, int[] lengths ) {\n // Increment indexes from right to left (i.e. Arabic numeral order).\n bool carry = true;\n for( int i = lengths.Length; carry && i > 0; --i ) {\n int index = i - 1;\n int incrementedValue = (indexes[index] + 1) % lengths[index];\n indexes[index] = incrementedValue;\n carry = (incrementedValue == 0);\n }\n return !carry;\n}\n\n// Alphabetic numbers are 1-based (i.e. A = 1, AA = 11, etc, mod base-26).\nconst char AlphaDigitZero = (char)('A' - 1);\nconst int AlphaNumberBase = 'Z' - AlphaDigitZero + 1;\nint AlphaNumberToInt( string number ) {\n int sum = 0;\n int place = 1;\n foreach( char c in number.Cast<char>( ).Reverse( ) ) {\n int digit = c - AlphaDigitZero;\n sum += digit * place;\n place *= AlphaNumberBase;\n }\n return sum;\n}\n\nstring IntToAlphaNumber( int number ) {\n List<char> digits = new List<char>( );\n while( number > 0 ) {\n int digit = number % AlphaNumberBase;\n if( digit == 0 ) // Compensate for 1-based alphabetic numbers.\n return \"\";\n\n char c = (char)(AlphaDigitZero + digit);\n digits.Add( c );\n number /= AlphaNumberBase;\n }\n\n digits.Reverse( );\n return new string( digits.ToArray( ) );\n}\n"
},
{
"answer_id": 47373,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 1,
"selected": false,
"text": "S S('3A') = '4A' s = initial_string\nwhile s != final_string do\n output s\n s = S(s)\noutput s\n l b e // initialise s with b at every position\nfor i in [0..l) do\n s[i] = b\ndone = false\nwhile not done do\n output s\n j = 0\n // if s[j] is e, reset it to b and \"add carry\"\n while j < l and s[j] == e do\n s[j] = b\n j = j + 1\n if j == l then\n done = true\n if not done then\n s[j] = s[j] + 1\n l l"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1210/"
] |
45,650 |
<p>Many times I have seen Visual Studio solutions which have multiple projects that share source files. These common source files are usually out in a common directory and in the solution explorer their icon shows up with a link arrow in the bottom left.</p>
<p>However, any time I try to add a source file to the project that is outside of that project's main directory, it just automatically copies it into the directory so that I no longer have a shared copy.</p>
<p>I found that I can get around this by manually opening the project file in a text editor and modifying the path to something like "../../../Common/Source.cs" but this is more of a hack then I would like.</p>
<p>Is there a setting or something I can change that will allow me to do this from within the IDE?</p>
|
[
{
"answer_id": 45677,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 2,
"selected": false,
"text": "<Compile Include=\"..\\CommonAssemblyInfo.cs\">\n <Link>CommonAssemblyInfo.cs</Link>\n</Compile>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
45,651 |
<p>I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.</p>
<p>Can you tell me how to do it the right way?</p>
|
[
{
"answer_id": 45657,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "SELECT @@Scope_Identity as Id\n"
},
{
"answer_id": 45665,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 5,
"selected": false,
"text": "CREATE PROCEDURE [dbo].[InsertProducts]\n @id INT = NULL OUT,\n @name VARCHAR(150) = NULL,\n @desc VARCHAR(250) = NULL\n\nAS\n\n INSERT INTO dbo.Products\n (Name,\n Description)\n VALUES\n (@name,\n @desc)\n\n SET @id = SCOPE_IDENTITY();\n"
},
{
"answer_id": 45667,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 7,
"selected": true,
"text": "@@IDENTITY SCOPE_IDENTITY()"
},
{
"answer_id": 45682,
"author": "Tobias Baaz",
"author_id": 3036,
"author_profile": "https://Stackoverflow.com/users/3036",
"pm_score": 1,
"selected": false,
"text": "LAST_INSERT_ID()"
},
{
"answer_id": 45743,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 4,
"selected": false,
"text": "Connection conn = Database.getCurrent().getConnection(); \nPreparedStatement ps = conn.prepareStatement(insertSql, Statement.RETURN_GENERATED_KEYS);\ntry { \n ps.executeUpdate(); \n ResultSet rs = ps.getGeneratedKeys(); \n rs.next(); \n long primaryKey = rs.getLong(1); \n} finally { \n ps.close(); \n} \n"
},
{
"answer_id": 45775,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE mytable (\n id SERIAL PRIMARY KEY,\n lastname VARCHAR NOT NULL,\n firstname VARCHAR\n);\n INSERT INTO mytable (lastname, firstname) VALUES ('Washington', 'George');\nSELECT lastval();\n INSERT INTO mytable (lastname) VALUES ('Cher') RETURNING id;\n"
},
{
"answer_id": 45820,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE [dbo].[Test](\n [ID] [int] IDENTITY(1,1) NOT NULL,\n [somevalue] [nchar](10) NULL,\n) \n INSERT INTO Test(somevalue)\nOUTPUT INSERTED.ID\nVALUES('asdfasdf')\n"
},
{
"answer_id": 45949,
"author": "Wyck Hebert",
"author_id": 4772,
"author_profile": "https://Stackoverflow.com/users/4772",
"pm_score": 2,
"selected": false,
"text": " INSERT INTO MyTable (Field1, Field2) VALUES (@Value1, @Value2); \n SELECT SCOPE_IDENTITY(); \n INSERT INTO MyTable (Field1, Field2) VALUES (?Value1, ?Value2);\n SELECT LAST_INSERT_ID();\n"
},
{
"answer_id": 312905,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "CREATE OR REPLACE PACKAGE LAST\nAS\nID NUMBER;\nFUNCTION IDENT RETURN NUMBER;\nEND;\n/\n\nCREATE OR REPLACE PACKAGE BODY LAST\nAS\nFUNCTION IDENT RETURN NUMBER IS\n BEGIN\n RETURN ID;\n END;\nEND;\n/\n\n\nCREATE TABLE Test (\n TestID INTEGER ,\n Field1 int,\n Field2 int\n)\n\n\nCREATE SEQUENCE Test_seq\n/\nCREATE OR REPLACE TRIGGER Test_itrig\nBEFORE INSERT ON Test\nFOR EACH ROW\nDECLARE\nseq_val number;\nBEGIN\nIF :new.TestID IS NULL THEN\n SELECT Test_seq.nextval INTO seq_val FROM DUAL;\n :new.TestID := seq_val;\n Last.ID := seq_val;\nEND IF;\nEND;\n/\n\nTo get next identity value:\nSELECT LAST.IDENT FROM DUAL\n"
},
{
"answer_id": 312909,
"author": "Daniel Schaffer",
"author_id": 2596,
"author_profile": "https://Stackoverflow.com/users/2596",
"pm_score": 4,
"selected": false,
"text": "DECLARE @inserted_ids TABLE ([id] INT);\n\nINSERT INTO [dbo].[some_table] ([col1],[col2],[col3],[col4],[col5],[col6])\nOUTPUT INSERTED.[id] INTO @inserted_ids\nVALUES (@col1,@col2,@col3,@col4,@col5,@col6)\n"
},
{
"answer_id": 3159308,
"author": "James Lawruk",
"author_id": 88204,
"author_profile": "https://Stackoverflow.com/users/88204",
"pm_score": 2,
"selected": false,
"text": "sql = \"INSERT INTO MyTable (Name) VALUES (@Name);\" +\n \"SELECT CAST(scope_identity() AS int)\";\nSqlCommand cmd = new SqlCommand(sql, conn);\nint newId = (int)cmd.ExecuteScalar();\n"
},
{
"answer_id": 12000913,
"author": "Jan Remunda",
"author_id": 77154,
"author_profile": "https://Stackoverflow.com/users/77154",
"pm_score": 2,
"selected": false,
"text": " Declare @tblInsertedId table (Id int not null)\n\n INSERT INTO Test ([Title], [Text])\n OUTPUT inserted.Id INTO @tblInsertedId (Id)\n SELECT [Title], [Text] FROM AnotherTable\n\n select Id from @tblInsertedId \n"
},
{
"answer_id": 16434253,
"author": "SuperLucky",
"author_id": 766963,
"author_profile": "https://Stackoverflow.com/users/766963",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO my_table(col1,col2,col3) OUTPUT INSERTED.id VALUES('col1Value','col2Value','col3Value')\n"
},
{
"answer_id": 24127021,
"author": "LiranBo",
"author_id": 3022900,
"author_profile": "https://Stackoverflow.com/users/3022900",
"pm_score": 0,
"selected": false,
"text": "command.ExecuteScalar()\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
45,653 |
<p>We use QuickBooks for financial management, and feed it from a variety of sources. I now need to hook it up to BizTalk, and I'd hate to reinvent the wheel. I've done searches, and as far as I can tell there's no QuickBooks adapter for BizTalk. Does anyone know of anything that'll do the job, preferably something that doesn't suck? </p>
<hr>
<p>Doesn't the QB SDK require that Quickbooks be running on the client machine? Is there any way around it?</p>
|
[
{
"answer_id": 45735,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 2,
"selected": true,
"text": "Imports QBFC7Lib\n\nSub AttachToDB()\n If isAttachedtoQB Then Exit Sub\n\n Lasterror = \"Unknown QuickBooks Error\"\n Try\n QbSession = New QBSessionManager\n QbSession.OpenConnection(\"\", \"Your Company Name\")\n QbSession.BeginSession(\"\", ENOpenMode.omDontCare)\n MsgReq = QbSession.CreateMsgSetRequest(\"UK\", 6, 0)\n MsgReq.Attributes.OnError = ENRqOnError.roeStop\n\n Lasterror = \"\"\n isAttachedtoQB = True\n Catch e As Exception\n If Not QbSession Is Nothing Then\n QbSession.CloseConnection()\n QbSession = Nothing\n End If\n isAttachedtoQB = False\n Lasterror = \"QuickBooks Connection Error. - \" + e.Message + \".\"\n End Try\nEnd Sub\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] |
45,658 |
<p>I wrote an Active X plugin for IE7 which implements IObjectWithSite besides some other necessary interfaces (note no IOleClient). This interface is queried and called by IE7. During the SetSite() call I retrieve a pointer to IE7's site interface which I can use to retrieve the IHTMLDocument2 interface using the following approach:</p>
<pre><code>IUnknown *site = pUnkSite; /* retrieved from IE7 during SetSite() call */
IServiceProvider *sp = NULL;
IHTMLWindow2 *win = NULL;
IHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(IID_IServiceProvider, (void **)&sp);
if(sp) {
sp->QueryService(IID_IHTMLWindow2, IID_IHTMLWindow2, (void **)&win);
if(win) {
win->get_document(&doc);
}
}
}
if(doc) {
/* found */
}
</code></pre>
<p>I tried a similiar approach on PIE as well using the following code, however, even the IPIEHTMLWindow2 interface cannot be acquired, so I'm stuck:</p>
<pre><code>IUnknown *site = pUnkSite; /* retrieved from PIE during SetSite() call */
IPIEHTMLWindow2 *win = NULL;
IPIEHTMLDocument1 *tmp = NULL;
IPIEHTMLDocument2 *doc = NULL;
if(site) {
site->QueryInterface(__uuidof(*win), (void **)&win);
if(win) { /* never the case */
win->get_document(&tmp);
if(tmp) {
tmp->QueryInterface(__uuidof(*doc), (void **)&doc);
}
}
}
if(doc) {
/* found */
}
</code></pre>
<p>Using the IServiceProvider interface doesn't work either, so I already tested this.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 63430,
"author": "gnobal",
"author_id": 7748,
"author_profile": "https://Stackoverflow.com/users/7748",
"pm_score": 3,
"selected": true,
"text": "#ifdef WINCE\n// We can't get IWebBrowser2 for WinCE.\n#else\nHRESULT ActiveXUtils::GetWebBrowser2(IUnknown *site, IWebBrowser2 **browser2) {\n CComQIPtr<IServiceProvider> service_provider = site;\n if (!service_provider) { return E_FAIL; }\n\n return service_provider->QueryService(SID_SWebBrowserApp,\n IID_IWebBrowser2,\n reinterpret_cast<void**>(browser2));\n}\n#endif\n\n\nHRESULT ActiveXUtils::GetHtmlDocument2(IUnknown *site,\n IHTMLDocument2 **document2) {\n HRESULT hr;\n\n#ifdef WINCE\n // Follow path Window2 -> Window -> Document -> Document2\n CComPtr<IPIEHTMLWindow2> window2;\n hr = GetHtmlWindow2(site, &window2);\n if (FAILED(hr) || !window2) { return false; }\n CComQIPtr<IPIEHTMLWindow> window = window2;\n CComPtr<IHTMLDocument> document;\n hr = window->get_document(&document);\n if (FAILED(hr) || !document) { return E_FAIL; }\n return document->QueryInterface(__uuidof(*document2),\n reinterpret_cast<void**>(document2));\n#else\n CComPtr<IWebBrowser2> web_browser2;\n hr = GetWebBrowser2(site, &web_browser2);\n if (FAILED(hr) || !web_browser2) { return E_FAIL; }\n\n CComPtr<IDispatch> doc_dispatch;\n hr = web_browser2->get_Document(&doc_dispatch);\n if (FAILED(hr) || !doc_dispatch) { return E_FAIL; }\n\n return doc_dispatch->QueryInterface(document2);\n#endif\n}\n\n\nHRESULT ActiveXUtils::GetHtmlWindow2(IUnknown *site,\n#ifdef WINCE\n IPIEHTMLWindow2 **window2) {\n // site is javascript IDispatch pointer.\n return site->QueryInterface(__uuidof(*window2),\n reinterpret_cast<void**>(window2));\n#else\n IHTMLWindow2 **window2) {\n CComPtr<IHTMLDocument2> html_document2;\n // To hook an event on a page's window object, follow the path\n // IWebBrowser2->document->parentWindow->IHTMLWindow2\n\n HRESULT hr = GetHtmlDocument2(site, &html_document2);\n if (FAILED(hr) || !html_document2) { return E_FAIL; }\n\n return html_document2->get_parentWindow(window2);\n#endif\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4735/"
] |
45,702 |
<p>Let's say I want to run a .NET application on a machine where the .NET framework is not available; Is there any way to compile the application to native code?</p>
|
[
{
"answer_id": 35467422,
"author": "James Ko",
"author_id": 4077294,
"author_profile": "https://Stackoverflow.com/users/4077294",
"pm_score": 5,
"selected": false,
"text": "cd dotnet compile --native\n dotnet compile --native --cpp\n"
},
{
"answer_id": 55796754,
"author": "kbridge4096",
"author_id": 4379906,
"author_profile": "https://Stackoverflow.com/users/4379906",
"pm_score": 2,
"selected": false,
"text": ".exe kernel32.dll"
},
{
"answer_id": 68139211,
"author": "codevision",
"author_id": 354473,
"author_profile": "https://Stackoverflow.com/users/354473",
"pm_score": 3,
"selected": false,
"text": "<PropertyGroup>\n <PublishAot>true</PublishAot>\n</PropertyGroup>\n <ItemGroup>\n <PackageReference Include=\"Microsoft.DotNet.ILCompiler\" Version=\"8.0.0-*\" />\n</ItemGroup>\n dotnet8 <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <packageSources>\n <!--To inherit the global NuGet package sources remove the <clear/> line below -->\n <clear />\n <add key=\"dotnet-public\" value=\"https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-public/nuget/v3/index.json\" />\n <add key=\"dotnet8\" value=\"https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet8/nuget/v3/index.json\" />\n </packageSources>\n</configuration>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/184/"
] |
45,729 |
<p>I want to use the <a href="http://msdn.microsoft.com/en-us/library/system.enterpriseservices.internal.publish.gacremove(VS.80).aspx" rel="nofollow noreferrer">Publish.GacRemove</a> function to remove an assembly from GAC. However, I don't understand what path I should pass as an argument.</p>
<p>Should it be a path to the original DLL (what if I removed it after installing it in the GAC?) or the path to the assembly in the GAC?</p>
<p><strong>UPDATE:</strong></p>
<p>I finally used <a href="http://blogs.msdn.com/junfeng/articles/229649.aspx" rel="nofollow noreferrer">these API wrappers</a>.</p>
|
[
{
"answer_id": 45747,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": true,
"text": "GacInstall GacRemove GacRemove"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/95/"
] |
45,732 |
<p>I have an object graph serialized to xaml. A rough sample of what it looks like is:</p>
<pre><code><MyObject xmlns.... >
<MyObject.TheCollection>
<PolymorphicObjectOne .../>
<HiImPolymorphic ... />
</MyObject.TheCollection>
</MyObject>
</code></pre>
<p>I want to use Linq to XML in order to extract the serialized objects within the TheCollection.</p>
<p><strong>Note</strong>: <code>MyObject</code> may be named differently at runtime; I'm interested in any object that implements the same interface, which has a public collection called <code>TheCollection</code> that contains types of <code>IPolymorphicLol</code>.</p>
<p>The only things I know at runtime are the depth at which I will find the collection and that the collection element is named ``*.TheCollection`. Everything else will change.</p>
<p>The xml will be retrieved from a database using Linq; if I could combine both queries so instead of getting the entire serialized graph and then extracting the collection objects I would just get back the collection that would be sweet.</p>
|
[
{
"answer_id": 45747,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": true,
"text": "GacInstall GacRemove GacRemove"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
45,769 |
<p>I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.</p>
<p>First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)</p>
<p>Then when you run your app in release mode just before deploying, which build of the libraries do you use?</p>
<p>How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?</p>
|
[
{
"answer_id": 46120,
"author": "Henk",
"author_id": 4613,
"author_profile": "https://Stackoverflow.com/users/4613",
"pm_score": 2,
"selected": false,
"text": "$(ConfigurationName) $(ProjectDir)\\..\\third-party-prj\\$(ConfigurationName)\\third-party.lib\n xcopy $(ProjectDir)\\..\\third-party-prj\\$(ConfigurationName)\\third-party.dll $(IntDir)\n $(ProjectDir) $(ConfigurationName) Debug Release $(ConfigurationName)"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4225/"
] |
45,779 |
<p>How would you dynamically subscribe to a C# event so that given a Object instance and a String name containing the name of the event, you subscribe to that event and do something (write to the console for example) when that event has been fired?</p>
<p>It would seem using Reflection this isn't possible and I would like to avoid having to use Reflection.Emit if possible, as this currently (to me) seems like the only way of doing it.</p>
<p><strong>/EDIT:</strong> I do not know the signature of the delegate needed for the event, this is the core of the problem</p>
<p><strong>/EDIT 2:</strong> Although delegate contravariance seems like a good plan, I can not make the assumption necessary to use this solution</p>
|
[
{
"answer_id": 45797,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "var o = new SomeObjectWithEvent;\no.GetType().GetEvent(\"SomeEvent\").AddEventHandler(...);\n"
},
{
"answer_id": 45804,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": -1,
"selected": false,
"text": "//reflect out the method to fire as a delegate\nEventHandler eventDelegate = \n ( EventHandler ) Delegate.CreateDelegate(\n typeof( EventHandler ), //type of event delegate\n objectWithEventSubscriber, //instance of the object with the matching method\n eventSubscriberMethodName, //the name of the method\n true );\n"
},
{
"answer_id": 45806,
"author": "Erick Sgarbi",
"author_id": 4171,
"author_profile": "https://Stackoverflow.com/users/4171",
"pm_score": 2,
"selected": false,
"text": "public TestForm()\n{\n Button b = new Button();\n\n this.Controls.Add(b);\n\n MethodInfo method = typeof(TestForm).GetMethod(\"Clickbutton\",\n BindingFlags.NonPublic | BindingFlags.Instance);\n Type type = typeof(EventHandler);\n\n Delegate handler = Delegate.CreateDelegate(type, this, method);\n\n EventInfo eventInfo = cbo.GetType().GetEvent(\"Click\");\n\n eventInfo.AddEventHandler(b, handler);\n\n}\n\nvoid Clickbutton(object sender, System.EventArgs e)\n{\n // Code here\n}\n"
},
{
"answer_id": 45901,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": " using System;\n using System.Linq;\n using System.Linq.Expressions;\n using System.Reflection;\n\n class ExampleEventArgs : EventArgs\n {\n public int IntArg {get; set;}\n }\n\n class EventRaiser\n { \n public event EventHandler SomethingHappened;\n public event EventHandler<ExampleEventArgs> SomethingHappenedWithArg;\n\n public void RaiseEvents()\n {\n if (SomethingHappened!=null) SomethingHappened(this, EventArgs.Empty);\n\n if (SomethingHappenedWithArg!=null) \n {\n SomethingHappenedWithArg(this, new ExampleEventArgs{IntArg = 5});\n }\n }\n }\n\n class Handler\n { \n public void HandleEvent() { Console.WriteLine(\"Handler.HandleEvent() called.\");}\n public void HandleEventWithArg(int arg) { Console.WriteLine(\"Arg: {0}\",arg); }\n }\n\n static class EventProxy\n { \n //void delegates with no parameters\n static public Delegate Create(EventInfo evt, Action d)\n { \n var handlerType = evt.EventHandlerType;\n var eventParams = handlerType.GetMethod(\"Invoke\").GetParameters();\n\n //lambda: (object x0, EventArgs x1) => d()\n var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,\"x\"));\n var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod(\"Invoke\"));\n var lambda = Expression.Lambda(body,parameters.ToArray());\n return Delegate.CreateDelegate(handlerType, lambda.Compile(), \"Invoke\", false);\n }\n\n //void delegate with one parameter\n static public Delegate Create<T>(EventInfo evt, Action<T> d)\n {\n var handlerType = evt.EventHandlerType;\n var eventParams = handlerType.GetMethod(\"Invoke\").GetParameters();\n\n //lambda: (object x0, ExampleEventArgs x1) => d(x1.IntArg)\n var parameters = eventParams.Select(p=>Expression.Parameter(p.ParameterType,\"x\")).ToArray();\n var arg = getArgExpression(parameters[1], typeof(T));\n var body = Expression.Call(Expression.Constant(d),d.GetType().GetMethod(\"Invoke\"), arg);\n var lambda = Expression.Lambda(body,parameters);\n return Delegate.CreateDelegate(handlerType, lambda.Compile(), \"Invoke\", false);\n }\n\n //returns an expression that represents an argument to be passed to the delegate\n static Expression getArgExpression(ParameterExpression eventArgs, Type handlerArgType)\n {\n if (eventArgs.Type==typeof(ExampleEventArgs) && handlerArgType==typeof(int))\n {\n //\"x1.IntArg\"\n var memberInfo = eventArgs.Type.GetMember(\"IntArg\")[0];\n return Expression.MakeMemberAccess(eventArgs,memberInfo);\n }\n\n throw new NotSupportedException(eventArgs+\"->\"+handlerArgType);\n }\n }\n\n\n static class Test\n {\n public static void Main()\n { \n var raiser = new EventRaiser();\n var handler = new Handler();\n\n //void delegate with no parameters\n string eventName = \"SomethingHappened\";\n var eventinfo = raiser.GetType().GetEvent(eventName);\n eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,handler.HandleEvent));\n\n //void delegate with one parameter\n string eventName2 = \"SomethingHappenedWithArg\";\n var eventInfo2 = raiser.GetType().GetEvent(eventName2);\n eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,handler.HandleEventWithArg));\n\n //or even just:\n eventinfo.AddEventHandler(raiser,EventProxy.Create(eventinfo,()=>Console.WriteLine(\"!\"))); \n eventInfo2.AddEventHandler(raiser,EventProxy.Create<int>(eventInfo2,i=>Console.WriteLine(i+\"!\")));\n\n raiser.RaiseEvents();\n }\n }\n"
},
{
"answer_id": 45913,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": false,
"text": " public Form1()\n {\n Button b = new Button();\n TextBox tb = new TextBox();\n\n this.Controls.Add(b);\n this.Controls.Add(tb);\n WireUp(b, \"Click\", \"Clickbutton\");\n WireUp(tb, \"KeyDown\", \"Clickbutton\");\n }\n\n void WireUp(object o, string eventname, string methodname)\n {\n EventInfo ei = o.GetType().GetEvent(eventname);\n\n MethodInfo mi = this.GetType().GetMethod(methodname, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);\n\n Delegate del = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);\n\n ei.AddEventHandler(o, del);\n\n }\n void Clickbutton(object sender, System.EventArgs e)\n {\n MessageBox.Show(\"hello!\");\n }\n"
},
{
"answer_id": 2693383,
"author": "Tim Lloyd",
"author_id": 189516,
"author_profile": "https://Stackoverflow.com/users/189516",
"pm_score": 1,
"selected": false,
"text": "EventPublisher publisher = new EventPublisher();\n\nforeach (EventInfo eventInfo in publisher.GetType().GetEvents())\n{\n DynamicEvent.Subscribe(eventInfo, publisher, (sender, e, eventName) =>\n {\n Console.WriteLine(\"Event raised: \" + eventName);\n });\n}\n"
},
{
"answer_id": 49780888,
"author": "Edward Brey",
"author_id": 145173,
"author_profile": "https://Stackoverflow.com/users/145173",
"pm_score": 0,
"selected": false,
"text": "OnRaised void Subscribe(object source, EventInfo ev)\n{\n var eventParams = ev.EventHandlerType.GetMethod(\"Invoke\").GetParameters().Select(p => Expression.Parameter(p.ParameterType)).ToArray();\n var eventHandler = Expression.Lambda(ev.EventHandlerType,\n Expression.Call(\n instance: Expression.Constant(this),\n method: typeof(EventSubscriber).GetMethod(nameof(OnRaised), BindingFlags.NonPublic | BindingFlags.Instance),\n arg0: Expression.Constant(ev.Name),\n arg1: Expression.NewArrayInit(typeof(object), eventParams.Select(p => Expression.Convert(p, typeof(object))))),\n eventParams);\n ev.AddEventHandler(source, eventHandler.Compile());\n}\n OnRaised void OnRaised(string name, object[] parameters);\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1111/"
] |
45,783 |
<p>My team is currently trying to automate the deployment of our .Net and PHP web applications. We want to streamline deployments, and to avoid the hassle and many of the headaches caused by doing it manually.</p>
<p>We require a solution that will enable us to:</p>
<pre><code>- Compile the application
- Version the application with the SVN version number
- Backup the existing site
- Deploy to a web farm
</code></pre>
<p>All our apps are source controlled using SVN and our .Net apps use CruiseControl.
We have been trying to use MSBuild and NAnt deployment scripts with limited success. We have also used Capistrano in the past, but wish to avoid using Ruby if possible.</p>
<p>Are there any other deployment tools out there that would help us?</p>
|
[
{
"answer_id": 70621,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 1,
"selected": false,
"text": "msdeploy -verb:sync -source:dirpath=\\\\build\\e$\\app -dest:dirpath=\\\\live\\d$\\app,ignoreAcls=true\n ... > E:\\archive\\msdeploy.log\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4734/"
] |
45,792 |
<p>I've had some trouble forking of processes from a Perl CGI script when running on Windows. The main issue seems to be that 'fork' is emulated when running on windows, and doesn't actually seem to create a new process (just another thread in the current one). This means that web servers (like IIS) which are waiting for the process to finish continue waiting until the 'background' process finishes.</p>
<p>Is there a way of forking off a background process from a CGI script under Windows? Even better, is there a single function I can call which will do this in a cross platform way?</p>
<p>(And just to make life extra difficult, I'd really like a good way to redirect the forked processes output to a file at the same time).</p>
|
[
{
"answer_id": 49216535,
"author": "Jeffrey Tackett",
"author_id": 6789640,
"author_profile": "https://Stackoverflow.com/users/6789640",
"pm_score": 0,
"selected": false,
"text": " (All the CGI code that is standard stuff. Calls the subroutine needed, and then)\n\n my $randnum = int(rand(100000));\n my $callcmd = $progdir_path . \"/aoff-caller.pl --uniqueid $uuid --region $region --ticketid $ticketid\";\n my $daemon = Proc::Daemon->new(\n work_dir => $progdir_path,\n child_STDOUT => $tmpdir_path . '/stdout.txt',\n child_STDERR => $tmpdir_path . '/stderr.txt',\n pid_file => $tmpdir_path . '/' . $randnum . '-pid.txt',\n exec_command => $callcmd,\n );\n my $pid = $daemon->Init();\n\n exit 0;\n\n (kill CGI at the appropriate place)\n use Proc::Daemon"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] |
45,796 |
<p>Our ASP.NET 3.5 website running on IIS 6 has two teams that are adding content: </p>
<ul>
<li>Development team adding code. </li>
<li>Business team adding simple web pages. </li>
</ul>
<p>For sanity and organization, we would like for the business team to add their web pages to a sub-folder in the project: </p>
<blockquote>
<p>Root: for pages of development team </p>
<p>Content: for pages of business team </p>
</blockquote>
<p><strong>But</strong> </p>
<p>We would like for users to be able to navigate to the business team content without having to append "Content" in their URLs, as described below:</p>
<blockquote>
<p><strong>Root</strong>: Default.aspx (<em>Available at: www.oursite.com/default.aspx</em>)</p>
<p><strong>Content</strong>: Popcorn.aspx (<em>Available at: www.oursite.com/popcorn.aspx</em>)</p>
</blockquote>
<p>Is there a way we can accomplish for making a config entry in an ISAPI rewrite tool for every one of these pages?</p>
|
[
{
"answer_id": 45926,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 2,
"selected": true,
"text": "RewriteCond %{REQUEST_FILENAME} -!f\nRewriteCond Content/%{REQUEST_FILENAME} -f\nRewriteRule (.*) Content/(.*)\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/308/"
] |
45,803 |
<ol>
<li>Video podcast</li>
<li>???</li>
<li>Audio only mp3 player</li>
</ol>
<p>I'm looking for somewhere which will extract audio from video, but instead of a single file, for an on going video podcast.</p>
<p>I would most like a website which would suck in the RSS and spit out an RSS (I'm thinking of something like Feedburner), though would settle for something on my own machine.</p>
<p>If it must be on my machine, it should be quick, transparent, and automatic when I download each episode. </p>
<p>What would you use?</p>
<p><b>Edit:</b> I'm on an Ubuntu 8.04 machine; so running ffmpeg is no problem; however, I'm looking for automation and feed awareness.</p>
<p>Here's my use case: I want to listen to <a href="http://video.google.com/videosearch?q=google+techtalks&so=1&output=rss" rel="nofollow noreferrer">lectures</a> at Google Video, or <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow noreferrer">Structure and Interpretation of Computer Programs</a>. These videos come out fairly often, so anything that's needed to be done manually will also be done fairly often. </p>
<p>Here's one approach I'd thought of:</p>
<ul>
<li>download the RSS</li>
<li>parse the RSS for enclosures, </li>
<li>download the enclosures, keeping a track what has already been downloaded previously</li>
<li>transcode the files, but not the ones done already</li>
<li>reconstruct an RSS with the audio files, remembering to change the metadata.</li>
<li>schedule to be run periodically</li>
<li>point podcatcher at new RSS feed.</li>
</ul>
<p>I also liked the approach of gPodder of using a <a href="http://wiki.gpodder.org/wiki/Time_stretching#Using_the_post-download_script_hook" rel="nofollow noreferrer">post-download script</a>.</p>
<p>I wish the <a href="http://www.openp2p.com/pub/a/p2p/2003/01/07/lazyweb.html" rel="nofollow noreferrer">Lazy Web</a> still worked.</p>
|
[
{
"answer_id": 45823,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 4,
"selected": true,
"text": "ffmpeg -i episode1.mov -ab 128000 episode1.mp3\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4737/"
] |
45,813 |
<p>Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?</p>
|
[
{
"answer_id": 182363,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 6,
"selected": true,
"text": "Visual [VisualTreeHelper.]HitTest HitTestResultCallback HitTest Visual HitTestResultBehavior Callback(HitTestResult result)\n HitTestResultBehaviour.Continue // Return the result of the hit test to the callback.\npublic HitTestResultBehavior MyHitTestResult(HitTestResult result)\n{\n // Add the hit test result to the list that will be processed after the enumeration.\n hitResultsList.Add(result.VisualHit);\n\n // Set the behavior to return visuals at all z-order levels.\n return HitTestResultBehavior.Continue;\n}\n VisualTreeHelper.HitTest"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
45,824 |
<p>I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate. </p>
<p>I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers.</p>
<p>I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any?</p>
|
[
{
"answer_id": 45835,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "<link href=\"empty.css?log=example.html\" rel=\"stylesheet\" type=\"text/css\" />\n"
},
{
"answer_id": 45844,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 1,
"selected": false,
"text": "<script type=\"javascript\">\ndocument.write('<iframe src=\"myLogScript.php\" style=\"visibility:hidden\" width=\"1\" height=\"1\" frameborder=\"0\">');\n</script>\n"
},
{
"answer_id": 61076,
"author": "TomG",
"author_id": 6315,
"author_profile": "https://Stackoverflow.com/users/6315",
"pm_score": 1,
"selected": false,
"text": " <script type=\"text/javascript\">\n var thePg=window.location.pathname;\n var theSite=window.location.hostname;\n var theImage=new Image;\n theImage.src=\"/test/hitcounter.php?pg=\" + thePg + \"?site=\" + theSite;\n </script>\n <img> <iframe> 10.1.1.17 - - [13/Sep/2008:22:21:00 -0400] \"GET /test/testpage.html HTTP/1.1\" 200 306 \"-\" \"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16\"\n10.1.1.17 - - [13/Sep/2008:22:21:00 -0400] \"GET /test/hitcounter.php?pg=/test/testpage.html?site=www.home.***.com HTTP/1.1\" 301 - \"http://www.home.***.com/test/testpage.html\" \"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16\"\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] |
45,827 |
<p>How do you automatically set the focus to a textbox when a web page loads?</p>
<p>Is there an HTML tag to do it or does it have to be done via Javascript?</p>
|
[
{
"answer_id": 45833,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": false,
"text": "<BODY onLoad=\"document.getElementById('myButton').focus();\">\n function addLoadEvent(func) {\n var oldonload = window.onload;\n if (typeof window.onload != 'function') {\n window.onload = func;\n } else {\n window.onload = function() {\n if (oldonload) {\n oldonload();\n }\n func();\n }\n }\n}\n"
},
{
"answer_id": 45843,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<html> \n<head> \n<script language=\"javascript\" type=\"text/javascript\"> \nfunction SetFocus(InputID) \n{ \n document.getElementById(InputID).focus(); \n} \n</script> \n</head> \n<body onload=\"SetFocus('Box2')\"> \n<input id=\"Box1\" size=\"30\" /><br/> \n<input id=\"Box2\" size=\"30\" /> \n</body> \n</html> \n"
},
{
"answer_id": 45863,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 9,
"selected": true,
"text": "$(function() {\n $(\"#Box1\").focus();\n});\n Event.observe(window, 'load', function() {\n $(\"Box1\").focus();\n});\n window.onload = function() {\n document.getElementById(\"Box1\").focus();\n};\n"
},
{
"answer_id": 45887,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": 4,
"selected": false,
"text": "<input type='text' id='txtMyInputBox' />\n\n\n<script language='javascript' type='text/javascript'>\nfunction SetFocus()\n{\n // safety check, make sure its a post 1999 browser\n if (!document.getElementById)\n {\n return;\n }\n\n var txtMyInputBoxElement = document.getElementById(\"txtMyInputBox\");\n\n if (txtMyInputBoxElement != null)\n {\n txtMyInputBoxElement.focus();\n }\n}\nSetFocus();\n</script>\n protected void PageLoad(object sender, EventArgs e)\n{\n Page.SetFocus(txtMyInputBox);\n}\n Protected Sub PageLoad(sender as Object, e as EventArgs)\n\n Page.SetFocus(txtMyInputBox)\n\nEnd Sub\n"
},
{
"answer_id": 3043784,
"author": "dave1010",
"author_id": 315435,
"author_profile": "https://Stackoverflow.com/users/315435",
"pm_score": 7,
"selected": false,
"text": "autofocus <input id=\"my-input\" autofocus=\"autofocus\" />\n<script>\n if (!(\"autofocus\" in document.createElement(\"input\"))) {\n document.getElementById(\"my-input\").focus();\n }\n</script>\n autofocus"
},
{
"answer_id": 3316361,
"author": "revive",
"author_id": 225230,
"author_profile": "https://Stackoverflow.com/users/225230",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function() {\n $('input:text[value=\"\"]:visible:enabled:first').focus();\n});\n"
},
{
"answer_id": 7265423,
"author": "Amir Chatrbahr",
"author_id": 922713,
"author_profile": "https://Stackoverflow.com/users/922713",
"pm_score": 4,
"selected": false,
"text": "<script type=\"text/javascript\">\n\n $(document).ready(function () {\n $(\"#myTextBoxId\").focus();\n });\n\n</script>\n $(document).ready()"
},
{
"answer_id": 12821915,
"author": "srikanth",
"author_id": 1735238,
"author_profile": "https://Stackoverflow.com/users/1735238",
"pm_score": -1,
"selected": false,
"text": "jQuery(\"[id$='hfSpecialty_ids']\").focus()\n"
},
{
"answer_id": 40920357,
"author": "Chris Moschini",
"author_id": 176877,
"author_profile": "https://Stackoverflow.com/users/176877",
"pm_score": 2,
"selected": false,
"text": "autofocus placeholder placeholder autofocus var urlInput = $('#Url');\n\nfunction bodyFirstKey(ev) {\n $('body').off('keydown', bodyFirstKey);\n urlInput.off('focus', urlInputFirstFocus);\n\n if (ev.target == document.body) {\n urlInput.focus();\n if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {\n urlInput.val(ev.key);\n return false;\n }\n }\n};\nfunction urlInputFirstFocus() {\n $('body').off('keydown', bodyFirstKey);\n urlInput.off('focus', urlInputFirstFocus);\n};\n\n$('body').keydown(bodyFirstKey);\nurlInput.focus(urlInputFirstFocus);\n"
},
{
"answer_id": 40920516,
"author": "Andrew Morton",
"author_id": 1115360,
"author_profile": "https://Stackoverflow.com/users/1115360",
"pm_score": -1,
"selected": false,
"text": "yourControlName.Focus()\n"
},
{
"answer_id": 41675311,
"author": "Arjun",
"author_id": 7409227,
"author_profile": "https://Stackoverflow.com/users/7409227",
"pm_score": 4,
"selected": false,
"text": " <input name=\"abc\" autofocus></input>\n"
},
{
"answer_id": 58286168,
"author": "oscar castellon",
"author_id": 1283517,
"author_profile": "https://Stackoverflow.com/users/1283517",
"pm_score": 2,
"selected": false,
"text": "autofocus <input type=\"text\" class=\"b_calle\" id=\"b_calle\" placeholder=\"Buscar por nombre de calle\" autofocus=\"autofocus\">\n"
},
{
"answer_id": 70608454,
"author": "tdahman1325",
"author_id": 11580142,
"author_profile": "https://Stackoverflow.com/users/11580142",
"pm_score": 0,
"selected": false,
"text": "<input type=\"text\" id=\"my-input\" />\n if (!(document.getElementById(\"my-input\").hasAttribute(\"autofocus\"))) {\n document.getElementById(\"my-input\").focus();\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
45,861 |
<p>I am using <a href="http://code.google.com/p/js2-mode/" rel="noreferrer">js2-mode</a> to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.</p>
|
[
{
"answer_id": 7957258,
"author": "john_fries",
"author_id": 998684,
"author_profile": "https://Stackoverflow.com/users/998684",
"pm_score": 3,
"selected": false,
"text": ".emacs (setq js2-mode-hook\n '(lambda () (progn\n (set-variable 'indent-tabs-mode nil))))\n"
},
{
"answer_id": 30416044,
"author": "user1629060",
"author_id": 1629060,
"author_profile": "https://Stackoverflow.com/users/1629060",
"pm_score": 3,
"selected": false,
"text": "(setq-default indent-tabs-mode nil)\n (custom-set-variables\n ;; custom-set-variables was added by Custom.\n ;; If you edit it by hand, you could mess it up, so be careful.\n ;; Your init file should contain only one such instance.\n ;; If there is more than one, they won't work right.\n '(indent-tabs-mode nil))\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
] |
45,865 |
<p>I'm writing a wizard for an Eclipse RCP application. After doing some processing on a file and taking some user input, I don't want to let the user go back to make changes. At this point they must either accept or reject the changes they are about to make to the system.</p>
<p>What I can't seem to find is a method call that lets me override the buttons that display or the user's ability to hit the back button. I'd prefer that it not be there or at least be disabled.</p>
<p>Has anyone found a way to do this using the <a href="http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/wizard/package-summary.html" rel="noreferrer">JFace Wizard</a> and <a href="http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/jface/wizard/package-summary.html" rel="noreferrer">WizardPage</a>?</p>
<p>Usability-wise, am I breaking wizard conventions? Should I consider a different approach to the problem?</p>
|
[
{
"answer_id": 6780595,
"author": "Nick Sawadsky",
"author_id": 856583,
"author_profile": "https://Stackoverflow.com/users/856583",
"pm_score": 3,
"selected": false,
"text": "public abstract class MyWizardPage extends WizardPage {\n private boolean backButtonEnabled = true;\n\n public void setBackButtonEnabled(boolean enabled) {\n backButtonEnabled = enabled;\n getContainer().updateButtons();\n }\n\n @Override\n public IWizardPage getPreviousPage() {\n if (!backButtonEnabled) {\n return null;\n }\n return super.getPreviousPage();\n }\n}\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4513/"
] |
45,888 |
<p>I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's <code>text</code>, <code>value</code>, and <code>selected</code> properties, but I don't think that javascript's built in <code>Array.sort()</code> would work correctly.</p>
|
[
{
"answer_id": 45890,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 3,
"selected": false,
"text": "function sortSelect(selectToSort) {\n var arrOptions = [];\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n arrOptions[i] = [];\n arrOptions[i][0] = selectToSort.options[i].value;\n arrOptions[i][1] = selectToSort.options[i].text;\n arrOptions[i][2] = selectToSort.options[i].selected;\n }\n\n arrOptions.sort();\n\n for (var i = 0; i < selectToSort.options.length; i++) {\n selectToSort.options[i].value = arrOptions[i][0];\n selectToSort.options[i].text = arrOptions[i][1];\n selectToSort.options[i].selected = arrOptions[i][2];\n }\n}\n"
},
{
"answer_id": 45971,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "Array.sort() [\"value\", \"text\", \"selected\"] \"value, text, selected\" arrOptions.sort(function(a,b) { return new Number(a[0]) - new Number(b[0]); });\n"
},
{
"answer_id": 45974,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 3,
"selected": false,
"text": "jQuery.fn.sort = function() {\n return this.pushStack( [].sort.apply( this, arguments ), []);\n};\n function sortSelect(selectToSort) {\n jQuery(selectToSort.options).sort(function(a,b){ \n return a.value > b.value ? 1 : -1; \n });\n}\n"
},
{
"answer_id": 1885355,
"author": "Mark",
"author_id": 3915,
"author_profile": "https://Stackoverflow.com/users/3915",
"pm_score": 8,
"selected": true,
"text": "var my_options = $(\"#my_select option\");\nvar selected = $(\"#my_select\").val();\n\nmy_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n if (a.text < b.text) return -1;\n return 0\n})\n\n$(\"#my_select\").empty().append( my_options );\n$(\"#my_select\").val(selected);\n text text.toLowerCase() my_options.sort(function(a,b) {\n return a.text.localeCompare(b.text);\n});\n"
},
{
"answer_id": 4745818,
"author": "Tom Maeckelberghe",
"author_id": 1421542,
"author_profile": "https://Stackoverflow.com/users/1421542",
"pm_score": 4,
"selected": false,
"text": "$('#your_select_box').sort_select_box();\n $.fn.sort_select_box = function(){\n var my_options = $(\"#\" + this.attr('id') + ' option');\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n })\n return my_options;\n}\n"
},
{
"answer_id": 5432746,
"author": "JaredC",
"author_id": 339532,
"author_profile": "https://Stackoverflow.com/users/339532",
"pm_score": 4,
"selected": false,
"text": "$('#your_select_box').sort_select_box();\n $.fn.sort_select_box = function(){\n // Get options from select box\n var my_options = $(\"#\" + this.attr('id') + ' option');\n // sort alphabetically\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n })\n //replace with sorted my_options;\n $(this).empty().append( my_options );\n\n // clearing any selections\n $(\"#\"+this.attr('id')+\" option\").attr('selected', false);\n}\n"
},
{
"answer_id": 7236274,
"author": "João",
"author_id": 711756,
"author_profile": "https://Stackoverflow.com/users/711756",
"pm_score": 1,
"selected": false,
"text": "$.fn.sort_select_box = function(){\n var my_options = $(\"option\", $(this));\n my_options.sort(function(a,b) {\n if (a.text > b.text) return 1;\n else if (a.text < b.text) return -1;\n else return 0\n });\n $(this).empty().append(my_options);\n}\n\n// Usando:\n$(\"select#ProdutoFornecedorId\", $($context)).sort_select_box();\n"
},
{
"answer_id": 11196096,
"author": "Juan Perez",
"author_id": 1480913,
"author_profile": "https://Stackoverflow.com/users/1480913",
"pm_score": 2,
"selected": false,
"text": "$.fn.sortSelect = function() {\n var op = this.children(\"option\");\n op.sort(function(a, b) {\n return a.text > b.text ? 1 : -1;\n })\n return this.empty().append(op);\n}\n $(\"#my_select\").sortSelect();\n"
},
{
"answer_id": 12307006,
"author": "Tom Pietrosanti",
"author_id": 412074,
"author_profile": "https://Stackoverflow.com/users/412074",
"pm_score": 4,
"selected": false,
"text": "$.fn.sortOptions = function(){\n $(this).each(function(){\n var op = $(this).children(\"option\");\n op.sort(function(a, b) {\n return a.text > b.text ? 1 : -1;\n })\n return $(this).empty().append(op);\n });\n}\n $(\"select\").sortOptions();\n"
},
{
"answer_id": 59665960,
"author": "Adambean",
"author_id": 1372355,
"author_profile": "https://Stackoverflow.com/users/1372355",
"pm_score": 1,
"selected": false,
"text": "<OPTGROUP> $.fn.sortSelect = function(options){\n\n const OPTIONS_DEFAULT = {\n recursive: true, // Recurse into <optgroup>\n reverse: false, // Reverse order\n useValues: false, // Use values instead of text for <option> (<optgruop> is always label based)\n blankFirst: true, // Force placeholder <option> with empty value first, ignores reverse\n }\n\n if (typeof options != \"object\" || null === options) {\n options = OPTIONS_DEFAULT;\n }\n\n var sortOptions = function($root, $node, options){\n\n if ($node.length != 1) {\n return false;\n }\n\n if ($node[0].tagName != \"SELECT\" && $node[0].tagName != \"OPTGROUP\") {\n return false;\n }\n\n if (options.recursive) {\n $node.children('optgroup').each(function(k, v){\n return sortOptions($root, $(v), options);\n });\n }\n\n var $options = $node.children('option, optgroup');\n var $optionsSorted = $options.sort(function(a, b){\n\n if (options.blankFirst) {\n if (a.tagName == \"OPTION\" && a.value == \"\") {\n return -1;\n }\n\n if (b.tagName == \"OPTION\" && b.value == \"\") {\n return 1;\n }\n }\n\n var textA = (a.tagName == \"OPTION\" ? (options.useValues ? a.value : a.text) : a.label);\n var textB = (b.tagName == \"OPTION\" ? (options.useValues ? a.value : b.text) : b.label);\n\n if (textA > textB) {\n return options.reverse ? -1 : 1;\n }\n\n if (textA < textB) {\n return options.reverse ? 1 : -1;\n }\n\n return 0;\n\n });\n\n $options.remove();\n $optionsSorted.appendTo($node);\n\n return true;\n\n };\n\n var selected = $(this).val();\n var sorted = sortOptions($(this), $(this), {...OPTIONS_DEFAULT, ...options});\n $(this).val(selected);\n\n return sorted;\n\n};\n sortSelect() <SELECT> <OPTGROUP> $('select').sortSelect();\n $('select').sortSelect({\n reverse: true\n});\n $('select.js-sort').each(function(k, v){\n $(v).sortSelect();\n});\n"
},
{
"answer_id": 68092097,
"author": "CARLOS AGUIRRE",
"author_id": 10980978,
"author_profile": "https://Stackoverflow.com/users/10980978",
"pm_score": 0,
"selected": false,
"text": "function sortOptionsByText(a,b) {\n // I keep an empty value option on top, b.value comparison to 0 might not be necessary if empty value is always on top...\n if (a.value.length==0 || (b.value.length>0 && a.text <= b.text)) return -1; // no sort: a, b\n return 1; // sort switches places: b, a\n}\nfunction sortOptionsByValue(a,b) {\n if (a.value <= b.value) return -1; // a, b\n return 1; // b, a\n}\nfunction clearChildren(elem) {\n if (elem) {\n while (elem.firstChild) {\n elem.removeChild(elem.firstChild);\n }\n }\n}\nfunction sortSelectElem(sel,byText) {\n const val=sel.value;\n const tmp=[...sel.options];\n tmp.sort(byText?sortOptionsByText:sortOptionsByValue);\n clearChildren(sel);\n sel.append(...tmp);\n sel.value=val;\n} RACE: <select id=\"list\" size=\"6\">\n <option value=\"\">--PICK ONE--</option>\n <option value=\"1\">HUMANOID</option>\n <option value=\"2\">AMPHIBIAN</option>\n <option value=\"3\">REPTILE</option>\n <option value=\"4\">INSECTOID</option>\n</select><br>\n<button type=\"button\" onclick=\"sortSelectElem(document.getElementById('list'));\">SORT LIST BY VALUE</button><br>\n<button type=\"button\" onclick=\"sortSelectElem(document.getElementById('list'),true);\">SORT LIST BY TEXT</button>"
},
{
"answer_id": 69577409,
"author": "lisandro",
"author_id": 2363940,
"author_profile": "https://Stackoverflow.com/users/2363940",
"pm_score": 0,
"selected": false,
"text": "$(document).ready(function(){\n \n var $list = $(\"#my_select\");\n var selected = $(\"#my_select\").val(); //save selected value\n \n $list.children().detach().sort(function(a, b) {\n return $(a).text().localeCompare($(b).text());\n }).appendTo($list); //do the sorting locale for latin chars\n \n $(\"#my_select\").val(selected); //select previous selected value\n\n});\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] |
45,898 |
<p>In an application that I'm writing I have some code like this:</p>
<pre><code>NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";
NSURL* url = [NSURL URLWithString:myurl];
[ws openURL:url];
</code></pre>
<p>The main difference being that <em>myurl</em> comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning <em>nil</em>.</p>
<p>What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?</p>
|
[
{
"answer_id": 45905,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "http://www.somewebsite.com/method?a=%25d\n"
},
{
"answer_id": 8665933,
"author": "nverinaud",
"author_id": 855846,
"author_profile": "https://Stackoverflow.com/users/855846",
"pm_score": 1,
"selected": false,
"text": "stringByAddingPercentEscapesUsingEncoding:\n @interface NSURL (SmartEncoding)\n+ (NSURL *)smartURLWithString:(NSString *)str;\n@end\n\n@implementation NSURL (SmartEncoding)\n\n+ (NSURL *)smartURLWithString:(NSString *)str\n{\n CFStringRef preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(\"\"), kCFStringEncodingUTF8);\n if (!preprocessed) \n preprocessed = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (CFStringRef)str, CFSTR(\"\"), kCFStringEncodingASCII);\n\n if (!preprocessed)\n return [NSURL URLWithString:str];\n\n CFStringRef sanitized = CFURLCreateStringByAddingPercentEscapes(NULL, preprocessed, NULL, NULL, kCFStringEncodingUTF8);\n CFRelease(preprocessed);\n NSURL *result = (NSURL*)CFURLCreateWithString(NULL, sanitized, NULL);\n CFRelease(sanitized);\n return [result autorelease];\n}\n\n@end\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2998/"
] |
45,904 |
<p><strong>Situation:</strong></p>
<p>I have a simple <em>XML</em> document that contains image information. I need to transform it into <em>HTML</em>. However, I can't see where the open tag is and when I use the <em>XSL</em> code below, it shows the following error message: </p>
<blockquote>
<p>"Cannot write an attribute node when no element start tag is open."</p>
</blockquote>
<p><strong>XML content:</strong></p>
<pre><code><root>
<HeaderText>
<HeaderText>Dan Testing</HeaderText>
</HeaderText>
<Image>
<img width="100" height="100" alt="FPO lady" src="/uploadedImages/temp_photo_small.jpg"/>
</Image>
<BodyText>
<p>This is a test of the body text<br /></p>
</BodyText>
<ShowLinkArrow>false</ShowLinkArrow>
</root>
</code></pre>
<p><strong>XSL code:</strong></p>
<pre><code><xsl:stylesheet version="1.0" extension-element-prefixes="msxsl"
exclude-result-prefixes="msxsl js dl" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:js="urn:custom-javascript" xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:dl="urn:datalist">
<xsl:output method="xml" version="1.0" omit-xml-declaration="yes" indent="yes" encoding="utf-8"/>
<xsl:template match="/" xml:space="preserve">
<img>
<xsl:attribute name="width">
100
</xsl:attribute>
<xsl:attribute name="height">
100
</xsl:attribute>
<xsl:attribute name="class">
CalloutRightPhoto
</xsl:attribute>
<xsl:attribute name="src">
<xsl:copy-of select="/root/Image/node()"/>
</xsl:attribute>
</img>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
[
{
"answer_id": 45912,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<xsl:value-of select=\"/root/Image/img/@src\"/>\n"
},
{
"answer_id": 45955,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<xsl:attribute name=\"src\">\n <xsl:copy-of select=\"/root/Image/node()\"/>\n</xsl:attribute>\n <img width=\"100\" height=\"100\" src=\"{/root/Image/node()}\" class=\"CalloutRightPhoto\"/>\n"
},
{
"answer_id": 12581814,
"author": "m_cheung",
"author_id": 582032,
"author_profile": "https://Stackoverflow.com/users/582032",
"pm_score": 0,
"selected": false,
"text": "<img width=\"100\" height=\"100\" src=\"/root/Image/image.jpeg\" class=\"CalloutRightPhoto\"/>\n"
}
] |
2008/09/05
|
[
"https://Stackoverflow.com/questions/45904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.