qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
35,700 |
<p>What things should be kept most in mind when writing cross-platform applications in C? Targeted platforms: 32-bit Intel based PC, Mac, and Linux. I'm especially looking for the type of versatility that Jungle Disk has in their USB desktop edition ( <a href="http://www.jungledisk.com/desktop/download.aspx" rel="noreferrer">http://www.jungledisk.com/desktop/download.aspx</a> )</p>
<p>What are tips and "gotchas" for this type of development?</p>
|
[
{
"answer_id": 372091,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 0,
"selected": false,
"text": "int c;\nfread(&c, sizeof(int), 1, file);\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] |
35,743 |
<p>According to <a href="http://msdn.microsoft.com/en-us/library/bb386454.aspx" rel="noreferrer">Microsoft</a> the FileUpload control is not compatible with an AJAX UpdatePanel. </p>
<p>I am aware that a PostBackTrigger can be added to the submit button of the form like this:</p>
<pre><code><Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</code></pre>
<p>The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh?</p>
|
[
{
"answer_id": 36859,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 2,
"selected": false,
"text": "AJAX HTML iframe"
},
{
"answer_id": 217722,
"author": "user10859",
"author_id": 10859,
"author_profile": "https://Stackoverflow.com/users/10859",
"pm_score": 2,
"selected": false,
"text": "OnClientClick=\"javascript:document.forms[0].encoding = 'multipart/form-data';\"\n <form id=\"form1\" runat=\"server\" enctype=\"multipart/form-data\">\n"
},
{
"answer_id": 9537496,
"author": "Houston77mr",
"author_id": 1245623,
"author_profile": "https://Stackoverflow.com/users/1245623",
"pm_score": -1,
"selected": false,
"text": "UseSubmitBehavior clsUploadButton.UseSubmitBehavior = False;\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3677/"
] |
35,753 |
<p>Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). </p>
<p>Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?</p>
<p>What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.</p>
|
[
{
"answer_id": 35759,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "assert"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
] |
35,785 |
<p>What is the Java analogue of .NET's XML serialization?</p>
|
[
{
"answer_id": 4067429,
"author": "so_mv",
"author_id": 186858,
"author_profile": "https://Stackoverflow.com/users/186858",
"pm_score": 4,
"selected": false,
"text": "FREE Simple"
},
{
"answer_id": 18681762,
"author": "Mishax",
"author_id": 1766655,
"author_profile": "https://Stackoverflow.com/users/1766655",
"pm_score": 3,
"selected": false,
"text": "public class NPair {\n public NPair() { }\n int number1 = 0;\n int number2 = 0;\n public void setNumber1(int value) { number1 = value;}\n public int getNumber1() { return number1; }\n public void setNumber2(int value) { number2 = value; }\n public int getNumber2() {return number2;}\n}\n NPair fe = new NPair();\nfe.setNumber1(12);\nfe.setNumber2(13);\nFileOutputStream fos1 = new FileOutputStream(\"d:\\\\ser.xml\");\njava.beans.XMLEncoder xe1 = new java.beans.XMLEncoder(fos1);\nxe1.writeObject(fe);\nxe1.close();\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<java version=\"1.7.0_02\" class=\"java.beans.XMLDecoder\">\n <object class=\"NPair\">\n <void property=\"number1\">\n <int>12</int>\n </void>\n <void property=\"number2\">\n <int>13</int>\n </void>\n </object>\n</java>\n"
},
{
"answer_id": 26011571,
"author": "user4067649",
"author_id": 4067649,
"author_profile": "https://Stackoverflow.com/users/4067649",
"pm_score": -1,
"selected": false,
"text": "public static String genXmlTag(String tagName, String innerXml, String properties )\n{\n return String.format(\"<%s %s>%s</%s>\", tagName, properties, innerXml, tagName);\n}\n\npublic static String genXmlTag(String tagName, String innerXml )\n{\n return genXmlTag(tagName, innerXml, \"\");\n}\n\npublic static <T> String serializeXML(List<T> list)\n{\n String result = \"\";\n if (list.size() > 0)\n {\n T tmp = list.get(0);\n String clsName = tmp.getClass().getName();\n String[] splitCls = clsName.split(\"\\\\.\");\n clsName = splitCls[splitCls.length - 1];\n Field[] fields = tmp.getClass().getFields();\n\n for (T t : list)\n {\n String row = \"\";\n try {\n for (Field f : fields)\n {\n Object value = f.get(t);\n row += genXmlTag(f.getName(), value == null ? \"\" : value.toString());\n }\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n row = genXmlTag(clsName, row);\n\n result += row;\n }\n }\n\n result = genXmlTag(\"root\", result);\n return result;\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
] |
35,805 |
<p>If I create a class <code>A</code> as follows:</p>
<pre><code>class A:
def __init__(self):
self.name = 'A'
</code></pre>
<p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p>
<p>If however I create a class <code>B</code>:</p>
<pre><code>class B:
name = 'B'
</code></pre>
<p><code>__dict__</code> is empty.</p>
<p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
|
[
{
"answer_id": 35823,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 7,
"selected": true,
"text": "B.name B.__dict__ b = B(); b.__dict__ b.name B.name"
},
{
"answer_id": 39755,
"author": "Tendayi Mawushe",
"author_id": 2979,
"author_profile": "https://Stackoverflow.com/users/2979",
"pm_score": 4,
"selected": false,
"text": "class A:\n def _ _init_ _(self):\n self.name = 'A'\na = A()\n a.__dict__ class B:\n name = 'B'\nb = B()\n B.__dict__ b.__class__.__dict__"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154/"
] |
35,817 |
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p>
<p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p>
<pre><code>def sh_escape(s):
return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")
os.system("cat %s | grep something | sort > %s"
% (sh_escape(in_filename),
sh_escape(out_filename)))
</code></pre>
<p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p>
<p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
|
[
{
"answer_id": 35857,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 8,
"selected": true,
"text": "def shellquote(s):\n return \"'\" + s.replace(\"'\", \"'\\\\''\") + \"'\"\n"
},
{
"answer_id": 35858,
"author": "Jamie",
"author_id": 3363,
"author_profile": "https://Stackoverflow.com/users/3363",
"pm_score": 6,
"selected": false,
"text": "os.system() subprocess Replacing shell pipe line\n-------------------------\n\noutput=`dmesg | grep hda`\n==>\np1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n"
},
{
"answer_id": 847800,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 7,
"selected": false,
"text": "shlex.quote() pipes.quote pipes"
},
{
"answer_id": 1884718,
"author": "John Wiseman",
"author_id": 122762,
"author_profile": "https://Stackoverflow.com/users/122762",
"pm_score": 3,
"selected": false,
"text": ">>> from pipes import quote\n>>> args = ['arg1', '', 'arg3']\n>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))\nmycommand arg1 arg3\n"
},
{
"answer_id": 3851646,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "def quote_argument(argument):\n return '\"%s\"' % (\n argument\n .replace('\\\\', '\\\\\\\\')\n .replace('\"', '\\\\\"')\n .replace('$', '\\\\$')\n .replace('`', '\\\\`')\n )\n"
},
{
"answer_id": 10750633,
"author": "Gary Shi",
"author_id": 626160,
"author_profile": "https://Stackoverflow.com/users/626160",
"pm_score": 4,
"selected": false,
"text": "subprocess.list2cmdline"
},
{
"answer_id": 29597408,
"author": "Rockallite",
"author_id": 2293304,
"author_profile": "https://Stackoverflow.com/users/2293304",
"pm_score": 2,
"selected": false,
"text": "pipes.quote() shlex.quote() subprocess.list2cmdline() import sys\nmswindows = (sys.platform == \"win32\")\n\nif mswindows:\n from subprocess import list2cmdline\n quote_args = list2cmdline\nelse:\n # POSIX\n from pipes import quote\n\n def quote_args(seq):\n return ' '.join(quote(arg) for arg in seq)\n # Quote a single argument\nprint quote_args(['my argument'])\n\n# Quote multiple arguments\nmy_args = ['This', 'is', 'my arguments']\nprint quote_args(my_args)\n"
},
{
"answer_id": 70669446,
"author": "Flimm",
"author_id": 247696,
"author_profile": "https://Stackoverflow.com/users/247696",
"pm_score": 0,
"selected": false,
"text": "shlex.quote * import os\nimport shlex\n\nos.system(\"rm \" + shlex.quote(filename))\n ../../etc/passwd os.system(\"rm \" + shlex.quote(filename)) /etc/passwd rm -f -- ./-f rm if os.sep in filename:\n raise Exception(\"Did not expect to find file path separator in file name\")\n\nos.system(\"rm -- \" + shlex.quote(filename))\n"
},
{
"answer_id": 72750573,
"author": "Matthew Roberts",
"author_id": 4276963,
"author_profile": "https://Stackoverflow.com/users/4276963",
"pm_score": 0,
"selected": false,
"text": "\ndef win_arg_escape(arg, allow_vars=0):\n allowed_list = \"\"\"'\"/\\\\abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-. \"\"\"\n if allow_vars:\n allowed_list += \"~%$\"\n\n # Filter out anything that isn't a\n # standard character.\n buf = \"\"\n for ch in arg:\n if ch in allowed_list:\n buf += ch\n\n # Escape all slashes.\n buf = buf.replace(\"\\\\\", \"\\\\\\\\\")\n\n # Escape double quotes.\n buf = buf.replace('\"', '\"\"')\n\n # Surround entire arg with quotes.\n # This avoids spaces breaking a command.\n buf = '\"%s\"' % (buf)\n\n return buf\n\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
35,837 |
<p>I've been using git for some time now on Windows (with msysGit) and I like the idea of distributed source control. Just recently I've been looking at Mercurial (hg) and it looks interesting. However, I can't wrap my head around the differences between hg and git.</p>
<p>Has anyone made a side-by-side comparison between git and hg? I'm interested to know what differs hg and git without having to jump into a fanboy discussion.</p>
|
[
{
"answer_id": 892688,
"author": "Martin Geisler",
"author_id": 110204,
"author_profile": "https://Stackoverflow.com/users/110204",
"pm_score": 8,
"selected": false,
"text": "git-instaweb.sh git fetch <project-to-union-merge>\nGIT_INDEX_FILE=.git/tmp-index git-read-tree FETCH_HEAD\nGIT_INDEX_FILE=.git/tmp-index git-checkout-cache -a -u\ngit-update-cache --add -- (GIT_INDEX_FILE=.git/tmp-index git-ls-files)\ncp .git/FETCH_HEAD .git/MERGE_HEAD\ngit commit\n hg pull --force <project-to-union-merge>\nhg merge\nhg commit\n --force hg pull"
},
{
"answer_id": 8268798,
"author": "gman",
"author_id": 128511,
"author_profile": "https://Stackoverflow.com/users/128511",
"pm_score": 4,
"selected": false,
"text": "o o---o---o\n / \no---o---o---o---o---o---o---o\n \\ /\n o---o---o\n o---o---o---o---o\n\no---o---o---o\n \\\n o---o\n\no---o---o---o\n $ time git checkout -b some-new-branch\nSwitched to new branch 'some-new-branch'\n\nreal 0m1.759s\nuser 0m1.596s\nsys 0m0.144s\n $ time hg clone project/ some-clone/\n\nupdating to branch default\n29387 files updated, 0 files merged, 0 files removed, 0 files unresolved.\nreal 0m58.196s\nuser 0m19.901s\nsys 0m8.957\n cp -r project project-clone git checkout master\ngit checkout -b add-2nd-joypad-support\ngit checkout master\ngit checkout -b fix-game-save-bug\ngit checkout master\ngit checkout -b add-a-star-support\n git checkout fix-game-save-bug\n git commit -a git add joypad.cpp // copies to stage\ngit commit -m \"added 2nd joypad support\"\ngit add gamesave.cpp // copies to stage\ngit commit -m \"fixed game save bug\"\n"
},
{
"answer_id": 11186287,
"author": "Kostas",
"author_id": 129363,
"author_profile": "https://Stackoverflow.com/users/129363",
"pm_score": 1,
"selected": false,
"text": " $ hg rollback $ git reset --soft HEAD^ hg serve "
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
] |
35,842 |
<p>How do I get the id of my Java process? </p>
<p>I know there are several platform-dependent hacks, but I would prefer a more generic solution.</p>
|
[
{
"answer_id": 35885,
"author": "Wouter Coekaerts",
"author_id": 3432,
"author_profile": "https://Stackoverflow.com/users/3432",
"pm_score": 10,
"selected": true,
"text": "ManagementFactory.getRuntimeMXBean().getName() \"12345@hostname\" 12345 long pid = ProcessHandle.current().pid();\n"
},
{
"answer_id": 42970,
"author": "Ryan P",
"author_id": 1539,
"author_profile": "https://Stackoverflow.com/users/1539",
"pm_score": 2,
"selected": false,
"text": "String jps = [JDK HOME] + \"\\\\bin\\\\jps.exe\";\nProcess p = Runtime.getRuntime().exec(jps);\n"
},
{
"answer_id": 3134967,
"author": "Ashwin Jayaprakash",
"author_id": 257122,
"author_profile": "https://Stackoverflow.com/users/257122",
"pm_score": 5,
"selected": false,
"text": "private Sigar sigar;\n\npublic synchronized Sigar getSigar() {\n if (sigar == null) {\n sigar = new Sigar();\n }\n return sigar;\n}\n\npublic synchronized void forceRelease() {\n if (sigar != null) {\n sigar.close();\n sigar = null;\n }\n}\n\npublic long getPid() {\n return getSigar().getPid();\n}\n"
},
{
"answer_id": 6372205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "private static String getPid() throws IOException {\n byte[] bo = new byte[256];\n InputStream is = new FileInputStream(\"/proc/self/stat\");\n is.read(bo);\n for (int i = 0; i < bo.length; i++) {\n if ((bo[i] < '0') || (bo[i] > '9')) {\n return new String(bo, 0, i);\n }\n }\n return \"-1\";\n}\n"
},
{
"answer_id": 7303433,
"author": "Luke Quinane",
"author_id": 18437,
"author_profile": "https://Stackoverflow.com/users/18437",
"pm_score": 7,
"selected": false,
"text": "jna-platform.jar int pid = Kernel32.INSTANCE.GetCurrentProcessId();\n private interface CLibrary extends Library {\n CLibrary INSTANCE = (CLibrary) Native.loadLibrary(\"c\", CLibrary.class); \n int getpid ();\n}\n int pid = CLibrary.INSTANCE.getpid();\n long pid = ProcessHandle.current().pid();\n"
},
{
"answer_id": 7309009,
"author": "Jared",
"author_id": 928992,
"author_profile": "https://Stackoverflow.com/users/928992",
"pm_score": 3,
"selected": false,
"text": "sun.java.launcher.pid JMX bean"
},
{
"answer_id": 7690178,
"author": "Martin",
"author_id": 66981,
"author_profile": "https://Stackoverflow.com/users/66981",
"pm_score": 5,
"selected": false,
"text": "java.lang.management.ManagementFactory private static String getProcessId(final String fallback) {\n // Note: may fail in some JVM implementations\n // therefore fallback has to be provided\n\n // something like '<pid>@<hostname>', at least in SUN / Oracle JVMs\n final String jvmName = ManagementFactory.getRuntimeMXBean().getName();\n final int index = jvmName.indexOf('@');\n\n if (index < 1) {\n // part before '@' empty (index = 0) / '@' not found (index = -1)\n return fallback;\n }\n\n try {\n return Long.toString(Long.parseLong(jvmName.substring(0, index)));\n } catch (NumberFormatException e) {\n // ignore\n }\n return fallback;\n}\n getProcessId(\"<PID>\")"
},
{
"answer_id": 12066696,
"author": "Brad Mace",
"author_id": 446591,
"author_profile": "https://Stackoverflow.com/users/446591",
"pm_score": 6,
"selected": false,
"text": "java.lang.management.RuntimeMXBean runtime = \n java.lang.management.ManagementFactory.getRuntimeMXBean();\njava.lang.reflect.Field jvm = runtime.getClass().getDeclaredField(\"jvm\");\njvm.setAccessible(true);\nsun.management.VMManagement mgmt = \n (sun.management.VMManagement) jvm.get(runtime);\njava.lang.reflect.Method pid_method = \n mgmt.getClass().getDeclaredMethod(\"getProcessId\");\npid_method.setAccessible(true);\n\nint pid = (Integer) pid_method.invoke(mgmt);\n"
},
{
"answer_id": 17348465,
"author": "Espinosa",
"author_id": 1185845,
"author_profile": "https://Stackoverflow.com/users/1185845",
"pm_score": 2,
"selected": false,
"text": "sun.jvmstat.monitor.* tool.jar package my.code.a003.process;\n\nimport sun.jvmstat.monitor.HostIdentifier;\nimport sun.jvmstat.monitor.MonitorException;\nimport sun.jvmstat.monitor.MonitoredHost;\nimport sun.jvmstat.monitor.MonitoredVm;\nimport sun.jvmstat.monitor.MonitoredVmUtil;\nimport sun.jvmstat.monitor.VmIdentifier;\n\n\npublic class GetOwnPid {\n\n public static void main(String[] args) {\n new GetOwnPid().run();\n }\n\n public void run() {\n System.out.println(getPid(this.getClass()));\n }\n\n public Integer getPid(Class<?> mainClass) {\n MonitoredHost monitoredHost;\n Set<Integer> activeVmPids;\n try {\n monitoredHost = MonitoredHost.getMonitoredHost(new HostIdentifier((String) null));\n activeVmPids = monitoredHost.activeVms();\n MonitoredVm mvm = null;\n for (Integer vmPid : activeVmPids) {\n try {\n mvm = monitoredHost.getMonitoredVm(new VmIdentifier(vmPid.toString()));\n String mvmMainClass = MonitoredVmUtil.mainClass(mvm, true);\n if (mainClass.getName().equals(mvmMainClass)) {\n return vmPid;\n }\n } finally {\n if (mvm != null) {\n mvm.detach();\n }\n }\n }\n } catch (java.net.URISyntaxException e) {\n throw new InternalError(e.getMessage());\n } catch (MonitorException e) {\n throw new InternalError(e.getMessage());\n }\n return null;\n }\n}\n tool.jar tool.jar tool.jar"
},
{
"answer_id": 19091039,
"author": "Subhash",
"author_id": 864111,
"author_profile": "https://Stackoverflow.com/users/864111",
"pm_score": -1,
"selected": false,
"text": "netstat -tupln | grep portNumber\n"
},
{
"answer_id": 21702291,
"author": "tomsv",
"author_id": 246622,
"author_profile": "https://Stackoverflow.com/users/246622",
"pm_score": 2,
"selected": false,
"text": "SIGAR import org.hyperic.sigar.Sigar;\n\nSigar sigar = new Sigar();\nlong pid = sigar.getPid();\nsigar.close();\n"
},
{
"answer_id": 28981466,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": "getpid()"
},
{
"answer_id": 31072610,
"author": "ZhekaKozlov",
"author_id": 706317,
"author_profile": "https://Stackoverflow.com/users/706317",
"pm_score": 4,
"selected": false,
"text": "public abstract class Process {\n\n ...\n\n public long getPid();\n}\n ProcessHandle System.out.println(ProcessHandle.current().pid());\n"
},
{
"answer_id": 33573952,
"author": "PartialData",
"author_id": 2989079,
"author_profile": "https://Stackoverflow.com/users/2989079",
"pm_score": -1,
"selected": false,
"text": "public static boolean isPIDInUse(int pid) {\n\n try {\n\n String s = null;\n int java_pid;\n\n RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();\n java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf(\"@\")));\n\n if (java_pid == pid) {\n System.out.println(\"In Use\\n\");\n return true;\n }\n } catch (Exception e) {\n System.out.println(\"Exception: \" + e.getMessage());\n }\n return false;\n }\n"
},
{
"answer_id": 33837794,
"author": "Florin T.",
"author_id": 5000738,
"author_profile": "https://Stackoverflow.com/users/5000738",
"pm_score": 3,
"selected": false,
"text": "import sys.process._\nval pid: Long = Seq(\"sh\", \"-c\", \"echo $PPID\").!!.trim.toLong\n"
},
{
"answer_id": 38122943,
"author": "AntiTiming",
"author_id": 4635513,
"author_profile": "https://Stackoverflow.com/users/4635513",
"pm_score": 3,
"selected": false,
"text": "String jvmName = ManagementFactory.getRuntimeMXBean().getName();\nreturn jvmName.split(\"@\")[0];\n int pid = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]);\n ApplicationPid pid = new ApplicationPid();\npid.toString();\n"
},
{
"answer_id": 39744535,
"author": "JaskeyLam",
"author_id": 2087628,
"author_profile": "https://Stackoverflow.com/users/2087628",
"pm_score": 3,
"selected": false,
"text": "public static long getPID() {\n String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();\n if (processName != null && processName.length() > 0) {\n try {\n return Long.parseLong(processName.split(\"@\")[0]);\n }\n catch (Exception e) {\n return 0;\n }\n }\n\n return 0;\n}\n"
},
{
"answer_id": 43399977,
"author": "markus",
"author_id": 2250186,
"author_profile": "https://Stackoverflow.com/users/2250186",
"pm_score": 4,
"selected": false,
"text": "java.lang.management.ManagementFactory.getRuntimeMXBean().getName().split(\"@\")[0]\n"
},
{
"answer_id": 48959178,
"author": "mrsrinivas",
"author_id": 1592191,
"author_profile": "https://Stackoverflow.com/users/1592191",
"pm_score": 3,
"selected": false,
"text": "process id final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();\nfinal long pid = runtime.getPid();\nout.println(\"Process ID is '\" + pid);\n"
},
{
"answer_id": 52130795,
"author": "Armin Bu",
"author_id": 2587809,
"author_profile": "https://Stackoverflow.com/users/2587809",
"pm_score": 0,
"selected": false,
"text": "public static void main(String[] args) {\n NodeJS nodeJS = NodeJS.createNodeJS();\n int pid = nodeJS.getRuntime().executeIntegerScript(\"process.pid;\\n\");\n System.out.println(pid);\n nodeJS.release();\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
] |
35,848 |
<p>I have a VB6.0 project and I want to convert it in VB.Net.</p>
<p>In my VB6.0 application some of the MDI Child form’s height is 17000 and width is 13000. Now I want to set the same form size in VB.Net forms, but it allows maximum form width = 1036, height = 780 for resolution 1024x768.</p>
<p>How can I increase form size with same resolution?</p>
<p>Also I want to print this from so, I can not use auto scroll property of vb.net forms.</p>
<p>Thaks</p>
|
[
{
"answer_id": 154479,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 1,
"selected": false,
"text": "Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n Me.Height = 17000 'or whatever you need\n Me.Width = 13000\nEnd Sub\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35848",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2528/"
] |
35,849 |
<p>So we've discussed logging in passing at my place of work and I was wondering if some of you guys here could give me some ideas of your approaches?</p>
<p>Typically our scenario is, no logging really at all, and mostly .NET apps, winforms/WPF clients talking through web services or direct to a db.</p>
<p>So, the real question is, where or what would you log? At the moment we have users reporting error messages - so I would assume log startups/shutdowns, exceptions...</p>
<p>Do you take it to calls to the web services or db? Page loads?</p>
<p>How do you get a good idea of what the user was trying to do at the time?</p>
<p>Is it better to go all the way and log everything across multiple attempts/days, or log only what you need to (given hdd is cheap).</p>
<p>I guess that's a few questions, but I wanted to get more of an idea of what the actual practice is out there in larger shops!</p>
|
[
{
"answer_id": 35875,
"author": "Tristan Juricek",
"author_id": 3436,
"author_profile": "https://Stackoverflow.com/users/3436",
"pm_score": 1,
"selected": false,
"text": "info(\"waaah\") warning(\"waah\")"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3717/"
] |
35,870 |
<p>I have a list of more than 15 thousand latitude and longitude coordinates. Given any X,Y coordinates, what is the fastest way to find the closest coordinates on the list?</p>
|
[
{
"answer_id": 35946,
"author": "Jeremy",
"author_id": 3657,
"author_profile": "https://Stackoverflow.com/users/3657",
"pm_score": 3,
"selected": false,
"text": "select *\n from dealers\n where latitude >= minlat\n and latitude <= maxlat\n and longitude >= minlong\n and longitude <= maxlong\n"
},
{
"answer_id": 400516,
"author": "Dylan",
"author_id": 49920,
"author_profile": "https://Stackoverflow.com/users/49920",
"pm_score": 1,
"selected": false,
"text": "SELECT network_id, ST_Length(geometry) from spatial_table where ST_Length(geometry) < 10;\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3725/"
] |
35,879 |
<p>I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have?</p>
<p>I am only familiar with PHP</p>
|
[
{
"answer_id": 35891,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 7,
"selected": true,
"text": " <?php\n $im = file_get_contents('filename.gif');\n $imdata = base64_encode($im); \n?> \n <img width=\"16\" height=\"16\">data:image/x-icon;base64,imageData</>\n imageData"
},
{
"answer_id": 318624,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 3,
"selected": false,
"text": "data:{mimetype};base64, url() src img data:image/... base64 $ base64 imagefile.ico > imagefile.base64.txt image/png image/jpeg image/gif image/x-icon image/vnd.microsoft.icon data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=\n\ndata:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==\n"
},
{
"answer_id": 9742151,
"author": "thefreeman",
"author_id": 920113,
"author_profile": "https://Stackoverflow.com/users/920113",
"pm_score": 4,
"selected": false,
"text": "$encoded_data = base64_encode(file_get_contents('path-to-your-image.jpg')); \n"
},
{
"answer_id": 32372709,
"author": "Imran Kabir",
"author_id": 3860369,
"author_profile": "https://Stackoverflow.com/users/3860369",
"pm_score": 3,
"selected": false,
"text": "// First get your image\n$imgPath = 'path-to-your-picture/image.jpg';\n$img = base64_encode(file_get_contents($imgPath));\necho '<img width=\"100\" height=\"100\" src=\"data:image/jpg;base64,'. $img .'\" />'\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
35,896 |
<p>Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx" rel="noreferrer">System.Media.SoundPlayer</a> can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with <a href="https://github.com/mono/csvorbis" rel="noreferrer">csvorbis</a> but I don't know how to play it afterwards).</p>
<p>I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.</p>
<p>[this question is a follow up to a <a href="http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html" rel="noreferrer">mailing list discussion on mono-dev</a> mailing list a year ago]</p>
|
[
{
"answer_id": 36050,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 4,
"selected": true,
"text": "System.Media.SoundPlayer using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read))\n{\n var player = new SoundPlayer(new OggDecodeStream(file));\n player.PlaySync();\n}\n SoundPlayer System.Diagnostics.Process.Start(\"fullPath.mp3\");"
},
{
"answer_id": 130628,
"author": "Trap",
"author_id": 7839,
"author_profile": "https://Stackoverflow.com/users/7839",
"pm_score": 1,
"selected": false,
"text": " //\n // Summary:\n // Starts a process resource by specifying the name of a document or application\n // file and associates the resource with a new System.Diagnostics.Process component.\n //\n // Parameters:\n // fileName:\n // The name of a document or application file to run in the process.\n //\n // Returns:\n // A new System.Diagnostics.Process component that is associated with the process\n // resource, or null, if no process resource is started (for example, if an\n // existing process is reused).\n //\n // Exceptions:\n // System.ComponentModel.Win32Exception:\n // There was an error in opening the associated file.\n //\n // System.ObjectDisposedException:\n // The process object has already been disposed.\n //\n // System.IO.FileNotFoundException:\n // The PATH environment variable has a string containing quotes.\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
35,905 |
<p>I've created a few <code>autorun</code> script files on various USB devices that run <code>bash</code> scripts when they mount. These scripts run "in the background", how do I get them to run in a terminal window? (Like the "Application in Terminal" gnome Launcher type.)</p>
|
[
{
"answer_id": 35924,
"author": "Vagnerr",
"author_id": 3720,
"author_profile": "https://Stackoverflow.com/users/3720",
"pm_score": 4,
"selected": true,
"text": "gnome-terminal -e top --title Testing\n"
},
{
"answer_id": 35925,
"author": "Steve Moon",
"author_id": 3660,
"author_profile": "https://Stackoverflow.com/users/3660",
"pm_score": 1,
"selected": false,
"text": "xterm -e shellscript.sh\n xterm gnome-terminal -e shellscript.sh\n konsole -e shellscript.sh\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
35,914 |
<p>Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like:</p>
<pre><code>Process.Start("Sample.xls");
</code></pre>
<p>However, I need to pass some command line arguments as well. I couldn't get this to work</p>
<pre><code> Process p = new Process();
p.StartInfo.FileName = "Sample.xls";
p.StartInfo.Arguments = "/r"; // open in read-only mode
p.Start();
</code></pre>
<p>Any suggestions on a mechanism to solve this?</p>
<p><strong>Edit</strong> @ aku</p>
<p>My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks!</p>
|
[
{
"answer_id": 35930,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": true,
"text": "Process.Start"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2258/"
] |
35,922 |
<p>I've played around with GTK, TK, wxPython, Cocoa, curses and others. They are are fairly horrible to use.. GTK/TK/wx/curses all seem to basically be direct-ports of the appropriate C libraries, and Cocoa basically mandates using both PyObjC and Interface Builder, both of which I dislike..</p>
<p>The Shoes GUI library for Ruby is great.. It's very sensibly designed, and very "rubyish", and borrows some nice-to-use things from web development (like using hex colours codes, or <code>:color => rgb(128,0,0)</code>)</p>
<p>As the title says: are there any nice, "Pythonic" GUI toolkits?</p>
|
[
{
"answer_id": 106696,
"author": "Ed Leafe",
"author_id": 19399,
"author_profile": "https://Stackoverflow.com/users/19399",
"pm_score": 4,
"selected": false,
"text": "obj.BackColor = \"red\"\nobj.BackColor = (255, 0, 0)\nobj.BackColor = \"FF0000\"\nobj.BackColor = \"#FF0000\"\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
35,948 |
<p>I'm using Google App Engine and Django templates.<br>
I have a table that I want to display the objects look something like:<br></p>
<pre><code>Object Result:
Items = [item1,item2]
Users = [{name='username',item1=3,item2=4},..]
</code></pre>
<p>The Django template is:</p>
<pre><code><table>
<tr align="center">
<th>user</th>
{% for item in result.items %}
<th>{{item}}</th>
{% endfor %}
</tr>
{% for user in result.users %}
<tr align="center">
<td>{{user.name}}</td>
{% for item in result.items %}
<td>{{ user.item }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</code></pre>
<p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="noreferrer">Django documention</a> states that when it sees a <strong>.</strong> in variables<br>
It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
|
[
{
"answer_id": 35978,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "{{ user.item }} \"item\" item {{ user.name }} name user name"
},
{
"answer_id": 37190,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 0,
"selected": false,
"text": "{{ user.item }}\n {{ item }}\n"
},
{
"answer_id": 50425,
"author": "Yon",
"author_id": 3117,
"author_profile": "https://Stackoverflow.com/users/3117",
"pm_score": 6,
"selected": true,
"text": "from google.appengine.ext import webapp\n\nregister = webapp.template.create_template_register()\n\ndef hash(h,key):\n if key in h:\n return h[key]\n else:\n return None\n\nregister.filter(hash)\n webapp.template.register_template_library('django_hack')\n {{ user|hash:item }}\n"
},
{
"answer_id": 1278623,
"author": "Brandon Henry",
"author_id": 112620,
"author_profile": "https://Stackoverflow.com/users/112620",
"pm_score": 2,
"selected": false,
"text": "* Dictionary lookup (e.e., foo[\"bar\"])\n* Attribute lookup (e.g., foo.bar)\n* Method call (e.g., foo.bar())\n* List-index lookup (e.g., foo[bar])\n"
},
{
"answer_id": 3125956,
"author": "Niall Farrington",
"author_id": 288710,
"author_profile": "https://Stackoverflow.com/users/288710",
"pm_score": 2,
"selected": false,
"text": "{% for pair in user.items %}\n {% for keyval in pair %} {{ keyval }}{% endfor %}<br>\n{% endfor %}\n"
},
{
"answer_id": 3466349,
"author": "Martyn",
"author_id": 418239,
"author_profile": "https://Stackoverflow.com/users/418239",
"pm_score": 3,
"selected": false,
"text": "from django.template import Variable, VariableDoesNotExist\[email protected]\ndef hash(object, attr):\n pseudo_context = { 'object' : object }\n try:\n value = Variable('object.%s' % attr).resolve(pseudo_context)\n except VariableDoesNotExist:\n value = None\nreturn value\n {{ user|hash:item }}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3117/"
] |
35,950 |
<p>I need an associative container that makes me index a certain object through a string, but that also keeps the order of insertion, so I can look for a specific object by its name or just iterate on it and retrieve objects in the same order I inserted them.</p>
<p>I think this <a href="http://www.ddj.com/cpp/184406207" rel="nofollow noreferrer">hybrid of linked list and hash map</a> should do the job, but before I tried to use <code>std::tr1::unordered_map</code> thinking that it was working in that way I described, but it wasn't. So could someone explain me the meaning and behavior of <code>unordered_map</code>?</p>
<hr>
<p>@wesc: I'm sure std::map is implemented by STL, while I'm sure std::hash_map is NOT in the STL (I think older version of Visual Studio put it in a namespace called stdext).</p>
<p>@cristopher: so, if I get it right, the difference is in the implementation (and thus performances), not in the way it behaves externally.</p>
|
[
{
"answer_id": 35965,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 3,
"selected": true,
"text": "operator< operator( key ) => index"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3373/"
] |
35,954 |
<p>I have a query that originally looks like this:</p>
<pre><code>select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode
from dbo.Customer as c
left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id
left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id
where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%'
or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%')
</code></pre>
<p>On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing). </p>
<p>I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term.</p>
<p>Is there a way to do this in full-text search?</p>
<hr>
<p>@David</p>
<p>Yep, there are indexes on the Ids.</p>
<p>I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this.</p>
<p>Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still.</p>
|
[
{
"answer_id": 35965,
"author": "Christopher",
"author_id": 3186,
"author_profile": "https://Stackoverflow.com/users/3186",
"pm_score": 3,
"selected": true,
"text": "operator< operator( key ) => index"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/372/"
] |
35,973 |
<p>What is the best approach to define additional data for typedef enums in C?</p>
<p>Example:</p>
<pre><code>typedef enum {
kVizsla = 0,
kTerrier = 3,
kYellowLab = 10
} DogType;
</code></pre>
<p>Now I would like to define names for each, for example <code>kVizsla</code> should be "vizsla".
I currently use a function that returns a string using a large switch block.</p>
|
[
{
"answer_id": 35998,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "char *DogList[] = {\n \"vizsla\", /* element 0 */\n NULL,\n NULL,\n NULL,\n \"terrier\", /* element 3 */\n ...\n};\n typedef struct DogMaps {\n DogType index;\n char * name;\n} DogMapt;\nDogMapt DogMap[] = {\n {kVizsla, \"vizsla\"},\n {kTerrier, \"terrier\"},\n {kYellowLab, \"yellow lab\"},\n NULL\n};\n"
},
{
"answer_id": 36075,
"author": "Hershi",
"author_id": 1596,
"author_profile": "https://Stackoverflow.com/users/1596",
"pm_score": 3,
"selected": true,
"text": "<EnumsDefinition>\n <Enum name=\"DogType\">\n <Value name=\"Vizsla\" value=\"0\" />\n <Value name=\"Terrier\" value=\"3\" />\n <Value name=\"YellowLab\" value=\"10\" />\n </Enum>\n</EnumsDefinition>\n"
},
{
"answer_id": 39816,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "// All dog data goes in this list\n#define XDOGTYPE \\\n X(kVizsla,0,\"vizsla\") \\\n X(kTerrier,3,\"terrier\") \\\n X(kYellowLab,10,\"yellowlab\")\n\n // Dog info\n typedef struct {\n int val; // Defined value\n char * desc; // Text description\n } DogType;\n\n // Build an array index using the Names\n typedef enum {\n #define X(Name,Val,Text) Name,\n XDOGTYPE\n #undef X\n MAXDOGS\n } DogIndex;\n\n // Build a lookup table of values\n DogType Dog[] = {\n #define X(Name,Val,Text) {Val,Text},\n XDOGTYPE\n #undef X\n };\n\n // Access the values\n for (i=0; i < MAXDOGS; i++)\n printf(\"%d: %s\\n\",Dog[i].val,Dog[i].desc);\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] |
35,974 |
<p>I'm working on an email solution in SQL Server ONLY that will use Database Mail to send out HTML formatted emails. The catch is that the images in the HTML need to be embedded in the outgoing email. This wouldn't be a problem if I were using a .net app to generate & send the emails but, unfortunately, all I have is SQL Server.</p>
<p>Is it possible for SQL Server to embed images on its own?</p>
|
[
{
"answer_id": 36173,
"author": "nathan_jr",
"author_id": 3769,
"author_profile": "https://Stackoverflow.com/users/3769",
"pm_score": 1,
"selected": false,
"text": "<img src=\"data:image/png;base64[your encoded image here...]"
},
{
"answer_id": 166446,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 2,
"selected": true,
"text": "@file_attachment sp_send_dbmail"
},
{
"answer_id": 179602,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<img src=\"...\"> cid:"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
] |
35,983 |
<p>Let's say I have committed some bad changes to Subversion repository. Then I commit good changes, that I want to keep.</p>
<p>What would be easiest way to roll back those bad changes in Eclipse, and keep the good changes? Assuming that files relating to bad changes are not same as those relating to the good changes. How things change if good changes were made to same files as bad changes?</p>
<p>I am mostly looking a way to do this via Eclipse plugins (Subclipse or Subversive) but commandline commands are also interesting.</p>
|
[
{
"answer_id": 36063,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 6,
"selected": true,
"text": "Replace with... Latest from Repository Branch Merge svn revert svn merge"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] |
35,988 |
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p>
<pre><code>class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
</code></pre>
|
[
{
"answer_id": 35990,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 6,
"selected": false,
"text": "myStruct = {'field1': 'some val', 'field2': 'some val'}\n print myStruct['field1']\nmyStruct['field2'] = 'some other values'\n"
},
{
"answer_id": 35993,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 7,
"selected": false,
"text": ">>> class Bunch:\n... def __init__(self, **kwds):\n... self.__dict__.update(kwds)\n...\n>>> mystruct = Bunch(field1=value1, field2=value2)\n"
},
{
"answer_id": 36033,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 9,
"selected": false,
"text": "from collections import namedtuple\nMyStruct = namedtuple(\"MyStruct\", \"field1 field2 field3\")\n m = MyStruct(\"foo\", \"bar\", \"baz\")\n m = MyStruct(field1=\"foo\", field2=\"bar\", field3=\"baz\")\n"
},
{
"answer_id": 36061,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 4,
"selected": false,
"text": "# Abstract struct class \nclass Struct:\n def __init__ (self, *argv, **argd):\n if len(argd):\n # Update by dictionary\n self.__dict__.update (argd)\n else:\n # Update by position\n attrs = filter (lambda x: x[0:2] != \"__\", dir(self))\n for n in range(len(argv)):\n setattr(self, attrs[n], argv[n])\n\n# Specific class\nclass Point3dStruct (Struct):\n x = 0\n y = 0\n z = 0\n\npt1 = Point3dStruct()\npt1.x = 10\n\nprint pt1.x\nprint \"-\"*10\n\npt2 = Point3dStruct(5, 6)\n\nprint pt2.x, pt2.y\nprint \"-\"*10\n\npt3 = Point3dStruct (x=1, y=2, z=3)\nprint pt3.x, pt3.y, pt3.z\nprint \"-\"*10\n"
},
{
"answer_id": 3761729,
"author": "Jose M Balaguer",
"author_id": 454110,
"author_profile": "https://Stackoverflow.com/users/454110",
"pm_score": 6,
"selected": false,
"text": "class Sample:\n name = ''\n average = 0.0\n values = None # list cannot be initialized here!\n\n\ns1 = Sample()\ns1.name = \"sample 1\"\ns1.values = []\ns1.values.append(1)\ns1.values.append(2)\ns1.values.append(3)\n\ns2 = Sample()\ns2.name = \"sample 2\"\ns2.values = []\ns2.values.append(4)\n\nfor v in s1.values: # prints 1,2,3 --> OK.\n print v\nprint \"***\"\nfor v in s2.values: # prints 4 --> OK.\n print v\n"
},
{
"answer_id": 18792190,
"author": "Phlip",
"author_id": 193980,
"author_profile": "https://Stackoverflow.com/users/193980",
"pm_score": 4,
"selected": false,
"text": "class Map(dict):\n def __init__(self, **kwargs):\n super(Map, self).__init__(**kwargs)\n self.__dict__ = self\n struct = Map(field1='foo', field2='bar', field3=42)\n\nself.assertEquals('bar', struct.field2)\nself.assertEquals(42, struct['field3'])\n"
},
{
"answer_id": 26826089,
"author": "Sujal Sheth",
"author_id": 2042079,
"author_profile": "https://Stackoverflow.com/users/2042079",
"pm_score": 3,
"selected": false,
"text": "class cstruct:\n var_i = 0\n var_f = 0.0\n var_str = \"\"\n obj = cstruct()\nobj.var_i = 50\nobj.var_f = 50.00\nobj.var_str = \"fifty\"\nprint \"cstruct: obj i=%d f=%f s=%s\" %(obj.var_i, obj.var_f, obj.var_str)\n obj_array = [cstruct() for i in range(10)]\nobj_array[0].var_i = 10\nobj_array[0].var_f = 10.00\nobj_array[0].var_str = \"ten\"\n\n#go ahead and fill rest of array instaces of struct\n\n#print all the value\nfor i in range(10):\n print \"cstruct: obj_array i=%d f=%f s=%s\" %(obj_array[i].var_i, obj_array[i].var_f, obj_array[i].var_str)\n"
},
{
"answer_id": 29212925,
"author": "user124757",
"author_id": 4094380,
"author_profile": "https://Stackoverflow.com/users/4094380",
"pm_score": 3,
"selected": false,
"text": "__init__ class MyStruct(type):\n def __call__(cls, *args, **kwargs):\n names = cls.__init__.func_code.co_varnames[1:]\n\n self = type.__call__(cls, *args, **kwargs)\n\n for name, value in zip(names, args):\n setattr(self , name, value)\n\n for name, value in kwargs.iteritems():\n setattr(self , name, value)\n return self \n >>> class MyClass(object):\n __metaclass__ = MyStruct\n def __init__(self, a, b, c):\n pass\n\n\n>>> my_instance = MyClass(1, 2, 3)\n>>> my_instance.a\n1\n>>> \n >>> def init_all_args(fn):\n @wraps(fn)\n def wrapped_init(self, *args, **kwargs):\n names = fn.func_code.co_varnames[1:]\n\n for name, value in zip(names, args):\n setattr(self, name, value)\n\n for name, value in kwargs.iteritems():\n setattr(self, name, value)\n\n return wrapped_init\n\n>>> class Test(object):\n @init_all_args\n def __init__(self, a, b):\n pass\n\n\n>>> a = Test(1, 2)\n>>> a.a\n1\n>>> \n"
},
{
"answer_id": 31062667,
"author": "Ella Rose",
"author_id": 3103584,
"author_profile": "https://Stackoverflow.com/users/3103584",
"pm_score": 5,
"selected": false,
"text": ">>> from ctypes import *\n>>> class POINT(Structure):\n... _fields_ = [(\"x\", c_int),\n... (\"y\", c_int)]\n...\n>>> point = POINT(10, 20)\n>>> print point.x, point.y\n10 20\n>>> point = POINT(y=5)\n>>> print point.x, point.y\n0 5\n>>> POINT(1, 2, 3)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in ?\nValueError: too many initializers\n>>>\n>>> class RECT(Structure):\n... _fields_ = [(\"upperleft\", POINT),\n... (\"lowerright\", POINT)]\n...\n>>> rc = RECT(point)\n>>> print rc.upperleft.x, rc.upperleft.y\n0 5\n>>> print rc.lowerright.x, rc.lowerright.y\n0 0\n>>>\n"
},
{
"answer_id": 32448434,
"author": "ArtOfWarfare",
"author_id": 901641,
"author_profile": "https://Stackoverflow.com/users/901641",
"pm_score": 3,
"selected": false,
"text": "def argumentsToAttributes(method):\n argumentNames = method.func_code.co_varnames[1:]\n\n # Generate a dictionary of default values:\n defaultsDict = {}\n defaults = method.func_defaults if method.func_defaults else ()\n for i, default in enumerate(defaults, start = len(argumentNames) - len(defaults)):\n defaultsDict[argumentNames[i]] = default\n\n def newMethod(self, *args, **kwargs):\n # Use the positional arguments.\n for name, value in zip(argumentNames, args):\n setattr(self, name, value)\n\n # Add the key word arguments. If anything is missing, use the default.\n for name in argumentNames[len(args):]:\n setattr(self, name, kwargs.get(name, defaultsDict[name]))\n\n # Run whatever else the method needs to do.\n method(self, *args, **kwargs)\n\n return newMethod\n a b c self class A(object):\n @argumentsToAttributes\n def __init__(self, a, b = 'Invisible', c = 'Hello'):\n print(self.a)\n print(self.b)\n print(self.c)\n\nA('Why', c = 'Nothing')\n __init__"
},
{
"answer_id": 40488966,
"author": "Jason C",
"author_id": 616460,
"author_profile": "https://Stackoverflow.com/users/616460",
"pm_score": 3,
"selected": false,
"text": "class Employee:\n pass\n\njohn = Employee() # Create an empty employee record\n\n# Fill the fields of the record\njohn.name = 'John Doe'\njohn.dept = 'computer lab'\njohn.salary = 1000\n class Employee:\n def __init__ (self):\n self.name = None # or whatever\n self.dept = None\n self.salary = None\n john.slarly = 1000"
},
{
"answer_id": 44989925,
"author": "Yujun Li",
"author_id": 7963712,
"author_profile": "https://Stackoverflow.com/users/7963712",
"pm_score": 0,
"selected": false,
"text": "d = dict{}\nd[field1] = field1\nd[field2] = field2\nd[field2] = field3\n"
},
{
"answer_id": 45426493,
"author": "Rotareti",
"author_id": 1612318,
"author_profile": "https://Stackoverflow.com/users/1612318",
"pm_score": 9,
"selected": false,
"text": "from dataclasses import dataclass\n\n\n@dataclass\nclass Point:\n x: float\n y: float\n z: float = 0.0\n\n\np = Point(1.5, 2.5)\n\nprint(p) # Point(x=1.5, y=2.5, z=0.0)\n from typing import NamedTuple\n\n\nclass User(NamedTuple):\n name: str\n\n\nclass MyStruct(NamedTuple):\n foo: str\n bar: int\n baz: list\n qux: User\n\n\nmy_item = MyStruct('foo', 0, ['baz'], User('peter'))\n\nprint(my_item) # MyStruct(foo='foo', bar=0, baz=['baz'], qux=User(name='peter'))\n"
},
{
"answer_id": 45517161,
"author": "w_jay",
"author_id": 6776633,
"author_profile": "https://Stackoverflow.com/users/6776633",
"pm_score": 3,
"selected": false,
"text": "class Struct:\n \"A structure that can have any fields defined.\"\n def __init__(self, **entries): self.__dict__.update(entries)\n >>> options = Struct(answer=42, linelen=80, font='courier')\n>>> options.answer\n42\n >>> options.cat = \"dog\"\n>>> options.cat\ndog\n"
},
{
"answer_id": 47016739,
"author": "Galaxy",
"author_id": 159695,
"author_profile": "https://Stackoverflow.com/users/159695",
"pm_score": 2,
"selected": false,
"text": "class myStruct:\n def __init__(self, **kwds):\n self.x=0\n self.__dict__.update(kwds) # Must be last to accept assigned member variable.\n def __repr__(self):\n args = ['%s=%s' % (k, repr(v)) for (k,v) in vars(self).items()]\n return '%s(%s)' % ( self.__class__.__qualname__, ', '.join(args) )\n\na=myStruct()\nb=myStruct(x=3,y='test')\nc=myStruct(x='str')\n\n>>> a\nmyStruct(x=0)\n>>> b\nmyStruct(x=3, y='test')\n>>> c\nmyStruct(x='str')\n"
},
{
"answer_id": 47140549,
"author": "normanius",
"author_id": 3388962,
"author_profile": "https://Stackoverflow.com/users/3388962",
"pm_score": 2,
"selected": false,
"text": "class struct:\n def __init__(self, *sequential, **named):\n fields = dict(zip(sequential, [None]*len(sequential)), **named)\n self.__dict__.update(fields)\n def __repr__(self):\n return str(self.__dict__)\n # Struct with field1, field2, field3 that are initialized to None.\nmystruct1 = struct(\"field1\", \"field2\", \"field3\") \n# Struct with field1, field2, field3 that are initialized according to arguments.\nmystruct2 = struct(field1=1, field2=2, field3=3)\n print(mystruct2)\n# Prints: {'field3': 3, 'field1': 1, 'field2': 2}\n"
},
{
"answer_id": 49560899,
"author": "PS1",
"author_id": 9570787,
"author_profile": "https://Stackoverflow.com/users/9570787",
"pm_score": 2,
"selected": false,
"text": "_class_template = \"\"\"\\\nclass {typename}:\ndef __init__(self, *args, **kwargs):\n fields = {field_names!r}\n\n for x in fields:\n setattr(self, x, None) \n\n for name, value in zip(fields, args):\n setattr(self, name, value)\n\n for name, value in kwargs.items():\n setattr(self, name, value) \n\ndef __repr__(self):\n return str(vars(self))\n\ndef __setattr__(self, name, value):\n if name not in {field_names!r}:\n raise KeyError(\"invalid name: %s\" % name)\n object.__setattr__(self, name, value) \n\"\"\"\n\ndef struct(typename, field_names):\n\n class_definition = _class_template.format(\n typename = typename,\n field_names = field_names)\n\n namespace = dict(__name__='struct_%s' % typename)\n exec(class_definition, namespace)\n result = namespace[typename]\n result._source = class_definition\n\n return result\n Person = struct('Person', ['firstname','lastname'])\ngeneric = Person()\nmichael = Person('Michael')\njones = Person(lastname = 'Jones')\n\n\nIn [168]: michael.middlename = 'ben'\nTraceback (most recent call last):\n\n File \"<ipython-input-168-b31c393c0d67>\", line 1, in <module>\nmichael.middlename = 'ben'\n\n File \"<string>\", line 19, in __setattr__\n\nKeyError: 'invalid name: middlename'\n"
},
{
"answer_id": 49789270,
"author": "Oamar Kanji",
"author_id": 7055858,
"author_profile": "https://Stackoverflow.com/users/7055858",
"pm_score": 5,
"selected": false,
"text": "class Point:\n __slots__ = [\"x\", \"y\"]\n def __init__(self, x, y):\n self.x = x\n self.y = y\n class Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\np1 = Point(3,5)\np1.z = 8\nprint(p1.z)\n class Point:\n __slots__ = [\"x\", \"y\"]\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\np1 = Point(3,5)\np1.z = 8\n"
},
{
"answer_id": 53721171,
"author": "שמואל ביאליסטוקי",
"author_id": 9184115,
"author_profile": "https://Stackoverflow.com/users/9184115",
"pm_score": 2,
"selected": false,
"text": "cstruct2py typedef struct {\n int x;\n int y;\n} Point;\n\nafter generating pythonic class...\np = Point(x=0x1234, y=0x5678)\np.packed == \"\\x34\\x12\\x00\\x00\\x78\\x56\\x00\\x00\"\n import cstruct2py\nparser = cstruct2py.c2py.Parser()\nparser.parse_file('examples/example.h')\n parser.update_globals(globals())\n A = parser.parse_string('struct A { int x; int y;};')\n a = A()\na.x = 45\nprint a\nbuf = a.packed\nb = A(buf)\nprint b\nc = A('aaaa11112222', 2)\nprint c\nprint repr(c)\n {'x':0x2d, 'y':0x0}\n{'x':0x2d, 'y':0x0}\n{'x':0x31316161, 'y':0x32323131}\nA('aa111122', x=0x31316161, y=0x32323131)\n cstruct2py git clone https://github.com/st0ky/cstruct2py.git --recursive\n"
},
{
"answer_id": 54400995,
"author": "gebbissimo",
"author_id": 2135504,
"author_profile": "https://Stackoverflow.com/users/2135504",
"pm_score": 1,
"selected": false,
"text": "class Params():\n def __init__(self):\n self.var1 : int = None\n self.var2 : str = None\n\n def are_all_defined(self):\n for key, value in self.__dict__.items():\n assert (value is not None), \"instance variable {} is still None\".format(key)\n return True\n\n\nparams = Params()\nparams.var1 = 2\nparams.var2 = 'hello'\nassert(params.are_all_defined)\n"
},
{
"answer_id": 55591469,
"author": "jochen",
"author_id": 648741,
"author_profile": "https://Stackoverflow.com/users/648741",
"pm_score": 3,
"selected": false,
"text": "class myStruct:\n field1 = \"one\"\n field2 = \"2\"\n myStruct.field3 = 3\n >>> myStruct.field1\n'one'\n"
},
{
"answer_id": 58118444,
"author": "calandoa",
"author_id": 26074,
"author_profile": "https://Stackoverflow.com/users/26074",
"pm_score": 2,
"selected": false,
"text": ">>> ms = Warning()\n>>> ms.foo = 123\n>>> ms.bar = 'akafrit'\n Warning Exception ms = object()"
},
{
"answer_id": 61660221,
"author": "Tioneb",
"author_id": 8484485,
"author_profile": "https://Stackoverflow.com/users/8484485",
"pm_score": 1,
"selected": false,
"text": "class AttrDict(dict):\n def __init__(self, *args, **kwargs):\n super(AttrDict, self).__init__(*args, **kwargs)\n self.__dict__ = self\n def __dir__(self):\n return self.keys()\n my_struct=AttrDict ({\n 'com1':AttrDict ({\n 'inst':[0x05],\n 'numbytes':2,\n 'canpayload':False,\n 'payload':None\n })\n})\n print(my_struct.com1.inst) [5]"
},
{
"answer_id": 62212859,
"author": "Carson",
"author_id": 9935654,
"author_profile": "https://Stackoverflow.com/users/9935654",
"pm_score": 2,
"selected": false,
"text": "from typing import NamedTuple\nimport guppy # pip install guppy\nimport timeit\n\n\nclass User:\n def __init__(self, name: str, uid: int):\n self.name = name\n self.uid = uid\n\n\nclass UserSlot:\n __slots__ = ('name', 'uid')\n\n def __init__(self, name: str, uid: int):\n self.name = name\n self.uid = uid\n\n\nclass UserTuple(NamedTuple):\n # __slots__ = () # AttributeError: Cannot overwrite NamedTuple attribute __slots__\n name: str\n uid: int\n\n\ndef get_fn(obj, attr_name: str):\n def get():\n getattr(obj, attr_name)\n return get\n if 'memory test':\n obj = [User('Carson', 1) for _ in range(1000000)] # Cumulative: 189138883\n obj_slot = [UserSlot('Carson', 1) for _ in range(1000000)] # 77718299 <-- winner\n obj_namedtuple = [UserTuple('Carson', 1) for _ in range(1000000)] # 85718297\n print(guppy.hpy().heap()) # Run this function individually. \n \"\"\"\n Index Count % Size % Cumulative % Kind (class / dict of class)\n 0 1000000 24 112000000 34 112000000 34 dict of __main__.User\n 1 1000000 24 64000000 19 176000000 53 __main__.UserTuple\n 2 1000000 24 56000000 17 232000000 70 __main__.User\n 3 1000000 24 56000000 17 288000000 87 __main__.UserSlot\n ...\n \"\"\"\n\nif 'performance test':\n obj = User('Carson', 1)\n obj_slot = UserSlot('Carson', 1)\n obj_tuple = UserTuple('Carson', 1)\n\n time_normal = min(timeit.repeat(get_fn(obj, 'name'), repeat=20))\n print(time_normal) # 0.12550550000000005\n\n time_slot = min(timeit.repeat(get_fn(obj_slot, 'name'), repeat=20))\n print(time_slot) # 0.1368690000000008\n\n time_tuple = min(timeit.repeat(get_fn(obj_tuple, 'name'), repeat=20))\n print(time_tuple) # 0.16006120000000124\n\n print(time_tuple/time_slot) # 1.1694481584580898 # The slot is almost 17% faster than NamedTuple on Windows. (Python 3.7.7)\n\n __dict__ __slots__ NamedTuple __slots__"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3738/"
] |
35,991 |
<p>I'm considering using Django for a project I'm starting (fyi, a browser-based game) and one of the features I'm liking the most is using <code>syncdb</code> to automatically create the database tables based on the Django models I define (a feature that I can't seem to find in any other framework).
I was already thinking this was too good to be true when I saw this in the <a href="https://docs.djangoproject.com/en/dev/ref/django-admin/" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>Syncdb will not alter existing tables</p>
<p>syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.</p>
<p>If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.</p>
</blockquote>
<p>It seems that altering existing tables will have to be done "by hand".</p>
<p>What I would like to know is the best way to do this. Two solutions come to mind:</p>
<ul>
<li>As the documentation suggests, make the changes manually in the DB;</li>
<li>Do a backup of the database, wipe it, create the tables again (with syncdb, since now it's creating the tables from scratch) and import the backed-up data (this might take too long if the database is big)</li>
</ul>
<p>Any ideas?</p>
|
[
{
"answer_id": 36015,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": "initial_data django-admin.py dumpdata fixtures django-admin.py loaddata initial_data.json syncdb manage.py test"
},
{
"answer_id": 55716,
"author": "Garth Kidd",
"author_id": 5700,
"author_profile": "https://Stackoverflow.com/users/5700",
"pm_score": 2,
"selected": false,
"text": "schema_evolution.py BEFORE = 'fv1:-436177719' # first fingerprint\nBEFORE64 = 'fv1:-108578349625146375' # same, but on 64-bit Linux\nAFTER = 'fv1:-2132605944' \nAFTER64 = 'fv1:-3559032165562222486'\n\nfingerprints = [\n BEFORE, AFTER,\n BEFORE64, AFTER64,\n ]\n\nCHANGESQL = \"\"\"\n /* put your SQL code to make the changes here */\n \"\"\"\n\nevolutions = [\n ((BEFORE, AFTER), CHANGESQL),\n ((BEFORE64, AFTER64), CHANGESQL)\n ]\n"
},
{
"answer_id": 20640720,
"author": "Jan Wrobel",
"author_id": 1031601,
"author_profile": "https://Stackoverflow.com/users/1031601",
"pm_score": 2,
"selected": false,
"text": "manage.py migrate manage.py makemigrations migrate syncdb"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
35,999 |
<p>How can I execute <code>a.exe</code> using the Cygwin shell?</p>
<p>I created a C file in Eclipse on Windows and then used Cygwin to navigate to the directory. I called gcc on the C source file and <code>a.exe</code> was produced. I would like to run <code>a.exe</code>.</p>
|
[
{
"answer_id": 36006,
"author": "kaiz.net",
"author_id": 3714,
"author_profile": "https://Stackoverflow.com/users/3714",
"pm_score": -1,
"selected": false,
"text": "> a\n"
},
{
"answer_id": 36016,
"author": "Jason Weathered",
"author_id": 3736,
"author_profile": "https://Stackoverflow.com/users/3736",
"pm_score": 2,
"selected": false,
"text": "./foo ./a.exe -o cc cc helloworld.c -o helloworld.exe"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/35999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
36,001 |
<p>I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed?</p>
<pre><code>CREATE TABLE dbo.Profiles
(
UserName varchar(100) NOT NULL,
LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()),
FullName varchar(50) NOT NULL,
Birthdate smalldatetime NULL,
PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)),
CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC),
CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE
)
</code></pre>
|
[
{
"answer_id": 36068,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 5,
"selected": false,
"text": "CREATE TRIGGER KeepUpdated on Profiles\nFOR UPDATE, INSERT AS \nUPDATE dbo.Profiles \nSET LastUpdate = GetDate()\nWHERE Username IN (SELECT Username FROM inserted)\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36001",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
36,014 |
<p>I'm working on a project using the <a href="http://antlr.org" rel="noreferrer">ANTLR</a> parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p>
<p>The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:</p>
<pre>
Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C#
Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes
Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes
Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C#
Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C#
</pre>
<p>The code snippet from the bottom-most call in Parse() looks like:</p>
<pre><code> try {
// Execution stopped at parser.prog()
TimeDefParser.prog_return prog_ret = parser.prog();
return prog_ret == null ? null : prog_ret.value;
}
catch (Exception ex) {
throw new ParserException(ex.Message, ex);
}
</code></pre>
<p>To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?</p>
<p><strong>Update:</strong> I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.</p>
<p>Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.</p>
<p>One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.</p>
<p>Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.</p>
<p>Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?</p>
<p><strong>Update 2:</strong> I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.</p>
<p>I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.</p>
<p><strong>Update 3:</strong>
I've replicated this scenario in a <a href="http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip" rel="noreferrer">simplified VS 2008 project</a>. Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.</p>
<p>If you can find a workaround, please do share your findings. Thanks again!</p>
<hr>
<p>Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.</p>
<p>The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.</p>
|
[
{
"answer_id": 36047,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 3,
"selected": false,
"text": "using System.Threading;\n\n...\n\nvoid Application_ThreadException(object sender, ThreadExceptionEventArgs e) {\n throw new ParserException(e.Exception.Message, e.Exception);\n} \n\n ...\n\n var exceptionHandler = \n new ThreadExceptionEventHandler(Application_ThreadException);\n Application.ThreadException += exceptionHandler;\n try {\n // Execution stopped at parser.prog()\n TimeDefParser.prog_return prog_ret = parser.prog();\n return prog_ret == null ? null : prog_ret.value;\n }\n catch (Exception ex) {\n throw new ParserException(ex.Message, ex);\n }\n finally {\n Application.ThreadException -= exceptionHandler;\n }\n"
},
{
"answer_id": 36048,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);\n\n // Catch all unhandled exceptions in all threads.\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);\n"
},
{
"answer_id": 36069,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "AppDomain.CurrentDomain.UnhandledException \n"
},
{
"answer_id": 39606,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 0,
"selected": false,
"text": "IsValid()"
},
{
"answer_id": 40055,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 2,
"selected": false,
"text": "catch (System.Exception)\n"
},
{
"answer_id": 40828,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "class MyNoViableAltException : Exception\n{\n public MyNoViableAltException()\n {\n }\n public MyNoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, Antlr.Runtime.IIntStream input)\n {\n }\n}\nclass MyEarlyExitException : Exception\n{\n public MyEarlyExitException()\n {\n }\n\n public MyEarlyExitException(int decisionNumber, Antlr.Runtime.IIntStream input)\n {\n }\n}\n using NoViableAltException = MyNoViableAltException;\nusing EarlyExitException = NoViableAltException; \n try\n {\n alt4 = dfa4.Predict(input);\n }\n catch\n {\n }\n"
},
{
"answer_id": 630024,
"author": "Dave Turvey",
"author_id": 18966,
"author_profile": "https://Stackoverflow.com/users/18966",
"pm_score": 2,
"selected": false,
"text": "@members {\n\n public override Object RecoverFromMismatchedSet(IIntStream input,RecognitionException e, BitSet follow) \n {\n throw e;\n }\n}\n\n@rulecatch {\n catch (RecognitionException e) \n {\n throw e;\n }\n}\n"
},
{
"answer_id": 8946874,
"author": "Tony Schwartz",
"author_id": 1161343,
"author_profile": "https://Stackoverflow.com/users/1161343",
"pm_score": 3,
"selected": false,
"text": "ExternalClassNotMyCode c = new ExternalClassNotMyCode();\ntry {\n c.doSomething( () => { throw new Exception(); } );\n}\ncatch ( Exception ex ) {}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3347/"
] |
36,028 |
<p>How do I assign a method's output to a textbox value without code behind?</p>
<pre><code><%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Public TextFromString As String = "test text test text"
Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w")
Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer)
Return New String(Input, Count)
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Test Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%=TextFromString%>
<br />
<asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox>
<br />
<%=TextFromMethod%>
<br />
<asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox>
</div>
</form>
</body>
</html>
</code></pre>
<p>it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.</p>
<p>It's also confusing to me why</p>
<pre><code><asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label>
</code></pre>
<p>and</p>
<pre><code><asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox>
</code></pre>
<p>works but </p>
<pre><code><asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox>
</code></pre>
<p>causes a compilation error.</p>
|
[
{
"answer_id": 36164,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 1,
"selected": false,
"text": "<input type=\"text\" id=\"TextBox4\" runat=\"server\" value=\"<%=TextFromString%>\" />\n"
},
{
"answer_id": 36234,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 3,
"selected": true,
"text": "<%= TextFromMethod %>\n <%# TextFromMethod %>\n <%$ ConnectionStrings:Database %>\n <%= %> <%# %> TextBox.DataBind() Page.DataBind() Page_Load Private Function Page_Load(sender as Object, e as EventArgs)\n If Not IsPostback Then\n Me.DataBind()\n End If\nEnd Function\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
36,039 |
<p>C++ seems to be rather grouchy when declaring templates across multiple files. More specifically, when working with templated classes, the linker expect all method definitions for the class in a single compiler object file. When you take into account headers, other declarations, inheritance, etc., things get really messy. </p>
<p>Are there any general advice or workarounds for organizing or redistributing templated member definitions across multiple files?</p>
|
[
{
"answer_id": 94890,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 2,
"selected": false,
"text": "extern"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4381/"
] |
36,058 |
<p>I have a popup window containing a form which gathers data for a report.
When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup.</p>
<p>I think I can open the report in the correct window by using</p>
<pre><code>{ :target => <name of window> }
</code></pre>
<p>in the <code>form_tag</code>, but I don't know how to determine or set the name of the originating window.</p>
<p>I also don't know how to close the popup window.</p>
|
[
{
"answer_id": 36065,
"author": "Craig",
"author_id": 1611,
"author_profile": "https://Stackoverflow.com/users/1611",
"pm_score": 0,
"selected": false,
"text": "# The submit button in your child window's view:\n<%= button_to_function 'Save', \"$('my_form').submit(); window.opener.location.reload(); window.close();\" %> \n"
},
{
"answer_id": 36126,
"author": "Brent ",
"author_id": 3764,
"author_profile": "https://Stackoverflow.com/users/3764",
"pm_score": 0,
"selected": false,
"text": "<%= submit_tag \"Go!\", {:onClick => \"window.close()\"} %>\n"
},
{
"answer_id": 159813,
"author": "Steropes",
"author_id": 21872,
"author_profile": "https://Stackoverflow.com/users/21872",
"pm_score": 2,
"selected": false,
"text": ":target => window.opener.location.href=\"http://new_url\";\n window.close();\n"
},
{
"answer_id": 445882,
"author": "praveenjayapal",
"author_id": 38172,
"author_profile": "https://Stackoverflow.com/users/38172",
"pm_score": 0,
"selected": false,
"text": "function fclosepopup(){\nwindow.opener.location.replace=\"URL\";\nwindow.close();\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
36,064 |
<p>I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?</p>
|
[
{
"answer_id": 36206,
"author": "Dane O'Connor",
"author_id": 1946,
"author_profile": "https://Stackoverflow.com/users/1946",
"pm_score": 2,
"selected": false,
"text": "public static T ReadFromRequest < T > (this Controller controller, string key) \n{\n // Setup\n HttpContextBase context = controller.ControllerContext.HttpContext;\n object val = null;\n T result = default(T);\n\n // Gaurd\n if (context == null)\n return result; // no point checking request\n\n // Bind value (check form then query string)\n if (context.Request.Form[key] != null)\n val = context.Request.Form[key];\n if (val == null) \n {\n if (context.Request.QueryString[key] != null)\n val = context.Request.QueryString[key];\n }\n\n // Cast value\n if (val != null)\n result = (t)val;\n\n return result;\n}\n\n}\n"
},
{
"answer_id": 36209,
"author": "matt",
"author_id": 2646,
"author_profile": "https://Stackoverflow.com/users/2646",
"pm_score": 3,
"selected": true,
"text": "UpdateModel(object model, string[] keys)\n controller.ReadFromRequest"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3412/"
] |
36,077 |
<p>I'm looking for an answer in MS VC++.</p>
<p>When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.</p>
<p>Example in pseudo code:</p>
<pre><code>FunctionB()
{
...
throw e;
...
}
FunctionA()
{
...
FunctionB()
...
}
try
{
Function A()
}
catch(e)
{
(<--- breakpoint)
...
}
</code></pre>
<p>I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in <code>FunctionA()</code> or <code>FunctionB()</code>, or some other function. (Assuming extensive exception use and a huge version of the above example).</p>
<p>One solution to my problem is to determine and save the call stack <strong>in the exception constructor</strong> (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.</p>
<p>Is there an easier way that requires less work? Without having to change my large code base?</p>
<p>Are there better solutions to this problem in other languages?</p>
|
[
{
"answer_id": 36223,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 2,
"selected": false,
"text": "#include <execinfo.h> // Backtrace\n#include <cxxabi.h> // Demangling\n\nvector<Str> backtrace(size_t numskip) {\n vector<Str> result;\n std::vector<void*> bt(100);\n bt.resize(backtrace(&(*bt.begin()), bt.size()));\n char **btsyms = backtrace_symbols(&(*bt.begin()), bt.size());\n if (btsyms) {\n for (size_t i = numskip; i < bt.size(); i++) {\n Aiss in(btsyms[i]);\n int idx = 0; Astr nt, addr, mangled;\n in >> idx >> nt >> addr >> mangled;\n if (mangled == \"start\") break;\n int status = 0;\n char *demangled = abi::__cxa_demangle(mangled.c_str(), 0, 0, &status);\n\n Str frame = (status==0) ? Str(demangled, demangled+strlen(demangled)) : \n Str(mangled.begin(), mangled.end());\n result.push_back(frame);\n\n free(demangled);\n }\n free(btsyms);\n }\n return result;\n}\n numskip"
},
{
"answer_id": 36473,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 0,
"selected": false,
"text": "throw Exception( \"comms::serial::serial( )\", \"Something failed!\" );\n throw Exception( \"comms::serial::serial( )\", ::GetLastError( ) );\n"
},
{
"answer_id": 60140,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 5,
"selected": true,
"text": "#define throwException(message) \\\n { \\\n std::ostringstream oss; \\\n oss << __FILE __ << \" \" << __LINE__ << \" \" \\\n << __FUNC__ << \" \" << message; \\\n throw std::exception(oss.str().c_str()); \\\n }\n throwException(\"An unknown enum value has been passed!\");\n"
},
{
"answer_id": 59470923,
"author": "GPMueller",
"author_id": 4069571,
"author_profile": "https://Stackoverflow.com/users/4069571",
"pm_score": 0,
"selected": false,
"text": "std::nested_exception std::throw_with_nested Library API: Exception caught in function 'api_function'\nBacktrace:\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed\n~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file \"nonexistent.txt\"\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
36,079 |
<p>In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done?</p>
|
[
{
"answer_id": 36086,
"author": "maxsilver",
"author_id": 1477,
"author_profile": "https://Stackoverflow.com/users/1477",
"pm_score": 2,
"selected": false,
"text": "<?php\nrequire_once \"Mail.php\";\n\n$from = \"Sandra Sender <[email protected]>\";\n$to = \"Ramona Recipient <[email protected]>\";\n$subject = \"Hi!\";\n$body = \"Hi,\\n\\nHow are you?\";\n\n// stick your GMAIL SMTP info here! ------------------------------\n$host = \"mail.example.com\";\n$username = \"smtp_username\";\n$password = \"smtp_password\";\n// --------------------------------------------------------------\n\n$headers = array ('From' => $from,\n 'To' => $to,\n 'Subject' => $subject);\n$smtp = Mail::factory('smtp',\n array ('host' => $host,\n 'auth' => true,\n 'username' => $username,\n 'password' => $password));\n\n$mail = $smtp->send($to, $headers, $body);\n\nif (PEAR::isError($mail)) {\n echo(\"<p>\" . $mail->getMessage() . \"</p>\");\n } else {\n echo(\"<p>Message successfully sent!</p>\");\n }\n?>\n"
},
{
"answer_id": 36279,
"author": "Javache",
"author_id": 1074,
"author_profile": "https://Stackoverflow.com/users/1074",
"pm_score": 4,
"selected": true,
"text": "Outgoing Mail (SMTP) Server (requires TLS)\n - smtp.gmail.com\n - Use Authentication: Yes\n - Use STARTTLS: Yes (some clients call this SSL)\n - Port: 465 or 587\nAccount Name: your full email address (including @gmail.com)\nEmail Address: your email address ([email protected])\nPassword: your Gmail password \n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] |
36,081 |
<p>I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?</p>
<p>Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.</p>
<hr>
<p>I'm looking for more detail on rolling my own catching block inside a using block.</p>
<p>Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...</p>
<p>Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!</p>
|
[
{
"answer_id": 36094,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 2,
"selected": false,
"text": "IDisposable disposable = null;\ntry\n{\n disposable = new WhateverYouWantedToMake();\n}\nfinally\n{\n disposable.Dispose()\n}\n"
},
{
"answer_id": 36097,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": true,
"text": "MyThing IDisposable using ( MyThing thing = new MyThing() )\n{\n ...\n throw new ApplicationException(\"oops\");\n}\n thing.Dispose try\n{\n ...\n using ( MyThing thing = new MyThing() )\n {\n ...\n }\n ...\n}\ncatch ( Exception e )\n{\n ....\n}\nfinally\n{\n ....\n} \n using ( MyThing thing = new MyThing() )\n{\n ...\n try\n {\n ...\n }\n catch ( Exception e )\n {\n ....\n }\n finally\n {\n ....\n } \n ...\n} // thing.Dispose is called now\n using Dispose finally finally catch Dispose using try/catch/finally using"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] |
36,101 |
<p>How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter)</p>
|
[
{
"answer_id": 36131,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 4,
"selected": true,
"text": "<script type=\"text/javascript\">\n window.name = \"MyWindow\";\n</script>\n app/helpers/application_helper.rb def window_name(name)\n content_for(:window_name) do\n \"<script type=\\\"text/javascript\\\">window.name = \\\"#{name}\\\";</script>\"\n end\nend\n <head> <%= yield :window_name %>\n <% window_name 'MyWindow' %>\n"
},
{
"answer_id": 30665419,
"author": "John S.",
"author_id": 4975918,
"author_profile": "https://Stackoverflow.com/users/4975918",
"pm_score": 0,
"selected": false,
"text": "var x=window.open(\"\", \"myWindow\");\nvar y=\"<head><title>my window</title></head><body>my window</body>\";\nx.document.write(y);\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
36,108 |
<p>Some WPF controls (like the <code>Button</code>) seem to happily consume all the available space in its' container if you don't specify the height it is to have.</p>
<p>And some, like the ones I need to use right now, the (multiline) <code>TextBox</code> and the <code>ListBox</code> seem more worried about just taking the space necessary to fit their contents, and no more. </p>
<p>If you put these guys in a cell in a <code>UniformGrid</code>, they will expand to fit the available space. However, <code>UniformGrid</code> instances are not right for all situations. What if you have a grid with some rows set to a * height to divide the height between itself and other * rows? What if you have a <code>StackPanel</code> and you have a <code>Label</code>, a <code>List</code> and a <code>Button</code>, how can you get the list to take up all the space not eaten by the label and the button?</p>
<p>I would think this would really be a basic layout requirement, but I can't figure out how to get them to fill the space that they could (putting them in a <code>DockPanel</code> and setting it to fill also doesn't work, it seems, since the <code>DockPanel</code> only takes up the space needed by its' subcontrols).</p>
<p>A resizable GUI would be quite horrible if you had to play with <code>Height</code>, <code>Width</code>, <code>MinHeight</code>, <code>MinWidth</code> etc. </p>
<p>Can you bind your <code>Height</code> and <code>Width</code> properties to the grid cell you occupy? Or is there another way to do this?</p>
|
[
{
"answer_id": 36634,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 8,
"selected": false,
"text": "HorizontalContentAlignment=\"Stretch\"\n HorizontalAlignment=\"Stretch\"\n"
},
{
"answer_id": 36741,
"author": "user3837",
"author_id": 3837,
"author_profile": "https://Stackoverflow.com/users/3837",
"pm_score": 8,
"selected": true,
"text": "Panel Measure() Arrange() Measure() Arrange() DockPanel LastChild false StackPanel Measure() Infinity Grid Panel MeasureOverride() ArrangeOverride()"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2122/"
] |
36,109 |
<p>The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.</p>
<pre><code>#! /bin/sh
if [ "${1+set}" != "set" ]
then
echo "Usage; winewrap EXEC [ARGS...]"
exit 1
fi
EXEC="$1"
shift
ARGS=""
for p in "$@";
do
if [ -e "$p" ]
then
p=$(winepath -w $p)
fi
ARGS="$ARGS '$p'"
done
CMD="wine '$EXEC' $ARGS"
echo $CMD
$CMD
</code></pre>
<p>However, there's something wrong with the quotation of command-line arguments.</p>
<pre><code>$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt
Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt'
wine: cannot find ''/home/chris/.wine/drive_c/Program'
</code></pre>
<p>Note that:</p>
<ol>
<li>The path to the executable is being chopped off at the first space, even though it is single-quoted.</li>
<li>The literal "\t" in the last path is being transformed into a tab character.</li>
</ol>
<p>Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?</p>
<p>EDIT: The "\t" is being expanded through two levels of indirection: first, <code>"$p"</code> (and/or <code>"$ARGS"</code>) is being expanded into <code>Z:\tmp\smtlib3cee8b.smt</code>; then, <code>\t</code> is being expanded into the tab character. This is (seemingly) equivalent to</p>
<pre><code>Y='y\ty'
Z="z${Y}z"
echo $Z
</code></pre>
<p>which yields </p>
<pre><code>zy\tyz
</code></pre>
<p>and <em>not</em></p>
<pre><code>zy yz
</code></pre>
<p>UPDATE: <code>eval "$CMD"</code> does the trick. The "<code>\t</code>" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." (<a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="nofollow noreferrer">POSIX specification of <code>echo</code></a>)</p>
|
[
{
"answer_id": 36113,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 0,
"selected": false,
"text": "/home/chris/.wine/drive_c/Program Files/Microsoft\\ Research/Z3-1.3.6/bin/z3.exe\n"
},
{
"answer_id": 42005,
"author": "WMR",
"author_id": 2844,
"author_profile": "https://Stackoverflow.com/users/2844",
"pm_score": 2,
"selected": true,
"text": "eval $CMD $CMD"
},
{
"answer_id": 112558,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 2,
"selected": false,
"text": "#! /bin/bash\n\n# push ARRAY arg1 arg2 ...\n# adds arg1, arg2, ... to the end of ARRAY\nfunction push() {\n local ARRAY_NAME=\"${1}\"\n shift\n for ARG in \"${@}\"; do\n eval \"${ARRAY_NAME}[\\${#${ARRAY_NAME}[@]}]=\\${ARG}\"\n done\n}\n\nPROG=\"$(basename -- \"${0}\")\"\n\nif (( ${#} < 1 )); then\n # Error messages should state the program name and go to stderr\n echo \"${PROG}: Usage: winewrap EXEC [ARGS...]\" 1>&2\n exit 1\nfi\n\nEXEC=(\"${1}\")\nshift\n\nfor p in \"${@}\"; do\n if [ -e \"${p}\" ]; then\n p=\"$(winepath -w -- \"${p}\")\"\n fi\n push EXEC \"${p}\"\ndone\n\nexec \"${EXEC[@]}\"\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1412/"
] |
36,114 |
<p>I know I must be missing something, but in a <code>while</code> statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?</p>
<hr>
<p>{</p>
<pre><code>int num1 = 0 ;
int num2 = 0;
int num3 = 0;
while (num1 < 10)
{cout << "enter your first number: ";
cin >> num1;
cout << "Enter your second number: ";
cin >> num2;
num1 = num1 + num2 ;
cout << "Number 1 is now: " << num1 <<endl;
cout << "Enter Number 3: " ;
cin >> num3;
num1 = num1 + num3;
cout << "Number 1 is now: " << num1 << endl;
num1++;
};
</code></pre>
<p>In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!</p>
|
[
{
"answer_id": 36155,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 2,
"selected": false,
"text": "int a = 0;\n\nwhile(a < 10)\n{\n int b = 0;\n\n cout << \"a: \" << a << \" b: \" << b << \"\\n\";\n\n a++;\n b++;\n}\n"
},
{
"answer_id": 36246,
"author": "James Sutherland",
"author_id": 1739,
"author_profile": "https://Stackoverflow.com/users/1739",
"pm_score": 3,
"selected": true,
"text": "cin >> num1;\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335696/"
] |
36,129 |
<p>I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.</p>
<p>If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.</p>
|
[
{
"answer_id": 36167,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 3,
"selected": true,
"text": "namespace PublishSubscribe\n{\n public partial class Form1 : Form\n {\n Form2 f2 = new Form2();\n\n public Form1()\n {\n InitializeComponent();\n\n f2.PublishData += new PublishDataEventHander( DataReceived );\n f2.Show();\n }\n\n private void DataReceived( object sender, Form2EventArgs e )\n {\n MessageBox.Show( e.OtherData ); \n }\n }\n}\n namespace PublishSubscribe\n{\n\n public delegate void PublishDataEventHander( object sender, Form2EventArgs e );\n\n public partial class Form2 : Form\n {\n public event PublishDataEventHander PublishData;\n\n public Form2()\n {\n InitializeComponent();\n }\n\n private void button1_Click( object sender, EventArgs e )\n {\n PublishData( this, new Form2EventArgs( \"data from form2\" ) ); \n }\n }\n\n public class Form2EventArgs : System.EventArgs\n {\n public string OtherData;\n\n public Form2EventArgs( string OtherData ) \n {\n this.OtherData = OtherData;\n }\n }\n}\n"
},
{
"answer_id": 36194,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 2,
"selected": false,
"text": "Partial Public Class _Default\n Inherits System.Web.UI.Page\n Implements IProductView\n\n Private presenter As ProductPresenter\n\n Protected Overrides Sub OnInit(ByVal e As System.EventArgs)\n MyBase.OnInit(e)\n presenter = New ProductPresenter(Me)\n End Sub\n\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n presenter.OnViewLoad()\n End Sub\n\n Private ReadOnly Property PageIsPostBack() As Boolean Implements IProductView.PageIsPostBack\n Get\n Return Page.IsPostBack\n End Get\n End Property\n\n Public Property Products() As System.Collections.Generic.List(Of Product) Implements Library.IProductView.Products\n Get\n Return DirectCast(gridProducts.DataSource(), List(Of Product))\n End Get\n Set(ByVal value As System.Collections.Generic.List(Of Product))\n gridProducts.DataSource = value\n gridProducts.DataBind()\n End Set\n End Property\nEnd Class\n Public Class ProductPresenter\n Private mView As IProductView\n Private mProductService As IProductService\n\n Public Sub New(ByVal View As IProductView)\n Me.New(View, New ProductService())\n End Sub\n\n Public Sub New(ByVal View As IProductView, ByVal ProductService As IProductService)\n mView = View\n mProductService = ProductService\n End Sub\n\n Public Sub OnViewLoad()\n If mView.PageIsPostBack = False Then\n PopulateProductsList()\n End If\n End Sub\n\n Public Sub PopulateProductsList()\n Try\n Dim ProductList As List(Of Product) = mProductService.GetProducts()\n mView.Products = ProductList\n Catch ex As Exception\n Throw ex\n End Try\n End Sub\nEnd Class\n"
},
{
"answer_id": 113353,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 1,
"selected": false,
"text": "void FireMyEvent(object sender, EventArgs e) \n{\n if (_myevent != null) _myEvent(sender, e);\n}\n public virtual void BeforeOpenFile(string filepath)\n{\n //stub\n}\npublic virtual void AfterOpenFile(string filepath)\n{\n //stub\n}\npublic sealed void OpenFile(string filepath) \n{\n BeforeOpenFile(filepath); //do user customisable pre-open bits\n //do standard bits here\n AfterOpenFile(filepath); //do user customisable post-open bits\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1603/"
] |
36,139 |
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
|
[
{
"answer_id": 36143,
"author": "rix0rrr",
"author_id": 2474,
"author_profile": "https://Stackoverflow.com/users/2474",
"pm_score": 5,
"selected": false,
"text": "list.sort()\n"
},
{
"answer_id": 36156,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 10,
"selected": true,
"text": "mylist = [\"b\", \"C\", \"A\"]\nmylist.sort()\n sorted() for x in sorted(mylist):\n print x\n key cmp key cmp_to_key sorted(mylist, key=cmp_to_key(locale.strcoll))\n import locale\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale\nassert sorted((u'Ab', u'ad', u'aa'),\n key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']\n lower() # this is incorrect!\nmylist.sort(key=lambda x: x.lower())\n# alternative notation, a bit faster, but still wrong\nmylist.sort(key=str.lower)\n"
},
{
"answer_id": 36220,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "list.sort()"
},
{
"answer_id": 36395,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "sorted() for x in sorted(list):\n print x\n"
},
{
"answer_id": 1640634,
"author": "schmichael",
"author_id": 10275,
"author_profile": "https://Stackoverflow.com/users/10275",
"pm_score": 4,
"selected": false,
"text": "import locale\nlocale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale\nassert sorted((u'Ab', u'ad', u'aa'), cmp=locale.strcoll) == [u'aa', u'Ab', u'ad']\n\n# Without using locale.strcoll you get:\nassert sorted((u'Ab', u'ad', u'aa')) == [u'Ab', u'aa', u'ad']\n mylist.sort(key=lambda x: x.lower())"
},
{
"answer_id": 43930555,
"author": "JON",
"author_id": 5289655,
"author_profile": "https://Stackoverflow.com/users/5289655",
"pm_score": 0,
"selected": false,
"text": "s = \"ZWzaAd\" print ''.join(sorted(s))\n"
},
{
"answer_id": 47993007,
"author": "Mahmud Ahsan",
"author_id": 339119,
"author_profile": "https://Stackoverflow.com/users/339119",
"pm_score": 4,
"selected": false,
"text": "items = [\"love\", \"like\", \"play\", \"cool\", \"my\"]\nsorted(items2)\n"
},
{
"answer_id": 51826113,
"author": "Dragos Alexe",
"author_id": 5379112,
"author_profile": "https://Stackoverflow.com/users/5379112",
"pm_score": 0,
"selected": false,
"text": "names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']\nprint (\"The solution for this is about this names being sorted:\",sorted(names, key=lambda name:name.lower()))\n"
},
{
"answer_id": 57692644,
"author": "vlz",
"author_id": 1879728,
"author_profile": "https://Stackoverflow.com/users/1879728",
"pm_score": 1,
"selected": false,
"text": "locale.LC_ALL import icu # PyICU\n\ndef sorted_strings(strings, locale=None):\n if locale is None:\n return sorted(strings)\n collator = icu.Collator.createInstance(icu.Locale(locale))\n return sorted(strings, key=collator.getSortKey)\n new_list = sorted_strings(list_of_strings, \"de_DE.utf8\")\n"
},
{
"answer_id": 59223861,
"author": "asing177",
"author_id": 5567627,
"author_profile": "https://Stackoverflow.com/users/5567627",
"pm_score": 1,
"selected": false,
"text": "l =['abc' , 'cd' , 'xy' , 'ba' , 'dc']\nl.sort()\nprint(l1)\n"
},
{
"answer_id": 62164160,
"author": "Hedayatullah Sarwary",
"author_id": 6119631,
"author_profile": "https://Stackoverflow.com/users/6119631",
"pm_score": 0,
"selected": false,
"text": "scores = '54 - Alice,35 - Bob,27 - Carol,27 - Chuck,05 - Craig,30 - Dan,27 - Erin,77 - Eve,14 - Fay,20 - Frank,48 - Grace,61 - Heidi,03 - Judy,28 - Mallory,05 - Olivia,44 - Oscar,34 - Peggy,30 - Sybil,82 - Trent,75 - Trudy,92 - Victor,37 - Walter'\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
36,144 |
<p>I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code:</p>
<pre><code>var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interface
s.nsIWindowMediator);
var browserWindow = windowManager.getMostRecentWindow("navigator:browser");
var browser = browserWindow.getBrowser();
if(browser.mCurrentBrowser.currentURI.spec == "about:blank")
browserWindow.loadURI(url, null, postData, false);
else
browser.loadOneTab(url, null, null, postData, false, false);
</code></pre>
<p>I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong?</p>
<p>What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET.</p>
<p>Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1</p>
|
[
{
"answer_id": 36216,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 0,
"selected": false,
"text": "function openAndReuseOneTabPerURL(url) {\n var wm = Components.classes[\"@mozilla.org/appshell/window-mediator;1\"]\n .getService(Components.interfaces.nsIWindowMediator);\n var browserEnumerator = wm.getEnumerator(\"navigator:browser\");\n\n // Check each browser instance for our URL\n var found = false;\n while (!found && browserEnumerator.hasMoreElements()) {\n var browserInstance = browserEnumerator.getNext().getBrowser();\n\n // Check each tab of this browser instance\n var numTabs = browserInstance.tabContainer.childNodes.length;\n for(var index=0; index<numTabs; index++) {\n var currentBrowser = browserInstance.getBrowserAtIndex(index);\n if (\"about:blank\" == currentBrowser.currentURI.spec) {\n\n // The URL is already opened. Select this tab.\n browserInstance.selectedTab = browserInstance.tabContainer.childNodes[index];\n\n // Focus *this* browser\n browserInstance.focus();\n found = true;\n break;\n }\n }\n }\n\n // Our URL isn't open. Open it now.\n if (!found) {\n var recentWindow = wm.getMostRecentWindow(\"navigator:browser\");\n if (recentWindow) {\n // Use an existing browser window\n recentWindow.delayedOpenTab(url, null, null, null, null);\n }\n else {\n // No browser windows are open, so open a new one.\n window.open(url);\n }\n }\n}\n"
},
{
"answer_id": 36995,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 2,
"selected": false,
"text": "nsIMIMEInputStream"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3288/"
] |
36,183 |
<p>I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:</p>
<pre><code>12||34||56
</code></pre>
<p>I want to replace the second set of pipes with ampersands to get this string:</p>
<pre><code>12||34&&56
</code></pre>
<p>The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:</p>
<pre><code>23||45||45||56||67 -> 23&&45||45||56||67
23||34||98||87 -> 23||34||98&&87
</code></pre>
<p>I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on <code>/\|\|/</code> and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using <code>eval()</code>, but it's not possible to use any Perl-specific regex instructions.</p>
|
[
{
"answer_id": 36191,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 5,
"selected": true,
"text": "\"23||45||45||56||67\".replace(/^((?:[0-9]+\\|\\|){n})([0-9]+)\\|\\|/,\"$1$2&&\")\n function pipe_replace(str,n) {\n var RE = new RegExp(\"^((?:[0-9]+\\\\|\\\\|){\" + (n-1) + \"})([0-9]+)\\|\\|\");\n return str.replace(RE,\"$1$2&&\");\n}\n"
},
{
"answer_id": 1181513,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "function pipe_replace(str,n) {\n m = 0;\n return str.replace(/\\|\\|/g, function (x) {\n //was n++ should have been m++\n m++;\n if (n==m) {\n return \"&&\";\n } else {\n return x;\n }\n });\n}\n"
},
{
"answer_id": 7958627,
"author": "Nathan Long",
"author_id": 4376,
"author_profile": "https://Stackoverflow.com/users/4376",
"pm_score": 5,
"selected": false,
"text": "original pattern split n 2 replace // Pipe examples like the OP's\nreplaceNthMatch(\"12||34||56\", /(\\|\\|)/, 2, '&&') // \"12||34&&56\"\nreplaceNthMatch(\"23||45||45||56||67\", /(\\|\\|)/, 1, '&&') // \"23&&45||45||56||67\"\n\n// Replace groups of digits\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 3, 'NEW') // \"foo-1-bar-23-stuff-NEW\"\n\n// Search value can be a string\nreplaceNthMatch(\"foo-stuff-foo-stuff-foo\", \"foo\", 2, 'bar') // \"foo-stuff-bar-stuff-foo\"\n\n// No change if there is no match for the search\nreplaceNthMatch(\"hello-world\", \"goodbye\", 2, \"adios\") // \"hello-world\"\n\n// No change if there is no Nth match for the search\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 6, 'NEW') // \"foo-1-bar-23-stuff-45\"\n\n// Passing in a function to make the replacement\nreplaceNthMatch(\"foo-1-bar-23-stuff-45\", /(\\d+)/, 2, function(val){\n //increment the given value\n return parseInt(val, 10) + 1;\n}); // \"foo-1-bar-24-stuff-45\"\n var replaceNthMatch = function (original, pattern, n, replace) {\n var parts, tempParts;\n\n if (pattern.constructor === RegExp) {\n\n // If there's no match, bail\n if (original.search(pattern) === -1) {\n return original;\n }\n\n // Every other item should be a matched capture group;\n // between will be non-matching portions of the substring\n parts = original.split(pattern);\n\n // If there was a capture group, index 1 will be\n // an item that matches the RegExp\n if (parts[1].search(pattern) !== 0) {\n throw {name: \"ArgumentError\", message: \"RegExp must have a capture group\"};\n }\n } else if (pattern.constructor === String) {\n parts = original.split(pattern);\n // Need every other item to be the matched string\n tempParts = [];\n\n for (var i=0; i < parts.length; i++) {\n tempParts.push(parts[i]);\n\n // Insert between, but don't tack one onto the end\n if (i < parts.length - 1) {\n tempParts.push(pattern);\n }\n }\n parts = tempParts;\n } else {\n throw {name: \"ArgumentError\", message: \"Must provide either a RegExp or String\"};\n }\n\n // Parens are unnecessary, but explicit. :)\n indexOfNthMatch = (n * 2) - 1;\n\n if (parts[indexOfNthMatch] === undefined) {\n // There IS no Nth match\n return original;\n }\n\n if (typeof(replace) === \"function\") {\n // Call it. After this, we don't need it anymore.\n replace = replace(parts[indexOfNthMatch]);\n }\n\n // Update our parts array with the new value\n parts[indexOfNthMatch] = replace;\n\n // Put it back together and return\n return parts.join('');\n\n }\n String.prototype.replaceNthMatch = function(pattern, n, replace) {\n // Same code as above, replacing \"original\" with \"this\"\n};\n \"foo-bar-foo\".replaceNthMatch(\"foo\", 2, \"baz\"); // \"foo-bar-baz\"\n describe(\"replaceNthMatch\", function() {\n\n describe(\"when there is no match\", function() {\n\n it(\"should return the unmodified original string\", function() {\n var str = replaceNthMatch(\"hello-there\", /(\\d+)/, 3, 'NEW');\n expect(str).toEqual(\"hello-there\");\n });\n\n });\n\n describe(\"when there is no Nth match\", function() {\n\n it(\"should return the unmodified original string\", function() {\n var str = replaceNthMatch(\"blah45stuff68hey\", /(\\d+)/, 3, 'NEW');\n expect(str).toEqual(\"blah45stuff68hey\");\n });\n\n });\n\n describe(\"when the search argument is a RegExp\", function() {\n\n describe(\"when it has a capture group\", function () {\n\n it(\"should replace correctly when the match is in the middle\", function(){\n var str = replaceNthMatch(\"this_937_thing_38_has_21_numbers\", /(\\d+)/, 2, 'NEW');\n expect(str).toEqual(\"this_937_thing_NEW_has_21_numbers\");\n });\n\n it(\"should replace correctly when the match is at the beginning\", function(){\n var str = replaceNthMatch(\"123_this_937_thing_38_has_21_numbers\", /(\\d+)/, 2, 'NEW');\n expect(str).toEqual(\"123_this_NEW_thing_38_has_21_numbers\");\n });\n\n });\n\n describe(\"when it has no capture group\", function() {\n\n it(\"should throw an error\", function(){\n expect(function(){\n replaceNthMatch(\"one_1_two_2\", /\\d+/, 2, 'NEW');\n }).toThrow('RegExp must have a capture group');\n });\n\n });\n\n\n });\n\n describe(\"when the search argument is a string\", function() {\n\n it(\"should should match and replace correctly\", function(){\n var str = replaceNthMatch(\"blah45stuff68hey\", 'stuff', 1, 'NEW');\n expect(str).toEqual(\"blah45NEW68hey\");\n });\n\n });\n\n describe(\"when the replacement argument is a function\", function() {\n\n it(\"should call it on the Nth match and replace with the return value\", function(){\n\n // Look for the second number surrounded by brackets\n var str = replaceNthMatch(\"foo[1][2]\", /(\\[\\d+\\])/, 2, function(val) {\n\n // Get the number without the [ and ]\n var number = val.slice(1,-1);\n\n // Add 1\n number = parseInt(number,10) + 1;\n\n // Re-format and return\n return '[' + number + ']';\n });\n expect(str).toEqual(\"foo[1][3]\");\n\n });\n\n });\n\n});\n"
},
{
"answer_id": 74004810,
"author": "Prashant",
"author_id": 1855068,
"author_profile": "https://Stackoverflow.com/users/1855068",
"pm_score": 0,
"selected": false,
"text": "private replaceNthMatch(original, pattern, n, replace) {\n let m = -1;\n return original.replaceAll(pattern, x => {\n m++;\n if ( n == m ) {\n return replace;\n } else {\n return x;\n }\n });\n}\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2289/"
] |
36,260 |
<p>I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed.</p>
<p>The only way I know of to solve this is to define all three types at once:</p>
<pre><code>type defn = ...
and stmt = ...
and expr = ...
</code></pre>
<p>It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code?</p>
|
[
{
"answer_id": 216062,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 4,
"selected": false,
"text": "type ('stmt, 'expr) defn = ...\ntype ('defn, 'expr) stmt = ...\ntype ('defn, 'stmt) expr = ...\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1891/"
] |
36,274 |
<p>What is Lazy Loading?</p>
<p>[Edit after reading a few answers]
Why do people use this term so often? </p>
<p>Say you just use a ASP/ADO recordset and load it with data or ADO.NET Datasource for a gridview.</p>
<p>I guess I should have asked why people use the term Lazy Loading, what "other" types are their?</p>
|
[
{
"answer_id": 36291,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 3,
"selected": false,
"text": "class Item(Model):\n ...\n @property\n def total(self):\n if not hasattr(self, \"_total\"):\n self._total = self.quantity \\\n + sum(bi.quantity for bi in self.borroweditem_set.all())\n return self._total\n"
},
{
"answer_id": 1670264,
"author": "Philip Wallace",
"author_id": 190145,
"author_profile": "https://Stackoverflow.com/users/190145",
"pm_score": 1,
"selected": false,
"text": "Lazy<T>"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
] |
36,294 |
<p>Looks like here in StackOveflow there is a group of <strong>F#</strong> enthusiasts. </p>
<p>I'd like to know better this language, so, apart from the <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional programming theory</a>, can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.</p>
<p>Thanks a lot</p>
<p>Andrea</p>
|
[
{
"answer_id": 36393,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": true,
"text": "#light\n > #light;;\n > let f x y = x + y;;\n\n val f : int -> int -> int\n\n > f 1 2;;\n val it : int = 3\n let sumStuff x y = x + y\nlet sumStuffTuple (x, y) = x + y\n sumStuff 1 2\n3\nsumStuffTuple (1, 2)\n3\n let sumStuff1 = sumStuff 1\nsumStuff 2\n3\n let someThing x =\n match x with\n | 0 -> \"zero\"\n | 1 -> \"one\"\n | 2 -> \"two\"\n | x when x < 0 -> \"negative = \" + x.ToString()\n | _ when x%2 = 0 -> \"greater than two but even\"\n | _ -> \"greater than two but odd\"\n let negEvenOdd x = if x < 0 then \"neg\" elif x % 2 = 0 then \"even\" else \"odd\"\n let l1 = [1;2;3]\nl1.[0]\n1\n\nlet l2 = [1 .. 10]\nList.length l2\n10\n\nlet squares = [for i in 1..10 -> i * i]\nsquares\n[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]\n\nlet square x = x * x;;\nlet squares2 = List.map square [1..10]\nsquares2\n[1; 4; 9; 16; 25; 36; 49; 64; 81; 100]\n\nlet evenSquares = List.filter (fun x -> x % 2 = 0) squares\nevenSqares\n[4; 16; 36; 64; 100]\n let f x = \"hi \" + x\n let f x y = x + y\n let f (x:string) y = x + y\n let (|>) x f = f x\n [1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)\n List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10])\n let (>>) f g x = g(f(x))\n let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0)\n let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0)\n let rec fact x = if x <= 1 then 1 else x * fact (x-1)\n let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2)\n let (/%) x y = x % y = 0\nlet fb = function\n | x when x /% 15 -> \"FizzBuzz\"\n | x when x /% 3 -> \"Fizz\"\n | x when x /% 5 -> \"Buzz\"\n | x -> x.ToString()\n\n[1..100] |> List.map (fb >> printfn \"%s\")\n"
},
{
"answer_id": 36847,
"author": "ila",
"author_id": 1178,
"author_profile": "https://Stackoverflow.com/users/1178",
"pm_score": 3,
"selected": false,
"text": "let thanksalot = \"thanks a lot\"\nprintfn \"%s\" (thanksalot);;\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1178/"
] |
36,314 |
<p>I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)</p>
|
[
{
"answer_id": 36321,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 11,
"selected": true,
"text": "function add (a, b) {\n return a + b;\n}\n\nadd(3, 4); // returns 7\n function add (a) {\n return function (b) {\n return a + b;\n }\n}\n a b add(3)(4); // returns 7\n\nvar add3 = add(3); // returns a function\n\nadd3(4); // returns 7\n add(3, 4) add3 add3"
},
{
"answer_id": 36340,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": false,
"text": "let f x y z = x + y + z\n f 1 2 3\n let curry f = fun x -> f x\n let curryf = curry f\n let f1 = curryf 1\n f1 2 3\n let papply f x = f x\n let papply2 f x y = f x y\nlet papply3 f x y z = f x y z\netc.\n let f1 = f 1\nf1 2 3\n let f x y z = x + y + z\nlet curryf = curry f\nlet f1 = curryf 1\nlet f2 = curryf 2\nf1 2 3\n6\nf2 1 3\n6\n let f x y z = x + y + z\nlet f1 = f 1\nlet f2 = f 2\nf1 2 3\n6\nf2 1 3\n6\n"
},
{
"answer_id": 1352865,
"author": "Alex Martelli",
"author_id": 95810,
"author_profile": "https://Stackoverflow.com/users/95810",
"pm_score": 7,
"selected": false,
"text": "f(x,y) f(x)(y) f(x) g y"
},
{
"answer_id": 1354439,
"author": "Anon",
"author_id": 108445,
"author_profile": "https://Stackoverflow.com/users/108445",
"pm_score": 3,
"selected": false,
"text": ">>> from functools import partial as curry\n\n>>> # Original function taking three parameters:\n>>> def display_quote(who, subject, quote):\n print who, 'said regarding', subject + ':'\n print '\"' + quote + '\"'\n\n\n>>> display_quote(\"hoohoo\", \"functional languages\",\n \"I like Erlang, not sure yet about Haskell.\")\nhoohoo said regarding functional languages:\n\"I like Erlang, not sure yet about Haskell.\"\n\n>>> # Let's curry the function to get another that always quotes Alex...\n>>> am_quote = curry(display_quote, \"Alex Martelli\")\n\n>>> am_quote(\"currying\", \"As usual, wikipedia has a nice summary...\")\nAlex Martelli said regarding currying:\n\"As usual, wikipedia has a nice summary...\"\n"
},
{
"answer_id": 23454424,
"author": "catch23",
"author_id": 1498427,
"author_profile": "https://Stackoverflow.com/users/1498427",
"pm_score": 2,
"selected": false,
"text": "scala> def plainOldSum(x: Int, y: Int) = x + y\nplainOldSum: (x: Int,y: Int)Int\nscala> plainOldSum(1, 2)\nres4: Int = 3\n scala> def curriedSum(x: Int)(y: Int) = x + y\ncurriedSum: (x: Int)(y: Int)Intscala> second(2)\nres6: Int = 3\nscala> curriedSum(1)(2)\nres5: Int = 3\n curriedSum x y first curriedSum scala> def first(x: Int) = (y: Int) => x + y\nfirst: (x: Int)(Int) => Int\n scala> val second = first(1)\nsecond: (Int) => Int = <function1>\n scala> second(2)\nres6: Int = 3\n"
},
{
"answer_id": 31081596,
"author": "Mario",
"author_id": 25358,
"author_profile": "https://Stackoverflow.com/users/25358",
"pm_score": 3,
"selected": false,
"text": "partial partial + (defn add [a b] (+ a b))\n inc (inc 7) # => 8\n partial (def inc (partial add 1))\n add add inc b partial add inc partial (def inc (add 1)) #partial is implied\n"
},
{
"answer_id": 34795493,
"author": "Adzz",
"author_id": 3601621,
"author_profile": "https://Stackoverflow.com/users/3601621",
"pm_score": 6,
"selected": false,
"text": "let add = function(x){\n return function(y){ \n return x + y\n };\n};\n let addTen = add(10);\n 10 x let add = function(10){\n return function(y){\n return 10 + y \n };\n};\n function(y) { return 10 + y };\n addTen();\n function(y) { return 10 + y };\n addTen(4)\n function(4) { return 10 + 4} // 14\n addTen() let addTwo = add(2) // addTwo(); will add two to whatever you pass in\nlet addSeventy = add(70) // ... and so on...\n x + y let doTheHardStuff = function(x) {\n let z = doSomethingComputationallyExpensive(x)\n return function (y){\n z + y\n }\n}\n let finishTheJob = doTheHardStuff(10)\nfinishTheJob(20)\nfinishTheJob(30)\n"
},
{
"answer_id": 36541937,
"author": "S2dent",
"author_id": 3664083,
"author_profile": "https://Stackoverflow.com/users/3664083",
"pm_score": 2,
"selected": false,
"text": "func aFunction(str: String) {\n let callback = callback(str) // signature now is `NSData -> ()`\n performAsyncRequest(callback)\n}\n\nfunc callback(str: String, data: NSData) {\n // Callback code\n}\n\nfunc performAsyncRequest(callback: NSData -> ()) {\n // Async code that will call callback with NSData as parameter\n}\n performAsyncRequest(_:)"
},
{
"answer_id": 49895155,
"author": "user3804449",
"author_id": 3804449,
"author_profile": "https://Stackoverflow.com/users/3804449",
"pm_score": 2,
"selected": false,
"text": "times = (x, y) --> x * y\ntimes 2, 3 #=> 6 (normal use works as expected)\ndouble = times 2\ndouble 5 #=> 10\n"
},
{
"answer_id": 50962077,
"author": "Marcus Thornton",
"author_id": 2288882,
"author_profile": "https://Stackoverflow.com/users/2288882",
"pm_score": 2,
"selected": false,
"text": "function curryMinus(x) \n{\n return function(y) \n {\n return x - y;\n }\n}\n\nvar minus5 = curryMinus(1);\nminus5(3);\nminus5(5);\n var minus7 = curryMinus(7);\nminus7(3);\nminus7(5);\n"
},
{
"answer_id": 52355185,
"author": "V. S.",
"author_id": 10014202,
"author_profile": "https://Stackoverflow.com/users/10014202",
"pm_score": 1,
"selected": false,
"text": "public static class FuncExtensions {\n public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> func)\n {\n return x1 => x2 => func(x1, x2);\n }\n}\n\n//Usage\nvar add = new Func<int, int, int>((x, y) => x + y).Curry();\nvar func = add(1);\n\n//Obtaining the next parameter here, calling later the func with next parameter.\n//Or you can prepare some base calculations at the previous step and then\n//use the result of those calculations when calling the func multiple times \n//with different input parameters.\n\nint result = func(1);\n"
},
{
"answer_id": 55357631,
"author": "MidhunKrishna",
"author_id": 3485581,
"author_profile": "https://Stackoverflow.com/users/3485581",
"pm_score": 3,
"selected": false,
"text": "f(a, b, c) f(a)(b)(c) curry(f) f(a, b) f(a)(b) function curry(f) { // curry(f) does the currying transform\n return function(a) {\n return function(b) {\n return f(a, b);\n };\n };\n}\n\n// usage\nfunction sum(a, b) {\n return a + b;\n}\n\nlet carriedSum = curry(sum);\n\nalert( carriedSum(1)(2) ); // 3\n curry(func) function(a) sum(1) function(b) sum(1)(2) function(b)"
},
{
"answer_id": 58290342,
"author": "Prashant Andani",
"author_id": 2545628,
"author_profile": "https://Stackoverflow.com/users/2545628",
"pm_score": 3,
"selected": false,
"text": "const add = a => b => b ? add(a + b) : a; \n const add = a => b => b ? add(a + b) : a; \nconsole.log(add(1)(2)(3)(4)());"
},
{
"answer_id": 60684994,
"author": "madeinQuant",
"author_id": 5329711,
"author_profile": "https://Stackoverflow.com/users/5329711",
"pm_score": 0,
"selected": false,
"text": "let run = () => {\n Js.log(\"Curryed function: \");\n let sum = (x, y) => x + y;\n Printf.printf(\"sum(2, 3) : %d\\n\", sum(2, 3));\n let per2 = sum(2);\n Printf.printf(\"per2(3) : %d\\n\", per2(3));\n };\n"
},
{
"answer_id": 62166542,
"author": "sabitha kuppusamy",
"author_id": 7544289,
"author_profile": "https://Stackoverflow.com/users/7544289",
"pm_score": 3,
"selected": false,
"text": "function add(a,b)\n {\n return a+b;\n }\nadd(5,6);\n function add(a)\n {\n return function(b){\n return a+b;\n }\n }\nvar curryAdd = add(5);\ncurryAdd(6);\n var curryAdd = add(5);\n curryAdd=function(y){return 5+y;}\n curryAdd(6);\n curryAdd=function(6){return 5+6;}\n// Which results in 11\n function add(a)\n {\n return function(b){\n return a+b;\n }\n }\n x=>y=>x+y\n"
},
{
"answer_id": 66853947,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 3,
"selected": false,
"text": "arity curry(f) :: (a,b,c) -> f(a) -> f(b)-> f(c)\n const withdraw=(cardInfo,pinNumber,request){\n // process it\n return request.amount\n}\n const withdraw=(cardInfo)=>(pinNumber)=>(request)=>request.amount\n"
},
{
"answer_id": 67447820,
"author": "WasitShafi",
"author_id": 10249156,
"author_profile": "https://Stackoverflow.com/users/10249156",
"pm_score": 0,
"selected": false,
"text": "const multiply = (presetConstant) => {\n return (x) => {\n return presetConstant * x;\n };\n};\n\nconst multiplyByTwo = multiply(2);\n\n// now multiplyByTwo is like below function & due to closure property in JavaScript it will always be able to access 'presetConstant' value\n// const multiplyByTwo = (x) => {\n// return presetConstant * x;\n// };\n\nconsole.log(`multiplyByTwo(8) : ${multiplyByTwo(8)}`);\n"
},
{
"answer_id": 69050333,
"author": "Mark Reed",
"author_id": 797049,
"author_profile": "https://Stackoverflow.com/users/797049",
"pm_score": 1,
"selected": false,
"text": "add x => k + x lambda x: k + x { |x| k + x } (lambda (x) (+ k x)) add(k) (k +) (+ k) (/ 9) (9 /) x map(fn, list) map(fn) map(list, fn) -> (defn f2c (deg) (-> deg (- 32) (* 5) (/ 9)) -> (/ (* (- deg 32) 5) 9) let f2c = (subtract 32) & (* 5) & (/ 9) (/ 9) . (* 5) . (subtract 32)"
},
{
"answer_id": 73095591,
"author": "ggorlen",
"author_id": 6243352,
"author_profile": "https://Stackoverflow.com/users/6243352",
"pm_score": 1,
"selected": false,
"text": "makeClickHandler onClick const List = () => {\n const [items, setItems] = React.useState([\n {name: \"foo\", likes: 0},\n {name: \"bar\", likes: 0},\n {name: \"baz\", likes: 0},\n ].map(e => ({...e, id: crypto.randomUUID()})));\n\n // .----------. outer func inner func\n // | currying | | |\n // `----------` V V\n const makeClickHandler = (id) => (event) => {\n setItems(prev => {\n const i = prev.findIndex(e => e.id === id);\n const cpy = {...prev[i]};\n cpy.likes++;\n return [\n ...prev.slice(0, i),\n cpy,\n ...prev.slice(i + 1)\n ];\n });\n };\n\n return (\n <ul>\n {items.map(({name, likes, id}) =>\n <li key={id}>\n <button\n onClick={\n /* strip off first function layer to get a click\n handler bound to `id` and pass it to onClick */\n makeClickHandler(id)\n }\n >\n {name} ({likes} likes)\n </button>\n </li>\n )}\n </ul>\n );\n};\n\nReactDOM.render(\n <List />,\n document.querySelector(\"#root\")\n); button {\n font-family: monospace;\n font-size: 2em;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js\"></script>\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js\"></script>\n<div id=\"root\"></div>"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
] |
36,315 |
<p>It'd be really nice to target my Windows Forms app to the .NET 3.5 SP1 <em>client</em> framework. But, right now I'm using the <code>HttpUtility.HtmlDecode</code> and <code>HttpUtility.UrlDecode</code> functions, and the MSDN documentation doesn't point to any alternatives inside of, say, System.Net or something.</p>
<p>So, short from reflectoring the source code and copying it into my assembly---which I don't think would be worth it---are there alternatives inside of the .NET 3.5 SP1 client framework that you know of, to replace this functionality? It seems a bit strange that they'd restrict these useful functions to server-only code.</p>
|
[
{
"answer_id": 36359,
"author": "Jeremy McGee",
"author_id": 3546,
"author_profile": "https://Stackoverflow.com/users/3546",
"pm_score": 1,
"selected": false,
"text": "HttpUtility System.Web.dll c:\\windows\\Microsoft.NET\\Framework\\ ..."
},
{
"answer_id": 4389349,
"author": "Ken Davis",
"author_id": 535211,
"author_profile": "https://Stackoverflow.com/users/535211",
"pm_score": 3,
"selected": false,
"text": "/// <summary>\n/// Taken from System.Net in 4.0, useful until we move to .NET 4.0 - needed for Client Profile\n/// </summary>\npublic static class WebUtility\n{\n // Fields\n private static char[] _htmlEntityEndingChars = new char[] { ';', '&' };\n\n // Methods\n public static string HtmlDecode(string value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return value;\n }\n if (value.IndexOf('&') < 0)\n {\n return value;\n }\n StringWriter output = new StringWriter(CultureInfo.InvariantCulture);\n HtmlDecode(value, output);\n return output.ToString();\n }\n\n public static void HtmlDecode(string value, TextWriter output)\n {\n if (value != null)\n {\n if (output == null)\n {\n throw new ArgumentNullException(\"output\");\n }\n if (value.IndexOf('&') < 0)\n {\n output.Write(value);\n }\n else\n {\n int length = value.Length;\n for (int i = 0; i < length; i++)\n {\n char ch = value[i];\n if (ch == '&')\n {\n int num3 = value.IndexOfAny(_htmlEntityEndingChars, i + 1);\n if ((num3 > 0) && (value[num3] == ';'))\n {\n string entity = value.Substring(i + 1, (num3 - i) - 1);\n if ((entity.Length > 1) && (entity[0] == '#'))\n {\n ushort num4;\n if ((entity[1] == 'x') || (entity[1] == 'X'))\n {\n ushort.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, (IFormatProvider)NumberFormatInfo.InvariantInfo, out num4);\n }\n else\n {\n ushort.TryParse(entity.Substring(1), NumberStyles.Integer, (IFormatProvider)NumberFormatInfo.InvariantInfo, out num4);\n }\n if (num4 != 0)\n {\n ch = (char)num4;\n i = num3;\n }\n }\n else\n {\n i = num3;\n char ch2 = HtmlEntities.Lookup(entity);\n if (ch2 != '\\0')\n {\n ch = ch2;\n }\n else\n {\n output.Write('&');\n output.Write(entity);\n output.Write(';');\n goto Label_0117;\n }\n }\n }\n }\n output.Write(ch);\n Label_0117: ;\n }\n }\n }\n }\n\n public static string HtmlEncode(string value)\n {\n if (string.IsNullOrEmpty(value))\n {\n return value;\n }\n if (IndexOfHtmlEncodingChars(value, 0) == -1)\n {\n return value;\n }\n StringWriter output = new StringWriter(CultureInfo.InvariantCulture);\n HtmlEncode(value, output);\n return output.ToString();\n }\n\n public static unsafe void HtmlEncode(string value, TextWriter output)\n {\n if (value != null)\n {\n if (output == null)\n {\n throw new ArgumentNullException(\"output\");\n }\n int num = IndexOfHtmlEncodingChars(value, 0);\n if (num == -1)\n {\n output.Write(value);\n }\n else\n {\n int num2 = value.Length - num;\n fixed (char* str = value)\n {\n char* chPtr = str;\n char* chPtr2 = chPtr;\n while (num-- > 0)\n {\n chPtr2++;\n output.Write(chPtr2[0]);\n }\n while (num2-- > 0)\n {\n chPtr2++;\n char ch = chPtr2[0];\n if (ch <= '>')\n {\n switch (ch)\n {\n case '&':\n {\n output.Write(\"&\");\n continue;\n }\n case '\\'':\n {\n output.Write(\"'\");\n continue;\n }\n case '\"':\n {\n output.Write(\""\");\n continue;\n }\n case '<':\n {\n output.Write(\"<\");\n continue;\n }\n case '>':\n {\n output.Write(\">\");\n continue;\n }\n }\n output.Write(ch);\n continue;\n }\n if ((ch >= '\\x00a0') && (ch < 'Ā'))\n {\n output.Write(\"&#\");\n output.Write(((int)ch).ToString(NumberFormatInfo.InvariantInfo));\n output.Write(';');\n }\n else\n {\n output.Write(ch);\n }\n }\n }\n }\n }\n }\n\n private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos)\n {\n int num = s.Length - startPos;\n fixed (char* str = s)\n {\n char* chPtr = str;\n char* chPtr2 = chPtr + startPos;\n while (num > 0)\n {\n char ch = chPtr2[0];\n if (ch <= '>')\n {\n switch (ch)\n {\n case '&':\n case '\\'':\n case '\"':\n case '<':\n case '>':\n return (s.Length - num);\n\n case '=':\n goto Label_0086;\n }\n }\n else if ((ch >= '\\x00a0') && (ch < 'Ā'))\n {\n return (s.Length - num);\n }\n Label_0086:\n chPtr2++;\n num--;\n }\n }\n return -1;\n }\n\n // Nested Types\n private static class HtmlEntities\n {\n // Fields\n private static string[] _entitiesList = new string[] { \n \"\\\"-quot\", \"&-amp\", \"'-apos\", \"<-lt\", \">-gt\", \"\\x00a0-nbsp\", \"\\x00a1-iexcl\", \"\\x00a2-cent\", \"\\x00a3-pound\", \"\\x00a4-curren\", \"\\x00a5-yen\", \"\\x00a6-brvbar\", \"\\x00a7-sect\", \"\\x00a8-uml\", \"\\x00a9-copy\", \"\\x00aa-ordf\", \n \"\\x00ab-laquo\", \"\\x00ac-not\", \"\\x00ad-shy\", \"\\x00ae-reg\", \"\\x00af-macr\", \"\\x00b0-deg\", \"\\x00b1-plusmn\", \"\\x00b2-sup2\", \"\\x00b3-sup3\", \"\\x00b4-acute\", \"\\x00b5-micro\", \"\\x00b6-para\", \"\\x00b7-middot\", \"\\x00b8-cedil\", \"\\x00b9-sup1\", \"\\x00ba-ordm\", \n \"\\x00bb-raquo\", \"\\x00bc-frac14\", \"\\x00bd-frac12\", \"\\x00be-frac34\", \"\\x00bf-iquest\", \"\\x00c0-Agrave\", \"\\x00c1-Aacute\", \"\\x00c2-Acirc\", \"\\x00c3-Atilde\", \"\\x00c4-Auml\", \"\\x00c5-Aring\", \"\\x00c6-AElig\", \"\\x00c7-Ccedil\", \"\\x00c8-Egrave\", \"\\x00c9-Eacute\", \"\\x00ca-Ecirc\", \n \"\\x00cb-Euml\", \"\\x00cc-Igrave\", \"\\x00cd-Iacute\", \"\\x00ce-Icirc\", \"\\x00cf-Iuml\", \"\\x00d0-ETH\", \"\\x00d1-Ntilde\", \"\\x00d2-Ograve\", \"\\x00d3-Oacute\", \"\\x00d4-Ocirc\", \"\\x00d5-Otilde\", \"\\x00d6-Ouml\", \"\\x00d7-times\", \"\\x00d8-Oslash\", \"\\x00d9-Ugrave\", \"\\x00da-Uacute\", \n \"\\x00db-Ucirc\", \"\\x00dc-Uuml\", \"\\x00dd-Yacute\", \"\\x00de-THORN\", \"\\x00df-szlig\", \"\\x00e0-agrave\", \"\\x00e1-aacute\", \"\\x00e2-acirc\", \"\\x00e3-atilde\", \"\\x00e4-auml\", \"\\x00e5-aring\", \"\\x00e6-aelig\", \"\\x00e7-ccedil\", \"\\x00e8-egrave\", \"\\x00e9-eacute\", \"\\x00ea-ecirc\", \n \"\\x00eb-euml\", \"\\x00ec-igrave\", \"\\x00ed-iacute\", \"\\x00ee-icirc\", \"\\x00ef-iuml\", \"\\x00f0-eth\", \"\\x00f1-ntilde\", \"\\x00f2-ograve\", \"\\x00f3-oacute\", \"\\x00f4-ocirc\", \"\\x00f5-otilde\", \"\\x00f6-ouml\", \"\\x00f7-divide\", \"\\x00f8-oslash\", \"\\x00f9-ugrave\", \"\\x00fa-uacute\", \n \"\\x00fb-ucirc\", \"\\x00fc-uuml\", \"\\x00fd-yacute\", \"\\x00fe-thorn\", \"\\x00ff-yuml\", \"Œ-OElig\", \"œ-oelig\", \"Š-Scaron\", \"š-scaron\", \"Ÿ-Yuml\", \"ƒ-fnof\", \"ˆ-circ\", \"˜-tilde\", \"Α-Alpha\", \"Β-Beta\", \"Γ-Gamma\", \n \"Δ-Delta\", \"Ε-Epsilon\", \"Ζ-Zeta\", \"Η-Eta\", \"Θ-Theta\", \"Ι-Iota\", \"Κ-Kappa\", \"Λ-Lambda\", \"Μ-Mu\", \"Ν-Nu\", \"Ξ-Xi\", \"Ο-Omicron\", \"Π-Pi\", \"Ρ-Rho\", \"Σ-Sigma\", \"Τ-Tau\", \n \"Υ-Upsilon\", \"Φ-Phi\", \"Χ-Chi\", \"Ψ-Psi\", \"Ω-Omega\", \"α-alpha\", \"β-beta\", \"γ-gamma\", \"δ-delta\", \"ε-epsilon\", \"ζ-zeta\", \"η-eta\", \"θ-theta\", \"ι-iota\", \"κ-kappa\", \"λ-lambda\", \n \"μ-mu\", \"ν-nu\", \"ξ-xi\", \"ο-omicron\", \"π-pi\", \"ρ-rho\", \"ς-sigmaf\", \"σ-sigma\", \"τ-tau\", \"υ-upsilon\", \"φ-phi\", \"χ-chi\", \"ψ-psi\", \"ω-omega\", \"ϑ-thetasym\", \"ϒ-upsih\", \n \"ϖ-piv\", \" -ensp\", \" -emsp\", \" -thinsp\", \"-zwnj\", \"-zwj\", \"-lrm\", \"-rlm\", \"–-ndash\", \"—-mdash\", \"‘-lsquo\", \"’-rsquo\", \"‚-sbquo\", \"“-ldquo\", \"”-rdquo\", \"„-bdquo\", \n \"†-dagger\", \"‡-Dagger\", \"•-bull\", \"…-hellip\", \"‰-permil\", \"′-prime\", \"″-Prime\", \"‹-lsaquo\", \"›-rsaquo\", \"‾-oline\", \"⁄-frasl\", \"€-euro\", \"ℑ-image\", \"℘-weierp\", \"ℜ-real\", \"™-trade\", \n \"ℵ-alefsym\", \"←-larr\", \"↑-uarr\", \"→-rarr\", \"↓-darr\", \"↔-harr\", \"↵-crarr\", \"⇐-lArr\", \"⇑-uArr\", \"⇒-rArr\", \"⇓-dArr\", \"⇔-hArr\", \"∀-forall\", \"∂-part\", \"∃-exist\", \"∅-empty\", \n \"∇-nabla\", \"∈-isin\", \"∉-notin\", \"∋-ni\", \"∏-prod\", \"∑-sum\", \"−-minus\", \"∗-lowast\", \"√-radic\", \"∝-prop\", \"∞-infin\", \"∠-ang\", \"∧-and\", \"∨-or\", \"∩-cap\", \"∪-cup\", \n \"∫-int\", \"∴-there4\", \"∼-sim\", \"≅-cong\", \"≈-asymp\", \"≠-ne\", \"≡-equiv\", \"≤-le\", \"≥-ge\", \"⊂-sub\", \"⊃-sup\", \"⊄-nsub\", \"⊆-sube\", \"⊇-supe\", \"⊕-oplus\", \"⊗-otimes\", \n \"⊥-perp\", \"⋅-sdot\", \"⌈-lceil\", \"⌉-rceil\", \"⌊-lfloor\", \"⌋-rfloor\", \"〈-lang\", \"〉-rang\", \"◊-loz\", \"♠-spades\", \"♣-clubs\", \"♥-hearts\", \"♦-diams\"\n };\n private static Dictionary<string, char> _lookupTable = GenerateLookupTable();\n\n // Methods\n private static Dictionary<string, char> GenerateLookupTable()\n {\n Dictionary<string, char> dictionary = new Dictionary<string, char>(StringComparer.Ordinal);\n foreach (string str in _entitiesList)\n {\n dictionary.Add(str.Substring(2), str[0]);\n }\n return dictionary;\n }\n\n public static char Lookup(string entity)\n {\n char ch;\n _lookupTable.TryGetValue(entity, out ch);\n return ch;\n }\n }\n}\n"
},
{
"answer_id": 4480633,
"author": "Almund",
"author_id": 479632,
"author_profile": "https://Stackoverflow.com/users/479632",
"pm_score": 5,
"selected": false,
"text": "Uri.EscapeDataString(...)\nWebUtility.HtmlEncode(...)\n"
},
{
"answer_id": 8517661,
"author": "coolaj86",
"author_id": 151312,
"author_profile": "https://Stackoverflow.com/users/151312",
"pm_score": 2,
"selected": false,
"text": "wget 'http://google-gdata.googlecode.com/svn/trunk/clients/cs/src/core/HttpUtility.cs'\ngmcs -t:library HttpUtility.cs\n your-project.cs using Google.GData.Client; // where HttpUtility lives\n gmcs your-project.cs -r:System.Web.Services -r:System.Web -r:HttpUtility\n .NET 2.0"
},
{
"answer_id": 12789657,
"author": "hfrmobile",
"author_id": 254829,
"author_profile": "https://Stackoverflow.com/users/254829",
"pm_score": 2,
"selected": false,
"text": " private static string HtmlDecode(string text)\n {\n#if WINDOWS_PHONE\n return System.Net.HttpUtility.HtmlDecode(text);\n#else\n return System.Net.WebUtility.HtmlDecode(text);\n#endif\n }\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
36,326 |
<p>I know it is a good idea to store configuration data in app.config (e.g. database connection strings) instead of hardcoing it, even if I am writing an application just for myself. But is there a way to update the configuration data stored in app.config from the program that is using it?</p>
|
[
{
"answer_id": 36335,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "a UserScopedSettingAttribute"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3205/"
] |
36,344 |
<p>I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.</p>
<p>I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it <em>does</em> show the symbol.</p>
<p>I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.</p>
<p>What else could it be, and how can I try to fix?</p>
<p>Here's the excerpt from running make test:</p>
<pre><code>PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t
t/01basic...........1/4
# Failed test 'use SGML::Parser::OpenSP;'
# at t/01basic.t line 14.
# Tried to use 'SGML::Parser::OpenSP'.
# Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication
# Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle
# Expected in: dynamic lookup
# at (eval 3) line 2
# Compilation failed in require at (eval 3) line 2.
# BEGIN failed--compilation aborted at (eval 3) line 2.
</code></pre>
|
[
{
"answer_id": 36335,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "a UserScopedSettingAttribute"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
36,347 |
<p>Java has generics and C++ provides a very strong programming model with <code>template</code>s.
So then, what is the difference between C++ and Java generics?</p>
|
[
{
"answer_id": 36364,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 8,
"selected": true,
"text": "template <typename T> T sum(T a, T b) { return a + b; }\n <T extends Something> T sum(T a, T b) { return a.add ( b ); }\n Something sum(Something a, Something b) { return a.add ( b ); }\n"
},
{
"answer_id": 41930,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "template <typename T> T sum(T a, T b) { return a + b; }\ntemplate <typename T> T sum(T* a, T* b) { return (*a) + (*b); }\nSpecial sum(const Special& a, const Special& b) { return a.plus(b); }\n sum Special"
},
{
"answer_id": 41973,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "template template <typename T> T sum(T a, T b) { return a + b; }\ntemplate <typename T> T sum(T* a, T* b) { return (*a) + (*b); }\n"
},
{
"answer_id": 498329,
"author": "cletus",
"author_id": 18393,
"author_profile": "https://Stackoverflow.com/users/18393",
"pm_score": 7,
"selected": false,
"text": "#define int public class PhoneNumbers {\n private Map phoneNumbers = new HashMap();\n \n public String getPhoneNumber(String name) {\n return (String) phoneNumbers.get(name);\n }\n}\n public class PhoneNumbers {\n private Map<String, String> phoneNumbers = new HashMap<String, String>();\n \n public String getPhoneNumber(String name) {\n return phoneNumbers.get(name);\n }\n}\n Map<String, String> Map IEnumerable IEnumerable<T> template<class T, int i>\nclass Matrix {\n int T[i][i];\n ...\n}\n public class ObservableList<T extends List> {\n ...\n}\n"
},
{
"answer_id": 18420523,
"author": "MigMit",
"author_id": 1722752,
"author_profile": "https://Stackoverflow.com/users/1722752",
"pm_score": 0,
"selected": false,
"text": "import java.io.*;\ninterface ScalarProduct<A> {\n public Integer scalarProduct(A second);\n}\nclass Nil implements ScalarProduct<Nil>{\n Nil(){}\n public Integer scalarProduct(Nil second) {\n return 0;\n }\n}\nclass Cons<A implements ScalarProduct<A>> implements ScalarProduct<Cons<A>>{\n public Integer value;\n public A tail;\n Cons(Integer _value, A _tail) {\n value = _value;\n tail = _tail;\n }\n public Integer scalarProduct(Cons<A> second){\n return value * second.value + tail.scalarProduct(second.tail);\n }\n}\nclass _Test{\n public static Integer main(Integer n){\n return _main(n, 0, new Nil(), new Nil());\n }\n public static <A implements ScalarProduct<A>> \n Integer _main(Integer n, Integer i, A first, A second){\n if (n == 0) {\n return first.scalarProduct(second);\n } else {\n return _main(n-1, i+1, \n new Cons<A>(2*i+1,first), new Cons<A>(i*i, second));\n //the following line won't compile, it produces an error:\n //return _main(n-1, i+1, first, new Cons<A>(i*i, second));\n }\n }\n}\npublic class Test{\n public static void main(String [] args){\n System.out.print(\"Enter a number: \");\n try {\n BufferedReader is = \n new BufferedReader(new InputStreamReader(System.in));\n String line = is.readLine();\n Integer val = Integer.parseInt(line);\n System.out.println(_Test.main(val));\n } catch (NumberFormatException ex) {\n System.err.println(\"Not a valid number\");\n } catch (IOException e) {\n System.err.println(\"Unexpected IO ERROR\");\n }\n }\n}\n"
},
{
"answer_id": 51124855,
"author": "Jswq",
"author_id": 5579519,
"author_profile": "https://Stackoverflow.com/users/5579519",
"pm_score": 2,
"selected": false,
"text": "Vector<String> vector = new Vector<String>();\nvector.add(new String(\"hello\"));\nString str = vector.get(0);\n Vector vector = new Vector();\nvector.add(new String(\"hello\"));\nString str = (String) vector.get(0);\n /*** MyClass.h ***/\n template<class T> class MyClass {\n public:\n static int val;\n MyClass(int v) { val v;}\n };\n /*** MyClass.cpp ***/\n template<typename T>\n int MyClass<T>::bar;\n\n template class MyClass<Foo>;\n template class MyClass<Bar>;\n\n /*** main.cpp ***/\n MyClass<Foo> * fool\n MyClass<Foo> * foo2\n MyClass<Bar> * barl\n MyClass<Bar> * bar2\n\n new MyClass<Foo>(10);\n new MyClass<Foo>(15);\n new MyClass<Bar>(20);\n new MyClass<Bar>(35);\n int fl fool->val; // will equal 15\n int f2 foo2->val; // will equal 15\n int bl barl->val; // will equal 35\n int b2 bar2->val; // will equal 35\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556/"
] |
36,350 |
<p>I have a method which takes params object[] such as:</p>
<pre><code>void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
</code></pre>
<p>When I pass two object arrays to this method, it works fine:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
</code></pre>
<p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p>
<pre><code>Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]
</code></pre>
<p>How do I pass a single object[] as a first argument to a params array?</p>
|
[
{
"answer_id": 36360,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "Foo(new Object[] { new object[]{ (object)\"1\", (object)\"2\" }});\n"
},
{
"answer_id": 36361,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "Foo(new object[]{ new object[]{ (object)\"1\", (object)\"2\" } });\n Foo((object) new object[]{ (object)\"1\", (object)\"2\" });\n void Foo(object[] item)\n{\n // Somehow don't duplicate Foo(object[]) and\n // Foo(params object[]) without making an infinite\n // recursive call... maybe something like\n // FooImpl(params object[] items) and then this\n // could invoke it via:\n // FooImpl(new object[] { item });\n}\n"
},
{
"answer_id": 36367,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 8,
"selected": true,
"text": "Foo((object)new object[]{ (object)\"1\", (object)\"2\" }));\n"
},
{
"answer_id": 38123,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 6,
"selected": false,
"text": "params params params object[] array = new[] { \"1\", \"2\" };\n\n// Foo receives the 'array' argument directly.\nFoo( array );\n // Foo receives a temporary array containing the list of arguments.\nFoo( \"1\", \"2\" );\n\n// This is equivalent to:\nobject[] temp = new[] { \"1\", \"2\" );\nFoo( temp );\n params object[] Foo( new object[] { array } ); // Equivalent to calling convention 1.\n object Foo( (object)array ); // Equivalent to calling convention 2.\n params object[][] void Foo( params object[][] arrays ) {\n foreach( object[] array in arrays ) {\n // process array\n }\n}\n\n...\nFoo( new[] { \"1\", \"2\" }, new[] { \"3\", \"4\" } );\n\n// Equivalent to:\nobject[][] arrays = new[] {\n new[] { \"1\", \"2\" },\n new[] { \"3\", \"4\" }\n};\nFoo( arrays );\n"
},
{
"answer_id": 11148337,
"author": "HoBa",
"author_id": 662165,
"author_profile": "https://Stackoverflow.com/users/662165",
"pm_score": 1,
"selected": false,
"text": "new[] { (object) 0, (object) null, (object) false }\n"
},
{
"answer_id": 35474769,
"author": "ACOMIT001",
"author_id": 3713362,
"author_profile": "https://Stackoverflow.com/users/3713362",
"pm_score": 3,
"selected": false,
"text": "var elements = new String[] { \"1\", \"2\", \"3\" };\nFoo(elements.Cast<object>().ToArray())\n"
},
{
"answer_id": 49778932,
"author": "Zhuravlev A.",
"author_id": 9112327,
"author_profile": "https://Stackoverflow.com/users/9112327",
"pm_score": 2,
"selected": false,
"text": "static class Helper\n{\n public static object AsSingleParam(this object[] arg)\n {\n return (object)arg;\n }\n}\n f(new object[] { 1, 2, 3 }.AsSingleParam());\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
36,407 |
<p>What Firefox add-ons do you use that are useful for programmers?</p>
|
[
{
"answer_id": 36433,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 1,
"selected": false,
"text": "Miscellaneous Display Ruler"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3305/"
] |
36,417 |
<p>What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.</p>
<p>I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.</p>
<p>What can I be doing better in my PHP development?</p>
|
[
{
"answer_id": 36428,
"author": "different",
"author_id": 3654,
"author_profile": "https://Stackoverflow.com/users/3654",
"pm_score": 0,
"selected": false,
"text": "$userName = \"John Doe\";\n$dateOfBirth = \"04/02/1982\";\n\nfunction calculateUserAgeFromBirth($userName, $dateOfBirth)\n"
},
{
"answer_id": 36444,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 5,
"selected": true,
"text": "<?php \n$people = array('derek','joel','jeff');\n$people[0] = 'martin'; // all your logic goes here\ninclude 'templates/people.php';\n?>\n <html> \n<body>\n<?php foreach($people as $name):?>\n <b>Person:</b> <?=$name?> <br />\n<?php endforeach;?> \n</body>\n</html>\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3800/"
] |
36,430 |
<p>I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there?</p>
<p>Since it might matter, I'm running Windows.</p>
|
[
{
"answer_id": 36452,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "sudo gem install gemname\nsudo gem update gemname\n"
},
{
"answer_id": 36463,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 1,
"selected": false,
"text": "cmd --help gem sudo gem update [gemname]\n man cmd cheat cmd sudo gem install cheat\n cheat gem\n"
},
{
"answer_id": 39103,
"author": "Wes Oldenbeuving",
"author_id": 4187,
"author_profile": "https://Stackoverflow.com/users/4187",
"pm_score": 5,
"selected": true,
"text": "gem update <gemname>\n gem install <gemname> -v <gemversion>\n gem help\n gem help commands\n gem help update\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
36,455 |
<p>Older K&R (2nd ed.) and other C-language texts I have read that discuss the implementation of a dynamic memory allocator in the style of <code>malloc()</code> and <code>free()</code> usually also mention, in passing, something about data type alignment restrictions. Apparently certain computer hardware architectures (CPU, registers, and memory access) restrict how you can store and address certain value types. For example, there may be a requirement that a 4 byte (<code>long</code>) integer must be stored beginning at addresses that are multiples of four.</p>
<p>What restrictions, if any, do major platforms (Intel & AMD, SPARC, Alpha) impose for memory allocation and memory access, or can I safely ignore aligning memory allocations on specific address boundaries?</p>
|
[
{
"answer_id": 36466,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 1,
"selected": false,
"text": "struct\n{ \n char A;\n int B;\n char C;\n int D;\n};\n struct\n{ \n char A;\n char C;\n int B;\n int D;\n};\n"
},
{
"answer_id": 36544,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 1,
"selected": false,
"text": "// For example, this changes the pack to 2 byte alignment.\n#pragma pack(2)\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
36,475 |
<p>What would be the best way to design a threaded commenting system so that it doesn't hammer the database?</p>
|
[
{
"answer_id": 36629,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 2,
"selected": false,
"text": "select * from my_table\n start with parent = :TOP_ARTICLE\n connect by prior child = parent;\n"
}
] |
2008/08/30
|
[
"https://Stackoverflow.com/questions/36475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1745/"
] |
36,498 |
<p>I would like to quickly send email from the command line. I realize there are probably a number of different ways to do this.</p>
<p>I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows. I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program. How would you go about doing this? If you have small scripts that would be fine as well.</p>
|
[
{
"answer_id": 36499,
"author": "aryeh",
"author_id": 3288,
"author_profile": "https://Stackoverflow.com/users/3288",
"pm_score": 4,
"selected": false,
"text": "$ echo \"This is the email body\" | mail -s \"This is the subject\" [email protected]\n $ cat | mail -s \"A few lines off the top of my head\" [email protected]\nThis is where my\nmultiline\nmessage would go\n^D\n"
},
{
"answer_id": 36500,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": true,
"text": "$mail -s <subject> <recipients>\n $<mail-generating-program> | mail -s <subject> <recipients>\n"
},
{
"answer_id": 36548,
"author": "Brendan",
"author_id": 199,
"author_profile": "https://Stackoverflow.com/users/199",
"pm_score": 2,
"selected": false,
"text": "mail"
},
{
"answer_id": 804411,
"author": "Philibert Perusse",
"author_id": 7984,
"author_profile": "https://Stackoverflow.com/users/7984",
"pm_score": 2,
"selected": false,
"text": "$smtp = new-object Net.Mail.SmtpClient(\"mail.example.com\")\n\nif( $Env:SmtpUseCredentials -eq \"true\" ) {\n $credentials = new-object Net.NetworkCredential(\"username\",\"password\")\n $smtp.Credentials = $credentials\n}\n$objMailMessage = New-Object System.Net.Mail.MailMessage\n$objMailMessage.From = \"[email protected]\"\n$objMailMessage.To.Add(\"[email protected]\")\n$objMailMessage.Subject = \"eMail subject Notification\"\n$objMailMessage.Body = \"Hello world!\"\n\n$smtp.send($objMailMessage)\n"
},
{
"answer_id": 2477883,
"author": "Philibert Perusse",
"author_id": 7984,
"author_profile": "https://Stackoverflow.com/users/7984",
"pm_score": 2,
"selected": false,
"text": "echo To: [email protected], [email protected] >> the.mail\necho From: [email protected] >> the.mail\necho Subject: This is a SENDMAIL notification >> the.mail\necho Hello World! >> the.mail\necho This is simple enough. >> the.mail\necho .>> the.mail\n \\usr\\lib\\sendmail.exe -t < the.mail\n\ntype the.mail | C:\\Projects\\Tools\\sendmail.exe -t\n"
},
{
"answer_id": 6938756,
"author": "jimmy",
"author_id": 878221,
"author_profile": "https://Stackoverflow.com/users/878221",
"pm_score": 1,
"selected": false,
"text": "#! /usr/bin/php\n<?php\n\nif ($argc < 3) {\n echo \"Usage: \" . basename($argv[0]) . \" TO SUBJECT [CC]\\n\";\n exit(1);\n}\n\n$message = file_get_contents('php://stdin', 'r');\n$headers = $argc >= 4 ? \"Cc: $argv[3]\\r\\n\" : null;\n\n$ret = mail($argv[1], $argv[2], $message, $headers);\n\nexit($ret ? 0 : 1);\n mail [email protected] test < message\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/792/"
] |
36,502 |
<p>I know Windows Vista (and XP) cache recently loaded DLL's in memory...</p>
<p>How can this be disabled via the command prompt?</p>
|
[
{
"answer_id": 36529,
"author": "The How-To Geek",
"author_id": 291,
"author_profile": "https://Stackoverflow.com/users/291",
"pm_score": 4,
"selected": true,
"text": "sc config Superfetch start= disabled\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
36,504 |
<p>I see a lot of talk on here about functional languages and stuff. Why would you use one over a "traditional" language? What do they do better? What are they worse at? What's the ideal functional programming application?</p>
|
[
{
"answer_id": 1440354,
"author": "RD1",
"author_id": 175097,
"author_profile": "https://Stackoverflow.com/users/175097",
"pm_score": 3,
"selected": false,
"text": "* The average corporate programmer, e.g. most of the people I work with, will not understand it and most work environments will not let you program in it\n* It's not really taught at universities (or is it nowadays?)\n* Most applications are simple enough to be solved in normal IMPERATIVE ways\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/655/"
] |
36,511 |
<p>I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties:</p>
<pre><code>For Each pi As PropertyInfo In person.GetType().GetProperties()
Dim column As New DataColumn(pi.Name, pi.PropertyType)
table.Columns.Add(column)
Next
</code></pre>
<p>My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 36519,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))\n"
},
{
"answer_id": 44108,
"author": "Ed Schwehm",
"author_id": 1206,
"author_profile": "https://Stackoverflow.com/users/1206",
"pm_score": 0,
"selected": false,
"text": "Dim i As Nullable(Of Integer) = Nothing\nDim t As Type = i.GetValueOrDefault().GetType()\n"
},
{
"answer_id": 44115,
"author": "Anderson Imes",
"author_id": 3244,
"author_profile": "https://Stackoverflow.com/users/3244",
"pm_score": 1,
"selected": false,
"text": "GetGenericParameters() myNullableObject.GetType().GetGenericParameters()[0] Guid Int32"
},
{
"answer_id": 752620,
"author": "Brian MacKay",
"author_id": 16082,
"author_profile": "https://Stackoverflow.com/users/16082",
"pm_score": 4,
"selected": false,
"text": "Private Function IsNullableType(ByVal myType As Type) As Boolean\n Return (myType.IsGenericType) AndAlso (myType.GetGenericTypeDefinition() Is GetType(Nullable(Of )))\nEnd Function\n If (Not value Is Nothing) AndAlso IsNullableType(GetType(T)) Then\n Dim UnderlyingType As Type = Nullable.GetUnderlyingType(GetType(T))\n Me.InnerValue = Convert.ChangeType(value, UnderlyingType)\nElse\n Me.InnerValue = value\nEnd If\n"
},
{
"answer_id": 2028329,
"author": "herzmeister",
"author_id": 90742,
"author_profile": "https://Stackoverflow.com/users/90742",
"pm_score": 2,
"selected": false,
"text": "Nullable.GetUnderylingType(myType)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
36,515 |
<p>I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized. </p>
<p>I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a <code><a href="http://code.google.com/apis/maps/documentation/reference.html#GScreenOverlay" rel="nofollow noreferrer">GScreenOverlay</a></code> class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?</p>
|
[
{
"answer_id": 36821,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 2,
"selected": false,
"text": "<div id=\"wrapper\">\n <div id=\"map\" style=\"width:400px;height:400px;\"></div>\n <div id=\"legend\"> ... marker descriptions in here ... </div>\n</div>\n div#wrapper { position: relative; }\ndiv#legend { position: absolute; bottom: 0px; right: 0px; }\n position: relative #wrapper position: absolute #legend #wrapper"
},
{
"answer_id": 42792,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 4,
"selected": true,
"text": "function MyPane() {}\nMyPane.prototype = new GControl;\nMyPane.prototype.initialize = function(map) {\n var me = this;\n me.panel = document.createElement(\"div\");\n me.panel.style.width = \"150px\";\n me.panel.style.height = \"100px\";\n me.panel.style.border = \"1px solid gray\";\n me.panel.style.background = \"white\";\n me.panel.innerHTML = \"Hello World!\";\n map.getContainer().appendChild(me.panel);\n return me.panel;\n};\n\nMyPane.prototype.getDefaultPosition = function() {\n return new GControlPosition(\n G_ANCHOR_TOP_RIGHT, new GSize(10, 50));\n //Should be _ and not _\n};\n\nMyPane.prototype.getPanel = function() {\n return me.panel;\n}\nmap.addControl(new MyPane());\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1482/"
] |
36,533 |
<p>my primary language is spanish, but I use all my software in english, including windows; however I'd like to use speech recognition in spanish.</p>
<p>Do you know if there's a way to use vista's speech recognition in other language than the primary os language?</p>
|
[
{
"answer_id": 483699,
"author": "guerda",
"author_id": 32043,
"author_profile": "https://Stackoverflow.com/users/32043",
"pm_score": 2,
"selected": false,
"text": "Windows Speech Recognition \"change language\""
},
{
"answer_id": 1441205,
"author": "Eric Brown",
"author_id": 175201,
"author_profile": "https://Stackoverflow.com/users/175201",
"pm_score": 2,
"selected": false,
"text": "using System.Speech.Recognition;\nSpeechRecognitionEngine recognizer = new SpeechRecognitionEngine(new CultureInfo(\"es-ES\"));\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
36,563 |
<p>I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.</p>
<p>I'd really love for that form to be transparent and to have the transparency be user-configurable.</p>
<p>Is there any easy way to achieve this?</p>
|
[
{
"answer_id": 36576,
"author": "Eric Haskins",
"author_id": 100,
"author_profile": "https://Stackoverflow.com/users/100",
"pm_score": 0,
"selected": false,
"text": "Form.Opacity"
},
{
"answer_id": 36577,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 3,
"selected": true,
"text": "private Sub CreateMyOpaqueForm()\n ' Create a new form.\n Dim form2 As New Form()\n ' Set the text displayed in the caption.\n form2.Text = \"My Form\"\n ' Set the opacity to 75%.\n form2.Opacity = 0.75\n ' Size the form to be 300 pixels in height and width.\n form2.Size = New Size(300, 300)\n ' Display the form in the center of the screen.\n form2.StartPosition = FormStartPosition.CenterScreen\n\n ' Display the form as a modal dialog box.\n form2.ShowDialog()\nEnd Sub\n"
},
{
"answer_id": 36578,
"author": "Ethan Gunderson",
"author_id": 2066,
"author_profile": "https://Stackoverflow.com/users/2066",
"pm_score": 0,
"selected": false,
"text": "Form.Opacity = 0.0 While Sleep"
},
{
"answer_id": 36597,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 0,
"selected": false,
"text": "AllowTransparency = True"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
36,567 |
<p>I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.</p>
|
[
{
"answer_id": 38203,
"author": "secr",
"author_id": 4085,
"author_profile": "https://Stackoverflow.com/users/4085",
"pm_score": 4,
"selected": true,
"text": "typedef struct _WAVstruct\n{\n char headertag[4];\n unsigned int remnantlength;\n char fileid[4];\n\n char fmtchunktag[4];\n unsigned int fmtlength;\n unsigned short fmttag;\n unsigned short channels;\n unsigned int samplerate;\n unsigned int bypse;\n unsigned short ba;\n unsigned short bipsa;\n\n char datatag[4];\n unsigned int datalength;\n\n void* data; //<--- that's where the raw sound-data goes\n}* WAVstruct;\n int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result)\n{\n result->headertag[0] = 'R';\n result->headertag[1] = 'I';\n result->headertag[2] = 'F';\n result->headertag[3] = 'F';\n result->remnantlength = 44 + datalength - 8;\n result->fileid[0] = 'W';\n result->fileid[1] = 'A';\n result->fileid[2] = 'V';\n result->fileid[3] = 'E';\n\n result->fmtchunktag[0] = 'f';\n result->fmtchunktag[1] = 'm'; \n result->fmtchunktag[2] = 't';\n result->fmtchunktag[3] = ' ';\n result->fmtlength = 0x00000010;\n result->fmttag = 1;\n result->channels = channels;\n result->samplerate = samplerate;\n result->bipsa = bipsa;\n result->ba = channels*bipsa / 8;\n result->bypse = samplerate*result->ba;\n\n result->datatag[0] = 'd';\n result->datatag[1] = 'a';\n result->datatag[2] = 't';\n result->datatag[3] = 'a';\n result->datalength = datalength;\n\n result->data = data; // <--- that's were the data comes in\n\n return 0; // an error code, not implemented, yet ...; in Java: return result\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
36,585 |
<p>I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table?</p>
|
[
{
"answer_id": 36592,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 1,
"selected": false,
"text": "desc tablename;\n SELECT *, LENGTH(fieldname) AS len FROM tablename\n"
},
{
"answer_id": 2943468,
"author": "sivasankar",
"author_id": 354574,
"author_profile": "https://Stackoverflow.com/users/354574",
"pm_score": 1,
"selected": false,
"text": "SELECT LEN(columnName) AS MyLength FROM myTable\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1208/"
] |
36,605 |
<p>What is the simplest and most elegant way to simulate the hover pseudo-class for non-Anchor tags in IE6?</p>
<p>I am specifically trying to change the cursor in this instance to that of a pointer.</p>
|
[
{
"answer_id": 36609,
"author": "Jon Galloway",
"author_id": 5,
"author_profile": "https://Stackoverflow.com/users/5",
"pm_score": 4,
"selected": false,
"text": "body { behavior:url(\"csshover.htc\"); }\n"
},
{
"answer_id": 36892,
"author": "Nathan Peretic",
"author_id": 3741,
"author_profile": "https://Stackoverflow.com/users/3741",
"pm_score": 3,
"selected": false,
"text": "cursor:pointer div <div style=\"background:orange; cursor:pointer; height:100px; width:100px;\">\n Hover\n</div>\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3821/"
] |
36,608 |
<p>I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.</p>
<p>Something like:</p>
<pre><code>Record.find(:all).date.unique.count
</code></pre>
<p>but of course, that doesn't seem to work.</p>
|
[
{
"answer_id": 36618,
"author": "Natalie Weizenbaum",
"author_id": 2518,
"author_profile": "https://Stackoverflow.com/users/2518",
"pm_score": 7,
"selected": true,
"text": "SELECT COUNT(DISTINCT date) FROM records\n Record.count('date', :distinct => true)\n"
},
{
"answer_id": 40293,
"author": "m104",
"author_id": 4039,
"author_profile": "https://Stackoverflow.com/users/4039",
"pm_score": 4,
"selected": false,
"text": "Record.find(:all).group_by(&:date).count\n"
},
{
"answer_id": 19362288,
"author": "Yule",
"author_id": 671422,
"author_profile": "https://Stackoverflow.com/users/671422",
"pm_score": 7,
"selected": false,
"text": ":distinct => true Record.distinct.count('date')\n Record.group(:date).distinct.count(:date)\n"
},
{
"answer_id": 24914018,
"author": "leompeters",
"author_id": 2334082,
"author_profile": "https://Stackoverflow.com/users/2334082",
"pm_score": 3,
"selected": false,
"text": "Post.create(:user_id => 1, :created_on => '2010-09-29')\nPost.create(:user_id => 1, :created_on => '2010-09-29')\nPost.create(:user_id => 2, :created_on => '2010-09-29')\nPost.create(:user_id => null, :created_on => '2010-09-29')\n\nPost.group(:created_on).count\n# => {'2010-09-29' => 4}\n\nPost.group(:created_on).count(:user_id)\n# => {'2010-09-29' => 3}\n\nPost.group(:created_on).count(:user_id, :distinct => true) # Rails <= 3\nPost.group(:created_on).distinct.count(:user_id) # Rails = 4\n# => {'2010-09-29' => 2}\n"
},
{
"answer_id": 33089317,
"author": "JacobEvelyn",
"author_id": 1103543,
"author_profile": "https://Stackoverflow.com/users/1103543",
"pm_score": 3,
"selected": false,
"text": "(...).uniq.count(:user_id) DISTINCT SELECT DISTINCT COUNT(DISTINCT user_id) FROM ... (...).count(\"DISTINCT user_id\") SELECT COUNT(DISTINCT user_id) FROM ..."
},
{
"answer_id": 44671200,
"author": "Yi Feng Xie",
"author_id": 2047546,
"author_profile": "https://Stackoverflow.com/users/2047546",
"pm_score": 4,
"selected": false,
"text": "#count Record.count('DISTINCT date')\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36608",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3764/"
] |
36,621 |
<p>I'm taking the leap: my PHP scripts will ALL fail gracefully!</p>
<p>At least, that's what I'm hoping for...`</p>
<p>I don't want to wrap (practically) every single line in <code>try...catch</code> statements, so I think my best bet is to make a custom error handler for the beginning of my files.</p>
<p>I'm testing it out on a practice page:</p>
<pre><code>function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
echo($imAFakeVariable);
</code></pre>
<p>This works fine, returning:</p>
<blockquote>
<p>Sorry, an error has occurred on line 17. The function that caused the
error says Undefined variable: imAFakeVariable.</p>
</blockquote>
<p>However, this setup doesn't work for undefined functions.</p>
<pre><code>function customError($level,$message,$file,$line,$context) {
echo "Sorry, an error has occured on line $line.<br />";
echo "The function that caused the error says $message.<br />";
die();
}
set_error_handler("customError");
imAFakeFunction();
</code></pre>
<p>This returns:</p>
<blockquote>
<p>Fatal error: Call to undefined function: imafakefunction() in
/Library/WebServer/Documents/experimental/errorhandle.php on line 17</p>
</blockquote>
<p>Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?</p>
|
[
{
"answer_id": 36625,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 1,
"selected": false,
"text": "try..catch"
},
{
"answer_id": 36705,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 5,
"selected": true,
"text": "set_error_handler E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE set_error_handler trigger_error E_ERROR E_PARSE E_CORE_ERROR E_CORE_WARNING E_COMPILE_ERROR E_COMPILE_WARNING E_STRICT set_error_handler() set_error_handler() ob_start() E_ERROR <?php\n\nfunction error_handler($output)\n{\n $error = error_get_last();\n $output = \"\";\n foreach ($error as $info => $string)\n $output .= \"{$info}: {$string}\\n\";\n return $output;\n}\n\nob_start('error_handler');\n\nwill_this_undefined_function_raise_an_error();\n\n?>\n E_PARSE"
},
{
"answer_id": 5471570,
"author": "ShRi Ram",
"author_id": 681921,
"author_profile": "https://Stackoverflow.com/users/681921",
"pm_score": 3,
"selected": false,
"text": "register_shutdown_function register_shutdown_function( array( $this, 'customError' ));.\n\n function customError() \n {\n\n $arrStrErrorInfo = error_get_last();\n\n print_r( $arrStrErrorInfo );\n\n }\n"
},
{
"answer_id": 11768333,
"author": "Spencer Mark",
"author_id": 1417500,
"author_profile": "https://Stackoverflow.com/users/1417500",
"pm_score": 0,
"selected": false,
"text": "ini_set('display_errors', 'Off');\nerror_reporting(-1);\n\nset_error_handler(array(\"Cmd\\Exception\\Handler\", \"getError\"), -1 & ~E_NOTICE & ~E_USER_NOTICE);\n"
},
{
"answer_id": 29037791,
"author": "phoenix",
"author_id": 3023353,
"author_profile": "https://Stackoverflow.com/users/3023353",
"pm_score": 1,
"selected": false,
"text": "function fatalHandler() {\n global $fatalHandlerError, $fatalHandlerTitle;\n\n $fatalHandlerError = error_get_last();\n\n if( $fatalHandlerError !== null ) {\n\n print($fatalHandlerTitle=\"{$fatalHandlerTitle} | \".join(\" | \", $fatalHandlerError).\n (preg_match(\"/memory/i\", $fatalHandlerError[\"message\"]) ? \" | Mem: limit \".ini_get('memory_limit').\" / peak \".round(memory_get_peak_usage(true)/(1024*1024)).\"M\" : \"\").\"\\n\".\n \"GET: \".var_export($_GET,1).\"\\n\".\n \"POST: \".var_export($_POST,1).\"\\n\".\n \"SESSION: \".var_export($_SESSION,1).\"\\n\".\n \"HEADERS: \".var_export(getallheaders(),1));\n }\n\n return $fatalHandlerTitle;\n}\n\nfunction fatalHandlerInit($title=\"phpError\") {\n global $fatalHandlerError, $fatalHandlerTitle;\n\n $fatalHandlerTitle = $title;\n $fatalHandlerError = error_get_last();\n\n set_error_handler( \"fatalHandler\" );\n}\n ini_set('memory_limit', '296M');\n\nfatalHandlerInit(\"testing\");\n\n$file[] = file(\"large file\"); // copy paste a bunch of times\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1615/"
] |
36,636 |
<p>I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?</p>
|
[
{
"answer_id": 36639,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 7,
"selected": false,
"text": "function makeCounter () {\n var count = 0;\n return function () {\n count += 1;\n return count;\n }\n}\n\nvar x = makeCounter();\nx(); returns 1\nx(); returns 2\n...etc...\n makeCounter x x function add (a) {\n return function (b) {\n return a + b;\n }\n}\n\nvar add3 = add(3);\n \nadd3(4); returns 7\n add a add3 add3 a"
},
{
"answer_id": 36641,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "def outer (a):\n b = \"variable in outer()\"\n def inner (c):\n print a, b, c\n return inner\n\n# Now the return value from outer() can be saved for later\nfunc = outer (\"test\")\nfunc (1) # prints \"test variable in outer() 1\n"
},
{
"answer_id": 36652,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "def n_times(a_thing)\n return lambda{|n| a_thing * n}\nend\n lambda(|n| a_thing * n} a_thing foo = n_times(4)\n foo.call(3)\n"
},
{
"answer_id": 36699,
"author": "Ben Childs",
"author_id": 2925,
"author_profile": "https://Stackoverflow.com/users/2925",
"pm_score": 6,
"selected": false,
"text": "count"
},
{
"answer_id": 36945,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 5,
"selected": false,
"text": "(define x 3)\n\n(define y 4)\n\n(+ x y) returns 7\n (define x 3)\n\n(define y 4)\n\n(let ((x 5))\n (+ x y)) returns 9\n\nx returns 3\n (define x 3)\n\n(define (plus-x y)\n (+ x y))\n\n(let ((x 5))\n (plus-x 4)) returns ?\n (define x 3)\n\n(define (plus-x y)\n (+ x y))\n\n(let ((x 5))\n (plus-x 4)) returns 7\n"
},
{
"answer_id": 4119185,
"author": "adamJLev",
"author_id": 26192,
"author_profile": "https://Stackoverflow.com/users/26192",
"pm_score": 3,
"selected": false,
"text": "Function.prototype.delay = function(ms /*[, arg...]*/) {\n var fn = this,\n args = Array.prototype.slice.call(arguments, 1);\n\n return window.setTimeout(function() {\n return fn.apply(fn, args);\n }, ms);\n};\n var startPlayback = function(track) {\n Player.play(track); \n};\nstartPlayback(someTrack);\n delay startPlayback.delay(5000, someTrack);\n// Keep going, do other things\n delay 5000 setTimeout"
},
{
"answer_id": 5973885,
"author": "Nigel Atkinson",
"author_id": 707446,
"author_profile": "https://Stackoverflow.com/users/707446",
"pm_score": 0,
"selected": false,
"text": "local old_dofile = dofile\n\nfunction dofile( filename )\n if filename == nil then\n error( 'Can not use default of stdin.' )\n end\n\n old_dofile( filename )\nend\n"
},
{
"answer_id": 7464475,
"author": "superluminary",
"author_id": 687677,
"author_profile": "https://Stackoverflow.com/users/687677",
"pm_score": 11,
"selected": true,
"text": "function() {\n var a = 1;\n console.log(a); // works\n} \nconsole.log(a); // fails\n var a = 1;\nfunction() {\n console.log(a); // works\n} \nconsole.log(a); // works\n outer = function() {\n var a = 1;\n var inner = function() {\n console.log(a);\n }\n return inner; // this returns a function\n}\n\nvar fnc = outer(); // execute outer to get inner \nfnc();\n a a fnc outer inner a a fnc fnc() a a outer a a a outer inner outer fnc inner a fnc a"
},
{
"answer_id": 35254177,
"author": "soundyogi",
"author_id": 3293027,
"author_profile": "https://Stackoverflow.com/users/3293027",
"pm_score": 4,
"selected": false,
"text": "var pure = function pure(x){\n return x \n // only own environment is used\n}\n\nvar foo = \"bar\"\n\nvar closure = function closure(){\n return foo \n // foo is a free variable from the outer environment\n}\n"
},
{
"answer_id": 36377697,
"author": "ericj",
"author_id": 1065175,
"author_profile": "https://Stackoverflow.com/users/1065175",
"pm_score": 0,
"selected": false,
"text": "var f=function(){\n var a=7;\n var g=function(){\n return a;\n }\n return g;\n}\n g g a g a f"
},
{
"answer_id": 36879264,
"author": "SasQ",
"author_id": 434562,
"author_profile": "https://Stackoverflow.com/users/434562",
"pm_score": 7,
"selected": false,
"text": "function closed(x) {\n return x + 3;\n}\n function open(x) {\n return x*y + 3;\n}\n y y y y y var y = 7;\n\nfunction open(x) {\n return x*y + 3;\n}\n var global = 2;\n\nfunction wrapper(y) {\n var w = \"unused\";\n\n return function(x) {\n return x*y + 3;\n }\n}\n y {\n global: 2,\n w: \"unused\",\n y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n y {\n y: [whatever has been passed to that wrapper function as its parameter `y`]\n}\n y"
},
{
"answer_id": 44915262,
"author": "totymedli",
"author_id": 1494454,
"author_profile": "https://Stackoverflow.com/users/1494454",
"pm_score": 3,
"selected": false,
"text": "function startAt(x) {\n return function (y) {\n return x + y;\n }\n}\n\nvar closure1 = startAt(1);\nvar closure2 = startAt(5);\n\nconsole.log(closure1(3)); // 4 (x == 1, y == 3)\nconsole.log(closure2(3)); // 8 (x == 5, y == 3) startAt closure1 closure2 y 3 startAt x 1 5 x startAt x startAt startAt startAt closure1 closure2 1 5 startAt closure1 closure2 3 y x x 1 5"
},
{
"answer_id": 45479869,
"author": "shohan",
"author_id": 849525,
"author_profile": "https://Stackoverflow.com/users/849525",
"pm_score": 0,
"selected": false,
"text": "Listing 2-18:\n function outerFunction(arg) {\n var variableInOuterFunction = arg;\n\n function bar() {\n console.log(variableInOuterFunction); // Access a variable from the outer scope\n }\n // Call the local function to demonstrate that it has access to arg\n bar(); \n }\n outerFunction('hello closure!'); // logs hello closure!\n"
},
{
"answer_id": 53794681,
"author": "arun",
"author_id": 2638170,
"author_profile": "https://Stackoverflow.com/users/2638170",
"pm_score": 0,
"selected": false,
"text": " for(var i=0; i< 5; i++){ \n setTimeout(function(){\n console.log(i);\n }, 1000); \n }\n 0,1,2,3,4 5,5,5,5,5 for(var i=0; i< 5; i++){\n (function(j){ //using IIFE \n setTimeout(function(){\n console.log(j);\n },1000);\n })(i); \n }\n setTimeout 5,5,5,5,5 (function(j){ //i is passed here \n setTimeout(function(){\n console.log(j);\n },1000);\n })(i); //look here it called immediate that is store i=0 for 1st loop, i=1 for 2nd loop, and so on and print 0,1,2,3,4\n for(let i=0; i< 5; i++){ \n setTimeout(function(){\n console.log(i);\n },1000); \n }\n\nOutput: 0,1,2,3,4\n setTimeout(function(){\n console.log(i);\n },1000); \n setTimeout(function(){\n console.log(i);\n },1000); \n setTimeout(function(){\n console.log(i);\n },1000); \n setTimeout(function(){\n console.log(i);\n },1000); \n setTimeout(function(){\n console.log(i);\n },1000); \n setTimeout 5,5,5,5,5"
},
{
"answer_id": 55753213,
"author": "rahul sharma",
"author_id": 11049404,
"author_profile": "https://Stackoverflow.com/users/11049404",
"pm_score": 3,
"selected": false,
"text": "var globalValue = 5;\n\nfunction functOuter() {\n var outerFunctionValue = 10;\n\n //Inner function has access to the outer function value\n //and the global variables\n function functInner() {\n var innerFunctionValue = 5;\n alert(globalValue + outerFunctionValue + innerFunctionValue);\n }\n functInner();\n}\nfunctOuter(); \n"
},
{
"answer_id": 55979154,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "function multiply (x, y) {\n return x * y;\n}\n\nconst double = multiply.bind(null, 2);\n\nconst eight = double(4);\n\neight == 8;\n function apple(x){\n function google(y,z) {\n console.log(x*y);\n }\n google(7,2);\n}\n\napple(3);\n\n// the answer here will be 21\n"
},
{
"answer_id": 56366052,
"author": "Rumel",
"author_id": 4360546,
"author_profile": "https://Stackoverflow.com/users/4360546",
"pm_score": 0,
"selected": false,
"text": "function init() {\n var name = “Mozilla”;\n}\n function init() {\n var name = “Mozilla”;\n function displayName(){\n alert(name);\n}\ndisplayName();\n}\n"
},
{
"answer_id": 58013619,
"author": "Claudio",
"author_id": 7056679,
"author_profile": "https://Stackoverflow.com/users/7056679",
"pm_score": 2,
"selected": false,
"text": "var a = 0;\n\na = a + 1; // => 1\na = a + 1; // => 2\na = a + 1; // => 3\n class Bread {\n constructor (weight) {\n this.weight = weight;\n }\n\n render () {\n return `My weight is ${this.weight}!`;\n }\n}\n var n = 0;\nvar count = function () {\n n = n + 1;\n return n;\n};\n\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n var countGenerator = function () {\n var n = 0;\n var count = function () {\n n = n + 1;\n return n;\n };\n\n return count;\n};\n\nvar count = countGenerator();\ncount(); // # 1\ncount(); // # 2\ncount(); // # 3\n"
},
{
"answer_id": 58125389,
"author": "GraceMeng",
"author_id": 9687097,
"author_profile": "https://Stackoverflow.com/users/9687097",
"pm_score": 0,
"selected": false,
"text": "def outer() {\n def x = 1\n return { -> println(x)} // inner\n}\ndef innerObj = outer()\ninnerObj() // prints 1\n"
},
{
"answer_id": 66317675,
"author": "Kim Mens",
"author_id": 13339955,
"author_profile": "https://Stackoverflow.com/users/13339955",
"pm_score": 0,
"selected": false,
"text": "; Function using a local variable\n(define (function)\n (define a 1)\n (display a) ; prints 1, when calling (function)\n )\n(function) ; prints 1\n(display a) ; fails: a undefined\n ; Function using a global variable\n(define b 2)\n(define (function)\n (display b) ; prints 2, when calling (function)\n )\n(function) ; prints 2\n(display 2) ; prints 2\n ; Function with closure\n(define (outer)\n (define c 3)\n (define (inner)\n (display c))\n inner ; outer function returns the inner function as result\n )\n(define function (outer))\n(function) ; prints 3\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
] |
36,646 |
<p>Does anyone use <a href="http://phing.info/trac/" rel="nofollow noreferrer">Phing</a> to deploy PHP applications, and if so how do you use it? We currently have a hand-written "setup" script that we run whenever we deploy a new instance of our project. We just check out from SVN and run it. It sets some basic configuration variables, installs or reloads the database, and generates a v-host for the site instance.</p>
<p>I have often thought that maybe we should be using <a href="http://phing.info/trac/" rel="nofollow noreferrer">Phing</a>. I haven't used ant much, so I don't have a real sense of what <a href="http://phing.info/trac/" rel="nofollow noreferrer">Phing</a> is supposed to do other than script the copying of files from one place to another much as our setup script does. What are some more advanced uses that you can give examples of to help me understand why we would or would not want to integrate <a href="http://phing.info/trac/" rel="nofollow noreferrer">Phing</a> into our process?</p>
|
[
{
"answer_id": 6323542,
"author": "cweiske",
"author_id": 282601,
"author_profile": "https://Stackoverflow.com/users/282601",
"pm_score": 2,
"selected": false,
"text": "exec exec"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
36,647 |
<p>Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?</p>
|
[
{
"answer_id": 36648,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 6,
"selected": true,
"text": "unittest doctest nose unittest unittest doctest"
},
{
"answer_id": 36654,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "unittest"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
36,656 |
<p>I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains <code>ASCII art</code> and whatnot that I would like to preserve. When I print out the string on the <code>HTML page</code>, even if it does have the same formatting and everything since it is in <code>HTML</code>, the spacing and line breaks are not preserved. What is the best way to print out the text in <code>HTML</code> exactly as it was in the original text file?<br>
I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P<br>
Basically, I would like suggestions on how to display <code>ASCII art in HTML</code>.</p>
|
[
{
"answer_id": 36657,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "nl2br() \\n \\r\\n <br>"
},
{
"answer_id": 36658,
"author": "Grant",
"author_id": 30,
"author_profile": "https://Stackoverflow.com/users/30",
"pm_score": 7,
"selected": true,
"text": "<pre>\ntext goes here and here \n and here and here Some out here\n ▄ ▄█▄ █▄ ▄\n ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀\n██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██\n█▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓\n█▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒\n ▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░\n\n</pre> \n"
},
{
"answer_id": 14956689,
"author": "Igor L.",
"author_id": 1315125,
"author_profile": "https://Stackoverflow.com/users/1315125",
"pm_score": 4,
"selected": false,
"text": "<pre> </pre> \\n \\n\\r str_replace(' ', ' ', $stringVariable); $result = str_replace(' ', ' ', $stringVariable);\n$result = nl2br($result);\n"
},
{
"answer_id": 29119413,
"author": "Divyanshu Jimmy",
"author_id": 2442565,
"author_profile": "https://Stackoverflow.com/users/2442565",
"pm_score": 3,
"selected": false,
"text": "pre {\n white-space: pre-line;\n text-align : left;\n }\n <pre >\n <?php echo htmlentities($yourText ) ; ?>\n</pre>\n"
},
{
"answer_id": 59850570,
"author": "OsowoIAM",
"author_id": 2335697,
"author_profile": "https://Stackoverflow.com/users/2335697",
"pm_score": -1,
"selected": false,
"text": "<?php \n\necho (\"hello world \\n\")\n\n?>\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
] |
36,701 |
<p>Is it completely against the Java way to create struct like objects?</p>
<pre><code>class SomeData1 {
public int x;
public int y;
}
</code></pre>
<p>I can see a class with accessors and mutators being more Java like.</p>
<pre><code>class SomeData2 {
int getX();
void setX(int x);
int getY();
void setY(int y);
private int x;
private int y;
}
</code></pre>
<p>The class from the first example is notationally convenient.</p>
<pre><code>// a function in a class
public int f(SomeData1 d) {
return (3 * d.x) / d.y;
}
</code></pre>
<p>This is not as convenient.</p>
<pre><code>// a function in a class
public int f(SomeData2 d) {
return (3 * d.getX()) / d.getY();
}
</code></pre>
|
[
{
"answer_id": 36734,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 7,
"selected": true,
"text": "public property String foo; \na->Foo = b->Foo;\n"
},
{
"answer_id": 36874,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 3,
"selected": false,
"text": "java.awt.Point"
},
{
"answer_id": 36891,
"author": "izb",
"author_id": 974,
"author_profile": "https://Stackoverflow.com/users/974",
"pm_score": 8,
"selected": false,
"text": "public class ScreenCoord2D{\n public int x;\n public int y;\n}\n public class BankAccount{\n public int balance;\n}\n"
},
{
"answer_id": 38698,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 6,
"selected": false,
"text": "class Data {\n public final int x;\n public final int y;\n public Data( int x, int y){\n this.x = x;\n this.y = y;\n }\n}\n public class DataTest {\n public DataTest() {\n Data data1 = new Data(1, 5);\n Data data2 = new Data(2, 4);\n System.out.println(f(data1));\n System.out.println(f(data2));\n }\n\n public int f(Data d) {\n return (3 * d.x) / d.y;\n }\n\n public static void main(String[] args) {\n DataTest dataTest = new DataTest();\n }\n}\n"
},
{
"answer_id": 14950725,
"author": "Avik Kumar Goswami",
"author_id": 2085746,
"author_profile": "https://Stackoverflow.com/users/2085746",
"pm_score": 1,
"selected": false,
"text": "import java.io.*;\n\nclass NameList {\n String name;\n int age;\n}\n\nclass StructNameAge {\n public static void main(String [] args) throws IOException {\n\n NameList nl[]=new NameList[5]; // Create new radix of the structure NameList into 'nl' object\n NameList temp=new NameList(); // Create a temporary object of the structure\n\n BufferedReader br=new BufferedReader(new InputStreamReader(System.in));\n\n /* Enter data into each radix of 'nl' object */\n\n for(int i=0; i<5; i++) {\n nl[i]=new NameList(); // Assign the structure into each radix\n\n System.out.print(\"Name: \");\n nl[i].name=br.readLine();\n\n System.out.print(\"Age: \");\n nl[i].age=Integer.parseInt(br.readLine());\n\n System.out.println();\n }\n\n /* Perform the sort (Selection Sort Method) */\n\n for(int i=0; i<4; i++) {\n for(int j=i+1; j<5; j++) {\n if(nl[i].age>nl[j].age) {\n temp=nl[i];\n nl[i]=nl[j];\n nl[j]=temp;\n }\n }\n }\n\n /* Print each radix stored in 'nl' object */\n\n for(int i=0; i<5; i++)\n System.out.println(nl[i].name+\" (\"+nl[i].age+\")\");\n }\n}\n"
},
{
"answer_id": 24680006,
"author": "Lyubomyr Shaydariv",
"author_id": 166589,
"author_profile": "https://Stackoverflow.com/users/166589",
"pm_score": 2,
"selected": false,
"text": "stream.mapToInt(SomeData1::x)\n stream.mapToInt(SomeData2::getX)\n"
},
{
"answer_id": 26032324,
"author": "sampathsris",
"author_id": 1461424,
"author_profile": "https://Stackoverflow.com/users/1461424",
"pm_score": 4,
"selected": false,
"text": "public public java.io.BufferedReader private boolean skipLF = false; // If the next character is a line feed, skip it\n skipLF skipLF BufferedReader public Point class Point {\n private double x;\n private double y;\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n\n public double getX() {\n return this.x;\n }\n\n public double getY() {\n return this.y;\n }\n\n public void setX(double x) {\n this.x = x;\n }\n\n public void setY(double y) {\n this.y = y;\n }\n}\n Point a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));\n class Point {\n public double x;\n public double y;\n\n public Point(double x, double y) {\n this.x = x;\n this.y = y;\n }\n}\n\nPoint a = new Point(5.0, 4.0);\nPoint b = new Point(4.0, 9.0);\ndouble distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));\n struct struct Point final public final double x;\npublic final double y;\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
] |
36,707 |
<p>Are there good reasons why it's a better practice to have only one return statement in a function? </p>
<p>Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?</p>
|
[
{
"answer_id": 36714,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 11,
"selected": true,
"text": "public void DoStuff(Foo foo)\n{\n if (foo != null)\n {\n ...\n }\n}\n public void DoStuff(Foo foo)\n{\n if (foo == null) return;\n\n ...\n}\n"
},
{
"answer_id": 36729,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 8,
"selected": false,
"text": "string fooBar(string s, int? i) {\n string ret = \"\";\n if(!string.IsNullOrEmpty(s) && i != null) {\n var res = someFunction(s, i);\n\n bool passed = true;\n foreach(var r in res) {\n if(!r.Passed) {\n passed = false;\n break;\n }\n }\n\n if(passed) {\n // Rest of code...\n }\n }\n\n return ret;\n}\n string fooBar(string s, int? i) {\n var ret = \"\";\n if(string.IsNullOrEmpty(s) || i == null) return null;\n\n var res = someFunction(s, i);\n\n foreach(var r in res) {\n if(!r.Passed) return null;\n }\n\n // Rest of code...\n\n return ret;\n}\n"
},
{
"answer_id": 36732,
"author": "blank",
"author_id": 1348,
"author_profile": "https://Stackoverflow.com/users/1348",
"pm_score": 6,
"selected": false,
"text": "if then else"
},
{
"answer_id": 36839,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 8,
"selected": false,
"text": "function()\n{\n HRESULT error = S_OK;\n\n if(SUCCEEDED(Operation1()))\n {\n if(SUCCEEDED(Operation2()))\n {\n if(SUCCEEDED(Operation3()))\n {\n if(SUCCEEDED(Operation4()))\n {\n }\n else\n {\n error = OPERATION4FAILED;\n }\n }\n else\n {\n error = OPERATION3FAILED;\n }\n }\n else\n {\n error = OPERATION2FAILED;\n }\n }\n else\n {\n error = OPERATION1FAILED;\n }\n\n return error;\n}\n"
},
{
"answer_id": 36870,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 3,
"selected": false,
"text": "int f(int y) {\n int value = -1;\n void *data = NULL;\n\n if (y < 0)\n goto clean;\n\n if ((data = malloc(123)) == NULL)\n goto clean;\n\n /* More code */\n\n value = 1;\nclean:\n free(data);\n return value;\n}\n int g(int y) {\n value = 0;\n\n if ((value = g0(y, value)) == -1)\n return -1;\n\n if ((value = g1(y, value)) == -1)\n return -1;\n\n return g2(y, value);\n}\n"
},
{
"answer_id": 48630,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 6,
"selected": false,
"text": "return a > 0 ?\n positively(a):\n negatively(a);\n if (a > 0)\n return positively(a);\nelse\n return negatively(a);\n"
},
{
"answer_id": 55957,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 3,
"selected": false,
"text": "resulttype res;\nif if if...\nreturn res;\n"
},
{
"answer_id": 56099,
"author": "Marcin Gil",
"author_id": 5731,
"author_profile": "https://Stackoverflow.com/users/5731",
"pm_score": 1,
"selected": false,
"text": "if (a is false) {\n handle this situation (eg. report, log, message, etc.)\n return some-err-code\n}\nif (b is false) {\n handle this situation\n return other-err-code\n}\nif (c is false) {\n handle this situation\n return yet-another-err-code\n}\n\nperform any action assured that a, b and c are ok.\n"
},
{
"answer_id": 64155,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "sub Int_to_String( Int i ){\n given( i ){\n when 0 { return \"zero\" }\n when 1 { return \"one\" }\n when 2 { return \"two\" }\n when 3 { return \"three\" }\n when 4 { return \"four\" }\n ...\n default { return undef }\n }\n}\n @Int_to_String = qw{\n zero\n one\n two\n three\n four\n ...\n}\nsub Int_to_String( Int i ){\n return undef if i < 0;\n return undef unless i < @Int_to_String.length;\n return @Int_to_String[i]\n}\n"
},
{
"answer_id": 85911,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 4,
"selected": false,
"text": "public void DoStuff(Foo foo)\n{\n if (foo == null) return;\n}\n void foo (int i, int j) {\n A a;\n if (i > 0) {\n B b;\n return ; // Call dtor for 'b' followed by 'a'\n }\n if (i == j) {\n C c;\n B b;\n return ; // Call dtor for 'b', 'c' and then 'a'\n }\n return 'a' // Call dtor for 'a'\n}\n A foo () {\n A a1;\n // do something\n return a1;\n}\n\nvoid bar () {\n A a2 ( foo() );\n}\n"
},
{
"answer_id": 89641,
"author": "Paulus",
"author_id": 14209,
"author_profile": "https://Stackoverflow.com/users/14209",
"pm_score": -1,
"selected": false,
"text": "function foo (input, output, exit_status)\n\n exit_status == UNDEFINED\n if (check_the_need_to_execute == false) then\n exit_status = NO_NEED_TO_EXECUTE // reason #1 \n exit\n\n useful_work\n\n if (error_is_found == true) then\n exit_status = ERROR // reason #2\n exit\n if (need_to_go_further == false) then\n exit_status = EARLY_COMPLETION // reason #3\n exit\n\n more_work\n\n if (error_is_found == true) then\n exit_status = ERROR\n else\n exit_status = NORMAL_COMPLETION // reason #4\n\nend function\n"
},
{
"answer_id": 124300,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 0,
"selected": false,
"text": "do while(false) function()\n {\n HRESULT error = S_OK;\n\n do\n {\n if(!SUCCEEDED(Operation1()))\n {\n error = OPERATION1FAILED;\n break;\n }\n\n if(!SUCCEEDED(Operation2()))\n {\n error = OPERATION2FAILED;\n break;\n }\n\n if(!SUCCEEDED(Operation3()))\n {\n error = OPERATION3FAILED;\n break;\n }\n if(!SUCCEEDED(Operation4()))\n {\n error = OPERATION4FAILED;\n break;\n }\n } while (false);\n\n return error;\n }\n if #define BREAKIFFAILED(x,y) if (!SUCCEEDED((x))) { error = (Y); break; }\n\n do\n {\n BREAKIFFAILED(Operation1(), OPERATION1FAILED)\n BREAKIFFAILED(Operation2(), OPERATION2FAILED)\n BREAKIFFAILED(Operation3(), OPERATION3FAILED)\n BREAKIFFAILED(Operation4(), OPERATION4FAILED)\n } while (false);\n"
},
{
"answer_id": 790043,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "function()\n{\n HRESULT error = S_OK;\n\n if(SUCCEEDED(Operation1()))\n {\n if(SUCCEEDED(Operation2()))\n {\n if(SUCCEEDED(Operation3()))\n {\n if(SUCCEEDED(Operation4()))\n {\n }\n else\n {\n error = OPERATION4FAILED;\n }\n }\n else\n {\n error = OPERATION3FAILED;\n }\n }\n else\n {\n error = OPERATION2FAILED;\n }\n }\n else\n {\n error = OPERATION1FAILED;\n }\n\n return error;\n}\n function() {\n HRESULT error = OPERATION1FAILED;//assume failure\n if(SUCCEEDED(Operation1())) {\n\n error = OPERATION2FAILED;//assume failure\n if(SUCCEEDED(Operation3())) {\n\n error = OPERATION3FAILED;//assume failure\n if(SUCCEEDED(Operation3())) {\n\n error = OPERATION4FAILED; //assume failure\n if(SUCCEEDED(Operation4())) {\n\n error = S_OK;\n }\n }\n }\n }\n return error;\n}\n function() {\n HRESULT error = OPERATION1FAILED;//assume failure\n if(SUCCEEDED(Operation1())) {\n\n //allocate resource for op2;\n char* const p2 = new char[1024];\n error = OPERATION2FAILED;//assume failure\n if(SUCCEEDED(Operation2(p2))) {\n\n //allocate resource for op3;\n char* const p3 = new char[1024];\n error = OPERATION3FAILED;//assume failure\n if(SUCCEEDED(Operation3(p3))) {\n\n error = OPERATION4FAILED; //assume failure\n if(SUCCEEDED(Operation4(p2,p3))) {\n\n error = S_OK;\n }\n }\n //free resource for op3;\n delete [] p3;\n }\n //free resource for op2;\n delete [] p2;\n }\n return error;\n}\n }else{"
},
{
"answer_id": 792392,
"author": "Alphaneo",
"author_id": 70702,
"author_profile": "https://Stackoverflow.com/users/70702",
"pm_score": 3,
"selected": false,
"text": "void ProcessMyFile (char *szFileName)\n{\n FILE *fp = NULL;\n char *pbyBuffer = NULL:\n\n do {\n\n fp = fopen (szFileName, \"r\");\n\n if (NULL == fp) {\n\n break;\n }\n\n pbyBuffer = malloc (__SOME__SIZE___);\n\n if (NULL == pbyBuffer) {\n\n break;\n }\n\n /*** Do some processing with file ***/\n\n } while (0);\n\n if (pbyBuffer) {\n\n free (pbyBuffer);\n }\n\n if (fp) {\n\n fclose (fp);\n }\n}\n"
},
{
"answer_id": 1276951,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": 4,
"selected": false,
"text": "return function isCorrect($param1, $param2, $param3) {\n $toret = false;\n if ($param1 != $param2) {\n if ($param1 == ($param3 * 2)) {\n if ($param2 == ($param3 / 3)) {\n $toret = true;\n } else {\n $error = 'Error 3';\n }\n } else {\n $error = 'Error 2';\n }\n } else {\n $error = 'Error 1';\n }\n return $toret;\n}\n function isCorrect($param1, $param2, $param3) {\n if ($param1 == $param2) { $error = 'Error 1'; return false; }\n if ($param1 != ($param3 * 2)) { $error = 'Error 2'; return false; }\n if ($param2 != ($param3 / 3)) { $error = 'Error 3'; return false; }\n return true;\n}\n function isEqual($param1, $param2) {\n return $param1 == $param2;\n}\n\nfunction isDouble($param1, $param2) {\n return $param1 == ($param2 * 2);\n}\n\nfunction isThird($param1, $param2) {\n return $param1 == ($param2 / 3);\n}\n\nfunction isCorrect($param1, $param2, $param3) {\n return !isEqual($param1, $param2)\n && isDouble($param1, $param3)\n && isThird($param2, $param3);\n}\n"
},
{
"answer_id": 2204081,
"author": "Dinah",
"author_id": 356,
"author_profile": "https://Stackoverflow.com/users/356",
"pm_score": 2,
"selected": false,
"text": "GOTO"
},
{
"answer_id": 2236273,
"author": "Serhiy",
"author_id": 246719,
"author_profile": "https://Stackoverflow.com/users/246719",
"pm_score": 0,
"selected": false,
"text": "var retVal = new RetVal();\n\nif(!someCondition)\n return ProcessVal(retVal);\n\nif(!anotherCondition)\n return retVal;\n"
},
{
"answer_id": 2863438,
"author": "Zorf",
"author_id": 2281094,
"author_profile": "https://Stackoverflow.com/users/2281094",
"pm_score": 0,
"selected": false,
"text": "function name(arg) {\n if (arg.failure?)\n return;\n\n //code for non failure\n}\n function name(arg) {\n if (arg.failure?)\n voidConstant\n else {\n //code for non failure\n\n\n}\n"
},
{
"answer_id": 3128187,
"author": "Anthony",
"author_id": 5599,
"author_profile": "https://Stackoverflow.com/users/5599",
"pm_score": 3,
"selected": false,
"text": "try..finally using"
},
{
"answer_id": 3252702,
"author": "Blessed Geek",
"author_id": 140803,
"author_profile": "https://Stackoverflow.com/users/140803",
"pm_score": 3,
"selected": false,
"text": "public void hello()\n{\n if (....)\n {\n ....\n }\n}\n"
},
{
"answer_id": 4317061,
"author": "BJS",
"author_id": 525534,
"author_profile": "https://Stackoverflow.com/users/525534",
"pm_score": 1,
"selected": false,
"text": "public string GetResult()\n{\n string rv = null;\n bool okay = false;\n\n okay = PerformTest(1);\n\n if (okay)\n {\n okay = PerformTest(2);\n }\n\n if (okay)\n {\n okay = PerformTest(3);\n }\n\n if (okay)\n {\n okay = PerformTest(4);\n };\n\n if (okay)\n {\n okay = PerformTest(5);\n }\n\n if (okay)\n {\n rv = \"All Tests Passed\";\n }\n\n return rv;\n}\n"
},
{
"answer_id": 5034398,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 3,
"selected": false,
"text": "void string fooBar(string s, int? i) {\n\n if(string.IsNullOrEmpty(s) || i == null) return null;\n\n var res = someFunction(s, i);\n\n foreach(var r in res) {\n if(!r.Passed) return null;\n }\n\n // Rest of code...\n\n return ret;\n}\n if (string.IsNullOrEmpty(s) || i == null) return null;\nif (someFunction(s, i).Any(r => !r.Passed)) return null;\n void string fooBar(string s, int? i) {\n\n if (string.IsNullOrEmpty(s) || i == null) return null;\n if (someFunction(s, i).Any(r => !r.Passed)) return null;\n\n // Rest of code...\n\n return ret;\n}\n"
},
{
"answer_id": 21793601,
"author": "TaylorMac",
"author_id": 720785,
"author_profile": "https://Stackoverflow.com/users/720785",
"pm_score": 0,
"selected": false,
"text": "function doStuff(foo) {\n if (foo != null) return;\n}\n function doStuff(foo) {\n if (foo !== null) {\n ...\n }\n}\n doStuff if(foo != null) doStuff(foo);\n"
},
{
"answer_id": 25201917,
"author": "Tom Tanner",
"author_id": 1182921,
"author_profile": "https://Stackoverflow.com/users/1182921",
"pm_score": 0,
"selected": false,
"text": " CALL SOMESUB(ARG1, 101, 102, 103)\nC Some code\n 101 CONTINUE\nC Some more code\n 102 CONTINUE\nC Yet more code\n 103 CONTINUE\nC You get the general idea\n"
},
{
"answer_id": 29472829,
"author": "DarioBB",
"author_id": 4195191,
"author_profile": "https://Stackoverflow.com/users/4195191",
"pm_score": 0,
"selected": false,
"text": "$content = \"\";\n$return = false;\n\nif($content != \"\")\n{\n $return = true;\n}\nelse \n{\n $return = false;\n}\n\nreturn $return;\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/381/"
] |
36,715 |
<p>When using host headers to host multiple websites on the same IP address in IIS, is there any way of accessing that website from a browser running on the local machine?</p>
<p>This is normally required when a given web component only allows configuration from the local machine. It's also useful when things like ASP.Net's built in error handling isn't working and you can only view the error in the browser but don't want to allow remote users to see it. </p>
<p>This has baffled me for a while and everytime I come across it I end up giving up in frustration and reconfigure stuff so I can accomplish such tasks remotely.</p>
<p><strong>Added:</strong> @Ishmaeel - modifying hosts doesn't seem to help - you either get a 400 error (if all websites have host headers) or whichever site is configured without a host header.</p>
|
[
{
"answer_id": 35499622,
"author": "Anders Bornholm",
"author_id": 1425531,
"author_profile": "https://Stackoverflow.com/users/1425531",
"pm_score": 0,
"selected": false,
"text": "$ telnet localhost 80\n GET / HTTP/1.1\nHost: www.example.com\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1521/"
] |
36,733 |
<p>I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page. </p>
<p>Since they are coming from a variety of ways, I am just curious as to the <strong>best</strong> way to <strong>redirect</strong> the user back to the calling page. I have some ideas, but would like to get other developers input.</p>
<p>Would you store the <strong>calling</strong> url in session? as a cookie? I like the concept of using an object <strong>handle</strong> the redirection.</p>
|
[
{
"answer_id": 36735,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "public partial class _Default : System.Web.UI.Page \n{\n\n void Redirect(string url, string messsage)\n {\n RedirectionParams paras = new RedirectionParams(url, messsage);\n RedirectionHandler(paras); // pass to some global method (or this could BE the global method)\n }\n protected void Button1_Click(object sender, EventArgs e)\n {\n Redirect(\"mypage.aspx\", \"you have been redirected\");\n }\n}\n\npublic class RedirectionParams\n{\n private string _url;\n\n public string URL\n {\n get { return _url; }\n set { _url = value; }\n }\n\n private string _message;\n\n public string Message\n {\n get { return _message; }\n set { _message = value; }\n }\n\n public RedirectionParams(string url, string message)\n {\n this.URL = url;\n this.Message = message;\n }\n}\n"
},
{
"answer_id": 36777,
"author": "Tom",
"author_id": 3139,
"author_profile": "https://Stackoverflow.com/users/3139",
"pm_score": 4,
"selected": true,
"text": "public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n if (Request.UrlReferrer == null)\n {\n //Handle the case where the page is requested directly\n throw new Exception(\"This page has been called without a referring page\");\n }\n\n if (!IsPostBack)\n { \n ReturnUrl = Request.UrlReferrer.PathAndQuery;\n }\n }\n\n public string ReturnUrl\n {\n get { return ViewState[\"returnUrl\"].ToString(); }\n set { ViewState[\"returnUrl\"] = value; }\n }\n\n protected void btn_Click(object sender, EventArgs e)\n {\n //Do what you need to do to save the page\n //...\n\n //Go back to calling page\n Response.Redirect(ReturnUrl, true);\n }\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
36,742 |
<p>My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case. </p>
<p>A sample complete sentence looks like:</p>
<pre><code>$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76
</code></pre>
<p>The line should start with a <code>$</code> sign, and end with an <code>*</code> and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file.</p>
<p>The following Python code might work: </p>
<pre><code>import re
from path import path
nmea = re.compile("^\$.+\*[0-9A-F]{2}$")
for log in path("gpslogs").files("*.log"):
for line in log.lines():
if not nmea.match(line) and not "ADVER" in line:
print "%s\n\t%s\n" % (log, line)
</code></pre>
<p>Is there a way to do that with <code>grep</code> or <code>awk</code> or something simple? I haven't really figured out how to get <code>grep</code> to do what I want.</p>
<p><strong>Update</strong>: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing <code>$</code> before it would work:</p>
<pre><code>grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB
</code></pre>
<p>Two further questions arise, how can I make it ignore blank lines? And can I combine the last two <code>grep</code>s?</p>
|
[
{
"answer_id": 36779,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 2,
"selected": false,
"text": "grep -Ev \"^\\$.*\\*[0-9A-Fa-f]{2}$\" a.txt | grep -v ADVER\n grep -v ADVER"
},
{
"answer_id": 36842,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": 1,
"selected": false,
"text": "grep -Ev \"^\\$.*\\*[0-9A-Fa-f]{2}$\" a.txt |grep -v ADVER\n"
},
{
"answer_id": 39021,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 1,
"selected": false,
"text": "$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76xxx\n grep -Ev \"ADVER|ADPMB\"\n"
},
{
"answer_id": 39516,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 0,
"selected": false,
"text": "grep $ grep"
},
{
"answer_id": 43336,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 0,
"selected": false,
"text": "grep (GNU grep) 2.4.2"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
] |
36,748 |
<p>What's the best way to asynchronously load an BitmapImage in C# using WPF? </p>
|
[
{
"answer_id": 40774,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 0,
"selected": false,
"text": "public class ResizeFolderBackgroundWorker : BackgroundWorker\n{\n\n public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)\n {\n this.sourceFolder = sourceFolder;\n this.destinationFolder = destinationFolder;\n this.resizeTo = resizeTo;\n\n this.WorkerReportsProgress = true;\n this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);\n }\n\n void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)\n {\n DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);\n FileInfo[] files = dirInfo.GetFiles(\"*.jpg\");\n\n\n foreach (FileInfo fileInfo in files)\n {\n /* iterate over each file and resizing it */\n }\n }\n}\n //handle a button click to start lengthy operation\n private void resizeImageButtonClick(object sender, EventArgs e)\n {\n string sourceFolder = getSourceFolderSomehow();\n resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);\n resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);\n resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);\n\n progressBar1.Value = 0;\n progressBar1.Visible = true;\n\n resizer.RunWorkerAsync();\n }\n\n void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n progressBar1.Visible = false;\n //signal to user that operation has completed\n }\n\n void genericProgressChanged(object sender, ProgressChangedEventArgs e)\n {\n progressBar1.Value = e.ProgressPercentage;\n //I just update a progress bar\n }\n"
},
{
"answer_id": 783633,
"author": "kevindaub",
"author_id": 27669,
"author_profile": "https://Stackoverflow.com/users/27669",
"pm_score": 2,
"selected": false,
"text": "ItemsSource=\"{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}\"\n"
},
{
"answer_id": 2672929,
"author": "Brian",
"author_id": 321017,
"author_profile": "https://Stackoverflow.com/users/321017",
"pm_score": 3,
"selected": false,
"text": "//Create the image control\nImage img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};\n\n//Create a seperate thread to load the image\nThreadStart thread = delegate\n {\n //Load the image in a seperate thread\n BitmapImage bmpImage = new BitmapImage();\n MemoryStream ms = new MemoryStream();\n\n //A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@\"C:\\ImageFileName.jpg\", FileMode.Open);\n MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);\n\n bmpImage.BeginInit();\n bmpImage.StreamSource = ms;\n bmpImage.EndInit();\n\n //**THIS LINE locks the BitmapImage so that it can be transported across threads!! \n bmpImage.Freeze();\n\n //Call the UI thread using the Dispatcher to update the Image control\n Dispatcher.BeginInvoke(new ThreadStart(delegate\n {\n img.Source = bmpImage;\n img.Unloaded += delegate \n {\n ms.Close();\n ms.Dispose();\n };\n\n grdImageContainer.Children.Add(img);\n }));\n\n };\n\n//Start previously mentioned thread...\nnew Thread(thread).Start();\n"
},
{
"answer_id": 19470572,
"author": "Cornel Marian",
"author_id": 736113,
"author_profile": "https://Stackoverflow.com/users/736113",
"pm_score": 2,
"selected": false,
"text": " BitmapCacheOption.OnLoad\n\nvar bmp = await System.Threading.Tasks.Task.Run(() => \n{ \nBitmapImage img = new BitmapImage(); \nimg.BeginInit(); \nimg.CacheOption = BitmapCacheOption.OnLoad; \nimg.UriSource = new Uri(path); \nimg.EndInit(); \nImageBrush brush = new ImageBrush(img); \n\n}\n"
},
{
"answer_id": 37737445,
"author": "David",
"author_id": 1995676,
"author_profile": "https://Stackoverflow.com/users/1995676",
"pm_score": 2,
"selected": false,
"text": "private async Task<BitmapImage> LoadImage(string url)\n{\n HttpClient client = new HttpClient();\n\n try\n {\n BitmapImage img = new BitmapImage();\n img.CacheOption = BitmapCacheOption.OnLoad;\n img.BeginInit();\n img.StreamSource = await client.GetStreamAsync(url);\n img.EndInit();\n return img;\n }\n catch (HttpRequestException)\n {\n // the download failed, log error\n return null;\n }\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3837/"
] |
36,760 |
<p>I have three tables: page, attachment, page-attachment</p>
<p>I have data like this:</p>
<pre><code>page
ID NAME
1 first page
2 second page
3 third page
4 fourth page
attachment
ID NAME
1 foo.word
2 test.xsl
3 mm.ppt
page-attachment
ID PAGE-ID ATTACHMENT-ID
1 2 1
2 2 2
3 3 3
</code></pre>
<p>I would like to get the number of attachments per page <strong>also when that number is 0</strong>. I have tried with: </p>
<pre><code>select page.name, count(page-attachment.id) as attachmentsnumber
from page
inner join page-attachment on page.id=page-id
group by page.id
</code></pre>
<p>I am getting this output: </p>
<pre><code>NAME ATTACHMENTSNUMBER
second page 2
third page 1
</code></pre>
<p>I would like to get this output:</p>
<pre><code>NAME ATTACHMENTSNUMBER
first page 0
second page 2
third page 1
fourth page 0
</code></pre>
<p>How do I get the 0 part?</p>
|
[
{
"answer_id": 36762,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 6,
"selected": true,
"text": "select page.name, count(page-attachment.id) as attachmentsnumber \nfrom page \n left outer join page-attachment on page.id=page-id \ngroup by page.name\n"
},
{
"answer_id": 86385,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "SELECT\n p.name,\n (\n SELECT COUNT(*) FROM [page-attachment] pa\n WHERE pa.[PAGE-ID] = p.id\n ) as attachmentsnumber\nFROM page p\n"
},
{
"answer_id": 28178720,
"author": "David M Goodwin",
"author_id": 4500153,
"author_profile": "https://Stackoverflow.com/users/4500153",
"pm_score": 2,
"selected": false,
"text": "(\nselect page.name, count(page-attachment.id) as attachmentsnumber \nfrom page \ninner join page-attachment on page.id=page-id \ngroup by page.id\n)\nUNION\n(\nselect page.name, 0 as attachmentsnumber \nfrom page\nwhere page.id not in (\n select page-id from page-attachment)\n) \n"
},
{
"answer_id": 28178806,
"author": "Jpasker",
"author_id": 4438190,
"author_profile": "https://Stackoverflow.com/users/4438190",
"pm_score": 0,
"selected": false,
"text": "SELECT p.name,(\n SELECT COUNT(*) FROM [page-attachment] pa WHERE pa.[PAGE-ID] = p.id) as attachmentsnumber\nFROM page p\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
36,806 |
<p>I have been sold on mod_wsgi and apache rather than mod_python.
I have all the parts installed (django, apache, mod_wsgi) but have run into a problem deploying.</p>
<p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p>
<p>My application is called tred.</p>
<p>Here are the relevant files:
httpd-vhosts (included in httpd-conf)</p>
<pre>
NameVirtualHost tred:80
ServerName tred
Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media
Order allow,deny
Allow from all
Alias /media /Users/dmg/Sites/tred/media
Order allow,deny
Allow from all
Alias / /Users/dmg/Sites/tred/
Order allow,deny
Allow from all
WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi
WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10
WSGIProcessGroup tred
</pre>
<p>mod_wsgi-handle.wsgi</p>
<pre>
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</pre>
<p>When I go to <a href="http://tred" rel="noreferrer">http://tred</a> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?</p>
|
[
{
"answer_id": 37009,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": true,
"text": "Alias /"
},
{
"answer_id": 37218,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "Alias / WSGIScriptAlias mod_alias Redirect RedirectMatch"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] |
36,812 |
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p>
<p>Here is my question. How can I add additional data (products) to my Product model?</p>
<p>I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django</p>
<p>How can I do this all without using this existing django admin interface.</p>
|
[
{
"answer_id": 36935,
"author": "Carl Meyer",
"author_id": 3207,
"author_profile": "https://Stackoverflow.com/users/3207",
"pm_score": 4,
"selected": true,
"text": "from django.conf.urls.defaults import *\nfrom django.views.generic.create_update import create_object\n\nfrom my_products_app.models import Product\n\nurlpatterns = patterns('',\n url(r'^admin/products/add/$', create_object, {'model': Product}))\n <form action=\".\" method=\"POST\">\n {{ form }}\n <input type=\"submit\" name=\"submit\" value=\"add\">\n</form>\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2592/"
] |
36,813 |
<p>When and how should table stats gathering be performed for Oracle, version 9 and up? How would you go about gathering stats for a large database, where stats gathering would collide with "business hours".</p>
|
[
{
"answer_id": 117066,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 3,
"selected": false,
"text": "dbms_stats.export_table_stats\n dbms_stats.import_table_stats\n schema database"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] |
36,831 |
<p>I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "<a href="http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx" rel="nofollow noreferrer">GetBestInterface</a>" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.</p>
<p>I've found some examples via Google, like <a href="http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/" rel="nofollow noreferrer">this one</a> or <a href="http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651" rel="nofollow noreferrer">this one</a>, but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...</p>
<p>There is also a way of doing this using IP Helper, using the <a href="http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx" rel="nofollow noreferrer">ParseNetworkString</a>, but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.</p>
<p>So, anyone knows of a standard way to do this in .NET?</p>
|
[
{
"answer_id": 36841,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 5,
"selected": true,
"text": "var ipAddress = IPAddress.Parse(\"some.ip.address\");\nvar ipBytes = ipAddress.GetAddressBytes();\nvar ip = (uint)ipBytes [3] << 24;\nip += (uint)ipBytes [2] << 16;\nip += (uint)ipBytes [1] <<8;\nip += (uint)ipBytes [0];\n"
},
{
"answer_id": 37231,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 4,
"selected": false,
"text": "var ipuint32 = BitConverter.ToUInt32(IPAddress.Parse(\"some.ip.address.ipv4\").GetAddressBytes(), 0);`\n"
},
{
"answer_id": 553315,
"author": "Christo",
"author_id": 66948,
"author_profile": "https://Stackoverflow.com/users/66948",
"pm_score": 4,
"selected": false,
"text": "var ipAddress = IPAddress.Parse(\"some.ip.address\");\nvar ipBytes = ipAddress.GetAddressBytes();\nvar ip = (uint)ipBytes [0] << 24;\nip += (uint)ipBytes [1] << 16;\nip += (uint)ipBytes [2] <<8;\nip += (uint)ipBytes [3];\n"
},
{
"answer_id": 3900026,
"author": "qasali",
"author_id": 517162,
"author_profile": "https://Stackoverflow.com/users/517162",
"pm_score": 1,
"selected": false,
"text": "System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(\"192.168.1.1\");\n\nbyte[] bytes = ipAddress.GetAddressBytes();\nfor (int i = 0; i < bytes.Length ; i++)\n Console.WriteLine(bytes[i]);\n"
},
{
"answer_id": 50188623,
"author": "Pavel Samoylenko",
"author_id": 2399045,
"author_profile": "https://Stackoverflow.com/users/2399045",
"pm_score": 1,
"selected": false,
"text": "public static uint IpStringToUint(string ipString)\n{\n var ipAddress = IPAddress.Parse(ipString);\n var ipBytes = ipAddress.GetAddressBytes();\n var ip = (uint)ipBytes [0] << 24;\n ip += (uint)ipBytes [1] << 16;\n ip += (uint)ipBytes [2] <<8;\n ip += (uint)ipBytes [3];\n return ip;\n}\n\npublic static string IpUintToString(uint ipUint)\n{\n var ipBytes = BitConverter.GetBytes(ipUint);\n var ipBytesRevert = new byte[4];\n ipBytesRevert[0] = ipBytes[3];\n ipBytesRevert[1] = ipBytes[2];\n ipBytesRevert[2] = ipBytes[1];\n ipBytesRevert[3] = ipBytes[0];\n return new IPAddress(ipBytesRevert).ToString();\n}\n public static uint IpStringToUint(string ipString)\n{\n return BitConverter.ToUInt32(IPAddress.Parse(ipString).GetAddressBytes(), 0);\n}\n\npublic static string IpUintToString(uint ipUint)\n{\n return new IPAddress(BitConverter.GetBytes(ipUint)).ToString();\n}\n"
},
{
"answer_id": 57980588,
"author": "Nick",
"author_id": 984516,
"author_profile": "https://Stackoverflow.com/users/984516",
"pm_score": 2,
"selected": false,
"text": "var ipBytes = ip.GetAddressBytes();\nulong ip = 0;\nif (BitConverter.IsLittleEndian)\n{\n ip = (uint) ipBytes[0] << 24;\n ip += (uint) ipBytes[1] << 16;\n ip += (uint) ipBytes[2] << 8;\n ip += (uint) ipBytes[3];\n}\nelse\n{\n ip = (uint)ipBytes [3] << 24;\n ip += (uint)ipBytes [2] << 16;\n ip += (uint)ipBytes [1] <<8;\n ip += (uint)ipBytes [0];\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1596/"
] |
36,832 |
<p>In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.</p>
<p>I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:</p>
<p>As long as the derived constructor has not been executed the object is <strong>not</strong> yet a <em>derived</em> instance.</p>
<p>So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:</p>
<pre><code>class base {
public:
base()
{
std::cout << "foo is " << foo() << std::endl;
}
virtual int foo() { return 42; }
};
class derived : public base {
int* ptr_;
public:
derived(int i) : ptr_(new int(i*i)) { }
// The following cannot be called before derived::derived due to how C++ behaves,
// if it was possible... Kaboom!
virtual int foo() { return *ptr_; }
};
</code></pre>
<p>It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for <em>the principle of least surprise</em>? </p>
<p>Which do you think is the correct choice?</p>
|
[
{
"answer_id": 75026,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 0,
"selected": false,
"text": "type\n TComponent = class\n public\n constructor Create(AOwner: TComponent); virtual; // virtual constructor\n end;\n\n TMyEdit = class(TComponent)\n public\n constructor Create(AOwner: TComponent); override; // override virtual constructor\n end;\n\n TMyButton = class(TComponent)\n public\n constructor Create(AOwner: TComponent); override; // override virtual constructor\n end;\n\n TComponentClass = class of TComponent;\n\nfunction CreateAComponent(ComponentClass: TComponentClass; AOwner: TComponent): TComponent;\nbegin\n Result := ComponentClass.Create(AOwner);\nend;\n\nvar\n MyEdit: TMyEdit;\n MyButton: TMyButton;\nbegin\n MyEdit := CreateAComponent(TMyEdit, Form) as TMyEdit;\n MyButton := CreateAComponent(TMyButton, Form) as TMyButton;\nend;\n"
},
{
"answer_id": 77445,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "BaseClass() {\n for (int i=0; i<virtualSize(); i++)\n initialize_stuff_for_index(i);\n}"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
36,861 |
<p>I've run into a strange syntax in <a href="http://boo.codehaus.org/Closures" rel="nofollow noreferrer">Boo Language Guide</a> :</p>
<pre><code>setter = { value | a = value }
</code></pre>
<p>What does the | operator mean?</p>
|
[
{
"answer_id": 36869,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "setter = { value | a = value }\n setter = def(value):\n a = value\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2313/"
] |
36,862 |
<p>With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing.</p>
<p>Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command..</p>
<p>Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup.</p>
<p>The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos)</p>
<p>I <em>could</em> use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup)</p>
<p>Currently I have a folder of git-repos (for example, ~/code_projects/proj1/.git/ ~/code_projects/proj2/.git/), and after doing changes to proj1 I do <code>git push github</code>, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do <code>git push backupdrive1</code>, <code>git push mymemorystick</code> etc</p>
<p>So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up?</p>
|
[
{
"answer_id": 36905,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": 2,
"selected": false,
"text": "git-submodule repo"
},
{
"answer_id": 37006,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 7,
"selected": true,
"text": "/repos/a.git\n/repos/b.git\n/repos/c.git\n svn checkout --> git clone\nsvn update --> git pull\nsvn commit --> git push\n $ cd ~/dev\n$ git clone /repos/foo.git # or the one from github, ...\n$ cd foo\n$ git remote add github ...\n$ git remote add memorystick ...\n $ for remote in origin github memorystick; do git push $remote; done\n ~/dev/foo $ cd ~/dev\n$ git clone --bare foo /repos/foo.git\n$ mv foo foo.old\n$ git clone /repos/foo.git\n svn import"
},
{
"answer_id": 779812,
"author": "imz -- Ivan Zakharyaschev",
"author_id": 94687,
"author_profile": "https://Stackoverflow.com/users/94687",
"pm_score": 5,
"selected": false,
"text": "$ for remote in origin github memorystick; do git push $remote; done\n [remote \"all\"]\nurl = master.kernel.org:/pub/scm/linux/kernel/git/torvalds/linux-2.6\nurl = login.osdl.org:linux-2.6.git\n git push all master [url \"<actual url base>\"]\n insteadOf = <other url base>\n"
},
{
"answer_id": 2731946,
"author": "Danny G",
"author_id": 328168,
"author_profile": "https://Stackoverflow.com/users/328168",
"pm_score": 2,
"selected": false,
"text": "./bin/ # prepended to $PATH\n./lib/ # prepended to $LD_LIBRARY_PATH\n./lib/python/ # prepended to $PYTHONPATH\n./setup_env.bash # sets up the environment\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
36,876 |
<p>I am using forms authentication. My users are redirected to a page (written in web.config) when they login, but some of them may not have the privilages to access this default page. In this case, I want them to redirect to another page but RedirectFromLoginPage method always redirects to the default page in web.config. How do I make the users login, and then redirect to a page which depends on some criteria?</p>
|
[
{
"answer_id": 36879,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 4,
"selected": true,
"text": "SetAuthCookie"
},
{
"answer_id": 11499845,
"author": "peyman",
"author_id": 1528166,
"author_profile": "https://Stackoverflow.com/users/1528166",
"pm_score": 1,
"selected": false,
"text": "if(mc.GetfaalUsers(mm.UserName.ToString())==\"True\")\n{\n this.Page.ClientScript.\n RegisterClientScriptBlock(this.GetType(), \"key\", \n \"alert('این نام کاربری فعال نشده است');\", false);\n FormsAuthentication.SignOut();\n Response.Redirect(\"default.aspx\");\n}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
36,877 |
<p>How can I set the cookies in my <code>PHP apps</code> as <code>HttpOnly cookies</code>?</p>
|
[
{
"answer_id": 36880,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": 3,
"selected": false,
"text": "header(\"Set-Cookie: hidden=value; httpOnly\");\n"
},
{
"answer_id": 36882,
"author": "Marius",
"author_id": 1585,
"author_profile": "https://Stackoverflow.com/users/1585",
"pm_score": 3,
"selected": false,
"text": "<?php\n//None HttpOnly cookie:\nsetcookie(\"abc\", \"test\", NULL, NULL, NULL, NULL, FALSE); \n\n//HttpOnly cookie:\nsetcookie(\"abc\", \"test\", NULL, NULL, NULL, NULL, TRUE); \n\n?>\n"
},
{
"answer_id": 36883,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 3,
"selected": false,
"text": "setcookie('Foo','Bar',0,'/', 'www.sample.com' , FALSE, TRUE);\n"
},
{
"answer_id": 36885,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 8,
"selected": true,
"text": "PHPSESSID setcookie() setrawcookie() httponly setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )\nsetrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly )\n NULL setcookie( $name, $value, httponly:true )\n header() header( \"Set-Cookie: name=value; HttpOnly\" );\n Secure"
},
{
"answer_id": 250458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "httponly $sess_name = session_name();\nif (session_start()) {\n setcookie($sess_name, session_id(), null, '/', null, null, true);\n}\n session_name() session_start()"
},
{
"answer_id": 8726269,
"author": "richie",
"author_id": 1105047,
"author_profile": "https://Stackoverflow.com/users/1105047",
"pm_score": 7,
"selected": false,
"text": ".htaccess <IfModule php5_module>\n php_flag session.cookie_httponly on\n</IfModule>\n session_start() ini_set( 'session.cookie_httponly', 1 );\n"
},
{
"answer_id": 16781285,
"author": "Marius",
"author_id": 2335501,
"author_profile": "https://Stackoverflow.com/users/2335501",
"pm_score": 2,
"selected": false,
"text": "// setup session enviroment\nini_set('session.cookie_httponly',1);\nini_set('session.use_only_cookies',1);\n"
},
{
"answer_id": 20081735,
"author": "Mareg",
"author_id": 1117506,
"author_profile": "https://Stackoverflow.com/users/1117506",
"pm_score": 2,
"selected": false,
"text": "php_flag session.cookie_httponly On\n"
},
{
"answer_id": 61391222,
"author": "Hein",
"author_id": 13392025,
"author_profile": "https://Stackoverflow.com/users/13392025",
"pm_score": 0,
"selected": false,
"text": "session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);\n"
},
{
"answer_id": 69456549,
"author": "rei",
"author_id": 13674736,
"author_profile": "https://Stackoverflow.com/users/13674736",
"pm_score": 0,
"selected": false,
"text": "session_start(['cookie_lifetime' => 43200,'cookie_secure' => true,'cookie_httponly' => true]);"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3871/"
] |
36,881 |
<p>I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.</p>
<p>The TabSpecs are created in this way within a <code>setupTabs()</code> method which loops to create the appropriate number of tabs:</p>
<pre><code>TabSpec ts = mTabs.newTabSpec("tab");
ts.setIndicator("TabTitle", iconResource);
ts.setContent(new TabHost.TabContentFactory(
{
public View createTabContent(String tag)
{
...
}
});
mTabs.addTab(ts);
</code></pre>
<p>There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.</p>
<pre><code>mTabs.getTabWidget().removeAllViews();
mTabs.clearAllTabs(true);
setupTabs();
</code></pre>
<p>Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?</p>
|
[
{
"answer_id": 68078,
"author": "dmazzoni",
"author_id": 7193,
"author_profile": "https://Stackoverflow.com/users/7193",
"pm_score": 6,
"selected": true,
"text": "TabHost TabSpec TabSpec mTabs.getTabWidget() TabWidget ViewGroup getChildCount() getChildAt() TabWidget ViewGroup LinearLayout ImageView TextView Log.i ImageView"
},
{
"answer_id": 504023,
"author": "srakyi",
"author_id": 56276,
"author_profile": "https://Stackoverflow.com/users/56276",
"pm_score": 5,
"selected": false,
"text": "tabHost.setOnTabChangedListener(new OnTabChangeListener() {\n public void onTabChanged(String tabId) {\n if (TAB_MAP.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));\n } else if (TAB_LIST.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));\n }\n }\n});\n"
},
{
"answer_id": 6627972,
"author": "Mohit",
"author_id": 620661,
"author_profile": "https://Stackoverflow.com/users/620661",
"pm_score": 3,
"selected": false,
"text": "public void updateTab(int stringID) {\n ViewGroup identifyView = (ViewGroup)getTabWidget().getChildAt(0);\n TextView v = (TextView)identifyView.getChildAt(identifyView.getChildCount() - 1);\n v.setText(stringID);\n}\n getParent().updateTab(R.string.tab_bar_analyze);\n"
},
{
"answer_id": 11808808,
"author": "Gautam Vasoya",
"author_id": 1500667,
"author_profile": "https://Stackoverflow.com/users/1500667",
"pm_score": 2,
"selected": false,
"text": "tabHost.setOnTabChangedListener(new OnTabChangeListener() {\n public void onTabChanged(String tabId) {\n if (TAB_MAP.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_black));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_white));\n } else if (TAB_LIST.equals(tabId)) {\n ImageView iv = (ImageView) tabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_map_white));\n iv = (ImageView) tabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.icon);\n iv.setImageDrawable(getResources().getDrawable(R.drawable.tab_list_black));\n }\n }\n});\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1197/"
] |
36,889 |
<p>We've been running <a href="http://eaccelerator.net/" rel="noreferrer" title="eAccelerator">eAccelerator</a> on each of 3 webservers and are looking to move to a <a href="http://www.danga.com/memcached/" rel="noreferrer" title="memcache">memcache</a> pool across all 3, hopefully reducing by about 2/3 our db lookups.</p>
<p>One of the handy things about eAccelerator is the web-based control interface (<a href="http://eaccelerator.net/browser/eaccelerator/tags/0.9.5-rc1/control.php" rel="noreferrer" title="control.php">control.php</a>), which has proved very useful when we've had to flush the cache unexpectedly, quickly monitor which scripts are in cache, etc.</p>
<p>We've been looking but haven't found anything that offers the same type of functionality for memcache - does anyone know if such a thing exists?</p>
<p>Obviously flushing cache etc is easy enough with memcache on the console, but our particular set-up means we may have guys monitoring our front-end and needing to flush the cache who will not necessarily have shell access on the servers. </p>
|
[
{
"answer_id": 26085210,
"author": "Bainternet",
"author_id": 783536,
"author_profile": "https://Stackoverflow.com/users/783536",
"pm_score": 3,
"selected": false,
"text": "github"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2287/"
] |
36,890 |
<p>I'd like to add a method to my existing server's CORBA interface. Will that require recompiling all clients?</p>
<p>I'm using TAO.</p>
|
[
{
"answer_id": 20404774,
"author": "shijie xu",
"author_id": 910118,
"author_profile": "https://Stackoverflow.com/users/910118",
"pm_score": 0,
"selected": false,
"text": " remoteObjRef->invoke(\"methodname\", args); // send(\"methodname\", args)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3583/"
] |
36,901 |
<p>What do <code>*args</code> and <code>**kwargs</code> mean?</p>
<pre><code>def foo(x, y, *args):
def bar(x, y, **kwargs):
</code></pre>
|
[
{
"answer_id": 36908,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 13,
"selected": true,
"text": "*args **kwargs *args def foo(*args):\n for a in args:\n print(a) \n\nfoo(1)\n# 1\n\nfoo(1,2,3)\n# 1\n# 2\n# 3\n **kwargs def bar(**kwargs):\n for a in kwargs:\n print(a, kwargs[a]) \n\nbar(name='one', age=27)\n# name one\n# age 27\n def foo(kind, *args, **kwargs):\n pass\n def foo(a, b, c):\n print(a, b, c)\n\nobj = {'b':10, 'c':'lee'}\n\nfoo(100,**obj)\n# 100 10 lee\n *l def foo(bar, lee):\n print(bar, lee)\n\nl = [1,2]\n\nfoo(*l)\n# 1 2\n *l first, *rest = [1,2,3,4]\nfirst, *l, last = [1,2,3,4]\n def func(arg1, arg2, arg3, *, kwarg1, kwarg2):\n pass\n >>> x = [1, 2]\n>>> [*x]\n[1, 2]\n>>> [*x, 3, 4]\n[1, 2, 3, 4]\n\n>>> x = {1:1, 2:2}\n>>> x\n{1: 1, 2: 2}\n>>> {**x, 3:3, 4:4}\n{1: 1, 2: 2, 3: 3, 4: 4}\n * dict **kwargs"
},
{
"answer_id": 36911,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 8,
"selected": false,
"text": "foo() foo(1,2,3,4,5) bar() bar(1, a=2, b=3) def foo(param1, *param2):\n print(param1)\n print(param2)\n\ndef bar(param1, **param2):\n print(param1)\n print(param2)\n\nfoo(1,2,3,4,5)\nbar(1,a=2,b=3)\n 1\n(2, 3, 4, 5)\n1\n{'a': 2, 'b': 3}\n"
},
{
"answer_id": 36926,
"author": "Lorin Hochstein",
"author_id": 742,
"author_profile": "https://Stackoverflow.com/users/742",
"pm_score": 10,
"selected": false,
"text": "* ** def foo(x,y,z):\n print(\"x=\" + str(x))\n print(\"y=\" + str(y))\n print(\"z=\" + str(z))\n >>> mylist = [1,2,3]\n>>> foo(*mylist)\nx=1\ny=2\nz=3\n\n>>> mydict = {'x':1,'y':2,'z':3}\n>>> foo(**mydict)\nx=1\ny=2\nz=3\n\n>>> mytuple = (1, 2, 3)\n>>> foo(*mytuple)\nx=1\ny=2\nz=3\n mydict foo TypeError >>> mydict = {'x':1,'y':2,'z':3,'badnews':9}\n>>> foo(**mydict)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: foo() got an unexpected keyword argument 'badnews'\n"
},
{
"answer_id": 12362812,
"author": "ronak",
"author_id": 1327247,
"author_profile": "https://Stackoverflow.com/users/1327247",
"pm_score": 5,
"selected": false,
"text": "* ** * **"
},
{
"answer_id": 26365795,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 8,
"selected": false,
"text": "** * * ** *args args **kwargs kwargs args kwargs *args **kwargs *args >>> x = xrange(3) # create our *args - an iterable of 3 integers\n>>> xrange(*x) # expand here\nxrange(0, 2, 2)\n str.format >>> foo = 'FOO'\n>>> bar = 'BAR'\n>>> 'this is foo, {foo} and bar, {bar}'.format(**locals())\n'this is foo, FOO and bar, BAR'\n *args kwarg2 def foo(arg, kwarg=None, *args, kwarg2=None, **kwargs): \n return arg, kwarg, args, kwarg2, kwargs\n >>> foo(1,2,3,4,5,kwarg2='kwarg2', bar='bar', baz='baz')\n(1, 2, (3, 4, 5), 'kwarg2', {'bar': 'bar', 'baz': 'baz'})\n * def foo(arg, kwarg=None, *, kwarg2=None, **kwargs): \n return arg, kwarg, kwarg2, kwargs\n kwarg2 >>> foo(1,2,kwarg2='kwarg2', foo='foo', bar='bar')\n(1, 2, 'kwarg2', {'foo': 'foo', 'bar': 'bar'})\n *args* >>> foo(1,2,3,4,5, kwarg2='kwarg2', foo='foo', bar='bar')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: foo() takes from 1 to 2 positional arguments \n but 5 positional arguments (and 1 keyword-only argument) were given\n kwarg def bar(*, kwarg=None): \n return kwarg\n kwarg >>> bar('kwarg')\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: bar() takes 0 positional arguments but 1 was given\n kwarg >>> bar(kwarg='kwarg')\n'kwarg'\n *args **kwargs * ** *foos **bars b def foo(a, b=10, *args, **kwargs):\n '''\n this function takes required argument a, not required keyword argument b\n and any number of unknown positional arguments and keyword arguments after\n '''\n print('a is a required argument, and its value is {0}'.format(a))\n print('b not required, its default value is 10, actual value: {0}'.format(b))\n # we can inspect the unknown arguments we were passed:\n # - args:\n print('args is of type {0} and length {1}'.format(type(args), len(args)))\n for arg in args:\n print('unknown arg: {0}'.format(arg))\n # - kwargs:\n print('kwargs is of type {0} and length {1}'.format(type(kwargs),\n len(kwargs)))\n for kw, arg in kwargs.items():\n print('unknown kwarg - kw: {0}, arg: {1}'.format(kw, arg))\n # But we don't have to know anything about them \n # to pass them to other functions.\n print('Args or kwargs can be passed without knowing what they are.')\n # max can take two or more positional args: max(a, b, c...)\n print('e.g. max(a, b, *args) \\n{0}'.format(\n max(a, b, *args))) \n kweg = 'dict({0})'.format( # named args same as unknown kwargs\n ', '.join('{k}={v}'.format(k=k, v=v) \n for k, v in sorted(kwargs.items())))\n print('e.g. dict(**kwargs) (same as {kweg}) returns: \\n{0}'.format(\n dict(**kwargs), kweg=kweg))\n help(foo) foo(a, b=10, *args, **kwargs)\n foo(1, 2, 3, 4, e=5, f=6, g=7) a is a required argument, and its value is 1\nb not required, its default value is 10, actual value: 2\nargs is of type <type 'tuple'> and length 2\nunknown arg: 3\nunknown arg: 4\nkwargs is of type <type 'dict'> and length 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: g, arg: 7\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n4\ne.g. dict(**kwargs) (same as dict(e=5, f=6, g=7)) returns: \n{'e': 5, 'g': 7, 'f': 6}\n a def bar(a):\n b, c, d, e, f = 2, 3, 4, 5, 6\n # dumping every local variable into foo as a keyword argument \n # by expanding the locals dict:\n foo(**locals()) \n bar(100) a is a required argument, and its value is 100\nb not required, its default value is 10, actual value: 2\nargs is of type <type 'tuple'> and length 0\nkwargs is of type <type 'dict'> and length 4\nunknown kwarg - kw: c, arg: 3\nunknown kwarg - kw: e, arg: 5\nunknown kwarg - kw: d, arg: 4\nunknown kwarg - kw: f, arg: 6\nArgs or kwargs can be passed without knowing what they are.\ne.g. max(a, b, *args) \n100\ne.g. dict(**kwargs) (same as dict(c=3, d=4, e=5, f=6)) returns: \n{'c': 3, 'e': 5, 'd': 4, 'f': 6}\n def foo(a, b, c, d=0, e=100):\n # imagine this is much more code than a simple function call\n preprocess() \n differentiating_process_foo(a,b,c,d,e)\n # imagine this is much more code than a simple function call\n postprocess()\n\ndef bar(a, b, c=None, d=0, e=100, f=None):\n preprocess()\n differentiating_process_bar(a,b,c,d,e,f)\n postprocess()\n\ndef baz(a, b, c, d, e, f):\n ... and so on\n *args **kwargs def decorator(function):\n '''function to wrap other functions with a pre- and postprocess'''\n @functools.wraps(function) # applies module, name, and docstring to wrapper\n def wrapper(*args, **kwargs):\n # again, imagine this is complicated, but we only write it once!\n preprocess()\n function(*args, **kwargs)\n postprocess()\n return wrapper\n @decorator\ndef foo(a, b, c, d=0, e=100):\n differentiating_process_foo(a,b,c,d,e)\n\n@decorator\ndef bar(a, b, c=None, d=0, e=100, f=None):\n differentiating_process_bar(a,b,c,d,e,f)\n\n@decorator\ndef baz(a, b, c=None, d=0, e=100, f=None, g=None):\n differentiating_process_baz(a,b,c,d,e,f, g)\n\n@decorator\ndef quux(a, b, c=None, d=0, e=100, f=None, g=None, h=None):\n differentiating_process_quux(a,b,c,d,e,f,g,h)\n *args **kwargs"
},
{
"answer_id": 32031804,
"author": "quiet_penguin",
"author_id": 1086143,
"author_profile": "https://Stackoverflow.com/users/1086143",
"pm_score": 3,
"selected": false,
"text": "__init__ def __init__(self, *args, **kwargs):\n for attribute_name, value in zip(self._expected_attributes, args):\n setattr(self, attribute_name, value)\n if kwargs.has_key(attribute_name):\n kwargs.pop(attribute_name)\n\n for attribute_name in kwargs.viewkeys():\n setattr(self, attribute_name, kwargs[attribute_name])\n class RetailItem(Item):\n _expected_attributes = Item._expected_attributes + ['name', 'price', 'category', 'country_of_origin']\n\nclass FoodItem(RetailItem):\n _expected_attributes = RetailItem._expected_attributes + ['expiry_date']\n food_item = FoodItem(name = 'Jam', \n price = 12.0, \n category = 'Foods', \n country_of_origin = 'US', \n expiry_date = datetime.datetime.now())\n __init__ class ElectronicAccessories(RetailItem):\n _expected_attributes = RetailItem._expected_attributes + ['specifications']\n # Depend on args and kwargs to populate the data as needed.\n def __init__(self, specifications = None, *args, **kwargs):\n self.specifications = specifications # Rest of attributes will make sense to parent class.\n super(ElectronicAccessories, self).__init__(*args, **kwargs)\n usb_key = ElectronicAccessories(name = 'Sandisk', \n price = '$6.00', \n category = 'Electronics',\n country_of_origin = 'CN',\n specifications = '4GB USB 2.0/USB 3.0')\n"
},
{
"answer_id": 34166505,
"author": "leewz",
"author_id": 2963903,
"author_profile": "https://Stackoverflow.com/users/2963903",
"pm_score": 4,
"selected": false,
"text": "list dict tuple set >>> (0, *range(1, 4), 5, *range(6, 8))\n(0, 1, 2, 3, 5, 6, 7)\n>>> [0, *range(1, 4), 5, *range(6, 8)]\n[0, 1, 2, 3, 5, 6, 7]\n>>> {0, *range(1, 4), 5, *range(6, 8)}\n{0, 1, 2, 3, 5, 6, 7}\n>>> d = {'one': 1, 'two': 2, 'three': 3}\n>>> e = {'six': 6, 'seven': 7}\n>>> {'zero': 0, **d, 'five': 5, **e}\n{'five': 5, 'seven': 7, 'two': 2, 'one': 1, 'three': 3, 'six': 6, 'zero': 0}\n >>> range(*[1, 10], *[2])\nrange(1, 10, 2)\n"
},
{
"answer_id": 34899056,
"author": "mrtechmaker",
"author_id": 1542490,
"author_profile": "https://Stackoverflow.com/users/1542490",
"pm_score": 6,
"selected": false,
"text": "def test(a,b,c):\n print(a)\n print(b)\n print(c)\n\ntest(1,2,3)\n#output:\n1\n2\n3\n def test(a,b,c):\n print(a)\n print(b)\n print(c)\n\ntest(a=1,b=2,c=3)\n#output:\n1\n2\n3\n def test(a=0,b=0,c=0):\n print(a)\n print(b)\n print(c)\n print('-------------------------')\n\ntest(a=1,b=2,c=3)\n#output :\n1\n2\n3\n-------------------------\n def test(a=0,b=0,c=0):\n print(a)\n print(b)\n print(c)\n print('-------------------------')\n\ntest(1,2,3)\n# output :\n1\n2\n3\n---------------------------------\n def sum(a,b): #receive args from function calls as sum(1,2) or sum(a=1,b=2)\n print(a+b)\n\nmy_tuple = (1,2)\nmy_list = [1,2]\nmy_dict = {'a':1,'b':2}\n\n# Let us unpack data structure of list or tuple or dict into arguments with help of '*' operator\nsum(*my_tuple) # becomes same as sum(1,2) after unpacking my_tuple with '*'\nsum(*my_list) # becomes same as sum(1,2) after unpacking my_list with '*'\nsum(**my_dict) # becomes same as sum(a=1,b=2) after unpacking by '**' \n\n# output is 3 in all three calls to sum function.\n def sum(*args): #pack the received positional args into data structure of tuple. after applying '*' - def sum((1,2,3,4))\n sum = 0\n for a in args:\n sum+=a\n print(sum)\n\nsum(1,2,3,4) #positional args sent to function sum\n#output:\n10\n def sum(**args): #pack keyword args into datastructure of dict after applying '**' - def sum({a:1,b:2,c:3,d:4})\n sum=0\n for k,v in args.items():\n sum+=v\n print(sum)\n\nsum(a=1,b=2,c=3,d=4) #positional args sent to function sum\n"
},
{
"answer_id": 40262722,
"author": "amir jj",
"author_id": 3066559,
"author_profile": "https://Stackoverflow.com/users/3066559",
"pm_score": 2,
"selected": false,
"text": ">>> def foo(*arg,**kwargs):\n... print arg\n... print kwargs\n>>>\n>>> a = (1, 2, 3)\n>>> b = {'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(*a,**b)\n(1, 2, 3)\n{'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(a,**b) \n((1, 2, 3),)\n{'aa': 11, 'bb': 22}\n>>>\n>>>\n>>> foo(a,b) \n((1, 2, 3), {'aa': 11, 'bb': 22})\n{}\n>>>\n>>>\n>>> foo(a,*b)\n((1, 2, 3), 'aa', 'bb')\n{}\n"
},
{
"answer_id": 40492308,
"author": "Lochu'an Chang",
"author_id": 7132449,
"author_profile": "https://Stackoverflow.com/users/7132449",
"pm_score": 4,
"selected": false,
"text": "x = [1, 2, 3]\ny = [4, 5, 6]\n\nunzip_x, unzip_y = zip(*zip(x, y))\n zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))\n"
},
{
"answer_id": 40823181,
"author": "thanhtang",
"author_id": 5098762,
"author_profile": "https://Stackoverflow.com/users/5098762",
"pm_score": 2,
"selected": false,
"text": "*args **kwargs super class base(object):\n def __init__(self, base_param):\n self.base_param = base_param\n\n\nclass child1(base): # inherited from base class\n def __init__(self, child_param, *args) # *args for non-keyword args\n self.child_param = child_param\n super(child1, self).__init__(*args) # call __init__ of the base class and initialize it with a NON-KEYWORD arg\n\nclass child2(base):\n def __init__(self, child_param, **kwargs):\n self.child_param = child_param\n super(child2, self).__init__(**kwargs) # call __init__ of the base class and initialize it with a KEYWORD arg\n\nc1 = child1(1,0)\nc2 = child2(1,base_param=0)\nprint c1.base_param # 0\nprint c1.child_param # 1\nprint c2.base_param # 0\nprint c2.child_param # 1\n"
},
{
"answer_id": 47580283,
"author": "Brad Solomon",
"author_id": 7954504,
"author_profile": "https://Stackoverflow.com/users/7954504",
"pm_score": 6,
"selected": false,
"text": "* ** In function construction In function call\n=======================================================================\n | def f(*args): | def f(a, b):\n*args | for arg in args: | return a + b\n | print(arg) | args = (1, 2)\n | f(1, 2) | f(*args)\n----------|--------------------------------|---------------------------\n | def f(a, b): | def f(a, b):\n**kwargs | return a + b | return a + b\n | def g(**kwargs): | kwargs = dict(a=1, b=2)\n | return f(**kwargs) | f(**kwargs)\n | g(a=1, b=2) |\n-----------------------------------------------------------------------\n"
},
{
"answer_id": 50116852,
"author": "Hrvoje",
"author_id": 2119941,
"author_profile": "https://Stackoverflow.com/users/2119941",
"pm_score": 2,
"selected": false,
"text": "*args **kwargs *args def args(normal_arg, *argv):\n print(\"normal argument:\", normal_arg)\n\n for arg in argv:\n print(\"Argument in list of arguments from *argv:\", arg)\n\nargs('animals', 'fish', 'duck', 'bird')\n normal argument: animals\nArgument in list of arguments from *argv: fish\nArgument in list of arguments from *argv: duck\nArgument in list of arguments from *argv: bird\n **kwargs* **kwargs **kwargs def who(**kwargs):\n if kwargs is not None:\n for key, value in kwargs.items():\n print(\"Your %s is %s.\" % (key, value))\n\nwho(name=\"Nikola\", last_name=\"Tesla\", birthday=\"7.10.1856\", birthplace=\"Croatia\") \n Your name is Nikola.\nYour last_name is Tesla.\nYour birthday is 7.10.1856.\nYour birthplace is Croatia.\n"
},
{
"answer_id": 50461663,
"author": "Miladiouss",
"author_id": 7428659,
"author_profile": "https://Stackoverflow.com/users/7428659",
"pm_score": 5,
"selected": false,
"text": "* f(*myList) ** f(**{'x' : 1, 'y' : 2}) x y myArgs myKW y myArgDict def f(x, y, *myArgs, **myKW):\n print(\"# x = {}\".format(x))\n print(\"# y = {}\".format(y))\n print(\"# myArgs = {}\".format(myArgs))\n print(\"# myKW = {}\".format(myKW))\n print(\"# ----------------------------------------------------------------------\")\n\n# Define a list for demonstration purposes\nmyList = [\"Left\", \"Right\", \"Up\", \"Down\"]\n# Define a dictionary for demonstration purposes\nmyDict = {\"Wubba\": \"lubba\", \"Dub\": \"dub\"}\n# Define a dictionary to feed y\nmyArgDict = {'y': \"Why?\", 'y0': \"Why not?\", \"q\": \"Here is a cue!\"}\n\n# The 1st elem of myList feeds y\nf(\"myEx\", *myList, **myDict)\n# x = myEx\n# y = Left\n# myArgs = ('Right', 'Up', 'Down')\n# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}\n# ----------------------------------------------------------------------\n\n# y is matched and fed first\n# The rest of myArgDict becomes additional arguments feeding myKW\nf(\"myEx\", **myArgDict)\n# x = myEx\n# y = Why?\n# myArgs = ()\n# myKW = {'y0': 'Why not?', 'q': 'Here is a cue!'}\n# ----------------------------------------------------------------------\n\n# The rest of myArgDict becomes additional arguments feeding myArgs\nf(\"myEx\", *myArgDict)\n# x = myEx\n# y = y\n# myArgs = ('y0', 'q')\n# myKW = {}\n# ----------------------------------------------------------------------\n\n# Feed extra arguments manually and append even more from my list\nf(\"myEx\", 4, 42, 420, *myList, *myDict, **myDict)\n# x = myEx\n# y = 4\n# myArgs = (42, 420, 'Left', 'Right', 'Up', 'Down', 'Wubba', 'Dub')\n# myKW = {'Wubba': 'lubba', 'Dub': 'dub'}\n# ----------------------------------------------------------------------\n\n# Without the stars, the entire provided list and dict become x, and y:\nf(myList, myDict)\n# x = ['Left', 'Right', 'Up', 'Down']\n# y = {'Wubba': 'lubba', 'Dub': 'dub'}\n# myArgs = ()\n# myKW = {}\n# ----------------------------------------------------------------------\n ** ** *"
},
{
"answer_id": 51733267,
"author": "ishandutta2007",
"author_id": 865220,
"author_profile": "https://Stackoverflow.com/users/865220",
"pm_score": 4,
"selected": false,
"text": "* ** def foo(*args):\n for arg in args:\n print(arg)\n\nfoo(\"two\", 3)\n two\n3\n ** def bar(**kwargs):\n for key in kwargs:\n print(key, kwargs[key])\n\nbar(dic1=\"two\", dic2=3)\n dic1 two\ndic2 3\n"
},
{
"answer_id": 52134172,
"author": "Premraj",
"author_id": 1697099,
"author_profile": "https://Stackoverflow.com/users/1697099",
"pm_score": 0,
"selected": false,
"text": "def foo(param1, *param2): *param2 def bar(param1, **param2): *param2 param1 accessModifier methodName(datatype… arg) {\n // method body\n}\n"
},
{
"answer_id": 55475113,
"author": "RBF06",
"author_id": 3311728,
"author_profile": "https://Stackoverflow.com/users/3311728",
"pm_score": 4,
"selected": false,
"text": "list dict def func(*args, **kwds):\n # do stuff\n args kwds func(\"this\", \"is a list of\", \"non-keyowrd\", \"arguments\", keyword=\"ligma\", options=[1,2,3])\n args [\"this\", \"is a list of\", \"non-keyword\", \"arguments\"] kwds dict {\"keyword\" : \"ligma\", \"options\" : [1,2,3]} def f(a, b, c, d=1, e=10):\n # do stuff\n iterable = [1, 20, 500]\nmapping = {\"d\" : 100, \"e\": 3}\nf(*iterable, **mapping)\n# That call is equivalent to\nf(1, 20, 500, d=100, e=3)\n"
},
{
"answer_id": 56962836,
"author": "Raj",
"author_id": 8588359,
"author_profile": "https://Stackoverflow.com/users/8588359",
"pm_score": 3,
"selected": false,
"text": "def foo(param1, *param2):\n print(param1)\n print(param2)\n\n\ndef bar(param1, **param2):\n print(param1)\n print(param2)\n\n\ndef three_params(param1, *param2, **param3):\n print(param1)\n print(param2)\n print(param3)\n\n\nfoo(1, 2, 3, 4, 5)\nprint(\"\\n\")\nbar(1, a=2, b=3)\nprint(\"\\n\")\nthree_params(1, 2, 3, 4, s=5)\n 1\n(2, 3, 4, 5)\n\n1\n{'a': 2, 'b': 3}\n\n1\n(2, 3, 4)\n{'s': 5}\n"
},
{
"answer_id": 59217020,
"author": "dreftymac",
"author_id": 42223,
"author_profile": "https://Stackoverflow.com/users/42223",
"pm_score": 2,
"selected": false,
"text": "** ** str.format f-strings ## init vars\n ddvars = dict()\n ddcalc = dict()\n pass\n ddvars['fname'] = 'Huomer'\n ddvars['lname'] = 'Huimpson'\n ddvars['motto'] = 'I love donuts!'\n ddvars['age'] = 33\n pass\n ddcalc['ydiff'] = 5\n ddcalc['ycalc'] = ddvars['age'] + ddcalc['ydiff']\n pass\n vdemo = []\n\n ## ********************\n ## single unpack supported in py 2.7\n vdemo.append('''\n Hello {fname} {lname}!\n\n Today you are {age} years old!\n\n We love your motto \"{motto}\" and we agree with you!\n '''.format(**ddvars)) \n pass\n\n ## ********************\n ## multiple unpack supported in py 3.x\n vdemo.append('''\n Hello {fname} {lname}!\n\n In {ydiff} years you will be {ycalc} years old!\n '''.format(**ddvars,**ddcalc)) \n pass\n\n ## ********************\n print(vdemo[-1])\n\n"
},
{
"answer_id": 59630576,
"author": "Meysam Sadeghi",
"author_id": 3484477,
"author_profile": "https://Stackoverflow.com/users/3484477",
"pm_score": 5,
"selected": false,
"text": "* ** *args def foo(*args): pass foo foo(1) foo(1, 'bar') **kwargs def foo(**kwargs): pass foo(name='Tom') foo(name='Tom', age=33) *args, **kwargs def foo(*args, **kwargs): pass foo foo(1,name='Tom') foo(1, 'bar', name='Tom', age=33) * def foo(pos1, pos2, *, kwarg1): pass * foo(1, 2, 3) foo(1, 2, kwarg1=3) *_ def foo(bar, baz, *_): pass foo bar baz **_ def foo(bar, baz, **_): pass foo bar baz / def f(a, b, /, c, d, *, e, f):\n pass\n * ** function call functions signature for loops"
},
{
"answer_id": 62442187,
"author": "etoricky",
"author_id": 4710031,
"author_profile": "https://Stackoverflow.com/users/4710031",
"pm_score": 3,
"selected": false,
"text": "sum = lambda x, y, z: x + y + z\nsum(1,2,3) # sum 3 items\n\nsum([1,2,3]) # error, needs 3 items, not 1 list\n\nx = [1,2,3][0]\ny = [1,2,3][1]\nz = [1,2,3][2]\nsum(x,y,z) # ok\n\nsum(*[1,2,3]) # ok, 1 list becomes 3 items\n"
},
{
"answer_id": 66705594,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "def any_param(*param):\n pass\n\nany_param(1)\nany_param(1,1)\nany_param(1,1,1)\nany_param(1,...)\n def any_param(*param):\n pass\n\nany_param() # will work correct\n def any_param(*param):\n return type(param)\n\nany_param(1) #tuple\nany_param() # tuple\n def any(*param):\n param[0] # correct\n\ndef any(*param):\n *param[0] # incorrect\n def func(**any):\n return type(any) # dict\n\ndef func(**any):\n return any\n\nfunc(width=\"10\",height=\"20\") # {width=\"10\",height=\"20\")\n\n\n"
},
{
"answer_id": 73178373,
"author": "Isaac Vinícius",
"author_id": 16892196,
"author_profile": "https://Stackoverflow.com/users/16892196",
"pm_score": 0,
"selected": false,
"text": "*args **kwargs \ndef print_all(*args, **kwargs):\n print(args) # print any number of arguments like: \"print_all(\"foo\", \"bar\")\"\n print(kwargs.get(\"to_print\")) # print the value of the keyworded argument \"to_print\"\n\n\n# example:\nprint_all(\"Hello\", \"World\", to_print=\"!\")\n# will print:\n\"\"\"\n('Hello', 'World')\n!\n\"\"\"\n"
},
{
"answer_id": 74406075,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "*args **kwargs *args *args ↓\ndef test(*args):\n print(args)\n\ntest() # Here\ntest(1, 2, 3, 4) # Here\ntest((1, 2, 3, 4)) # Here\ntest(*(1, 2, 3, 4)) # Here\n ()\n(1, 2, 3, 4)\n((1, 2, 3, 4),)\n(1, 2, 3, 4)\n *args def test(*args):\n print(*args) # Here\n \ntest(1, 2, 3, 4)\n 1 2 3 4\n args def test(*args):\n print(type(args)) # Here\n \ntest(1, 2, 3, 4)\n <class 'tuple'>\n *args def test(*args):\n print(type(*args)) # Here\n \ntest(1, 2, 3, 4)\n *args ↓ ↓\ndef test(num1, num2, *args):\n print(num1, num2, args)\n \ntest(1, 2, 3, 4)\n 1 2 (3, 4)\n **kwargs *args ↓ \ndef test(**kwargs, *args):\n print(kwargs, args)\n \ntest(num1=1, num2=2, 3, 4)\n *args ↓ ↓\ndef test(*args, num1, num2):\n print(args, num1, num2)\n \ntest(1, 2, 3, 4)\n *args ↓ ↓\ndef test(*args, num1=100, num2=None):\n print(args, num1, num2)\n \ntest(1, 2, num1=3, num2=4)\n (1, 2) 3 4\n **kwargs *args ↓\ndef test(*args, **kwargs):\n print(args, kwargs)\n \ntest(1, 2, num1=3, num2=4)\n (1, 2) {'num1': 3, 'num2': 4}\n **kwargs **kwargs ↓\ndef test(**kwargs):\n print(kwargs)\n\ntest() # Here\ntest(name=\"John\", age=27) # Here\ntest(**{\"name\": \"John\", \"age\": 27}) # Here\n {}\n{'name': 'John', 'age': 27}\n{'name': 'John', 'age': 27}\n *kwargs def test(**kwargs):\n print(*kwargs) # Here\n \ntest(name=\"John\", age=27)\n name age\n kwargs def test(**kwargs):\n print(type(kwargs)) # Here\n \ntest(name=\"John\", age=27)\n <class 'dict'>\n *kwargs **kwargs def test(**kwargs):\n print(type(*kwargs)) # Here\n \ntest(name=\"John\", age=27)\n def test(**kwargs):\n print(type(**kwargs)) # Here\n \ntest(name=\"John\", age=27)\n **kwargs ↓ ↓\ndef test(num1, num2, **kwargs):\n print(num1, num2, kwargs)\n\ntest(1, 2, name=\"John\", age=27)\n 1 2 {'name': 'John', 'age': 27}\n *args **kwargs ↓\ndef test(*args, **kwargs):\n print(args, kwargs)\n\ntest(1, 2, name=\"John\", age=27)\n (1, 2) {'name': 'John', 'age': 27}\n *args **kwargs ↓ ↓\ndef test(**kwargs, num1, num2):\n print(kwargs, num1, num2)\n\ntest(name=\"John\", age=27, 1, 2)\n ↓\ndef test(**kwargs, *args):\n print(kwargs, args)\n\ntest(name=\"John\", age=27, 1, 2)\n *args **kwargs *args **kwargs *args **kwargs ↓ ↓\ndef test(*banana, **orange):\n print(banana, orange)\n \ntest(1, 2, num1=3, num2=4)\n (1, 2) {'num1': 3, 'num2': 4}\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2572/"
] |
36,906 |
<p>I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:</p>
<pre><code>void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
</code></pre>
<p>Or the xor version that I'm sure most people have seen:</p>
<pre><code>void swap(int* a, int* b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
</code></pre>
<p>It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.</p>
|
[
{
"answer_id": 36948,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 0,
"selected": false,
"text": "PUSH A\nA=B\nPOP B\n"
},
{
"answer_id": 44911,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": -1,
"selected": false,
"text": "\nacopy=a;\nbcopy=b;\na=bcopy;\nb=acopy;\n"
},
{
"answer_id": 45512,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "void swap (int *a, int *b)\n{\n for (int i = 1 ; i ; i <<= 1)\n {\n if ((*a & i) != (*b & i))\n {\n *a ^= i;\n *b ^= i;\n }\n }\n}\n"
},
{
"answer_id": 45551,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 3,
"selected": false,
"text": "#define swap(a, b) \\\ndo { \\\n int temp = a; \\\n a = b; \\\n b = temp; \\\n} while(0)\n"
},
{
"answer_id": 46123,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "float a=1.5f,b=4.2f;\nswap (a,b);\n int a=1,temp=3;\nswap (a,temp);\n int &f1 ();\nint &f2 ();\nvoid func ()\n{\n swap (f1 (), f2 ());\n}\n int a[10], b[10], i=0, j=0;\nswap (a[i++], b[j++]);\n bytes = C(p) + C(f)\n size = C(p) + C(f) + n.C(c)\n size = n.C(f)\n void GetValue () { return m_value; }\n mov eax,[ecx + offsetof (m_value)]\n"
},
{
"answer_id": 155888,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 2,
"selected": false,
"text": "typeof() #define swap(a,b) \\\n do { \\\n typeof(a) temp; \\\n temp = a; \\\n a = b; \\\n b = temp; \\\n } while (0)\n\n... \n{\n int a, b;\n swap(a, b);\n unsigned char x, y;\n swap(x, y); /* works with any type */\n}\n"
},
{
"answer_id": 615995,
"author": "Trevor Boyd Smith",
"author_id": 52074,
"author_profile": "https://Stackoverflow.com/users/52074",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid swap_traditional(int * restrict a, int * restrict b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\nvoid swap_xor(int * restrict a, int * restrict b)\n{\n *a ^= *b;\n *b ^= *a;\n *a ^= *b;\n}\n\nint main() {\n int a = 5;\n int b = 6;\n swap_traditional(&a,&b);\n swap_xor(&a,&b);\n}\n .globl swap_traditional\n .type swap_traditional, @function\nswap_traditional:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %edx\n movl 12(%ebp), %ecx\n pushl %ebx\n movl (%edx), %ebx\n movl (%ecx), %eax\n movl %ebx, (%ecx)\n movl %eax, (%edx)\n popl %ebx\n popl %ebp\n ret\n .size swap_traditional, .-swap_traditional\n .p2align 4,,15\n .globl swap_xor\n .type swap_xor, @function\nswap_xor:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %ecx\n movl 12(%ebp), %edx\n movl (%ecx), %eax\n xorl (%edx), %eax\n movl %eax, (%ecx)\n xorl (%edx), %eax\n xorl %eax, (%ecx)\n movl %eax, (%edx)\n popl %ebp\n ret\n .size swap_xor, .-swap_xor\n .p2align 4,,15\n"
},
{
"answer_id": 671298,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n\n#define exchange(a,b) __asm mov eax, a \\\n __asm xchg eax, b \\\n __asm mov a, eax \n\nint main(int arg, char** argv)\n{\n int a = 1, b = 2;\n printf(\"%d %d --> \", a, b);\n exchange(a,b)\n printf(\"%d %d\\r\\n\", a, b);\n return 0;\n}\n"
},
{
"answer_id": 1013116,
"author": "Theofanis Pantelides",
"author_id": 70317,
"author_profile": "https://Stackoverflow.com/users/70317",
"pm_score": -1,
"selected": false,
"text": "void swap(int* a, int* b)\n{\n *a = (*b - *a) + (*b = *a);\n}\n"
},
{
"answer_id": 1533223,
"author": "Vadakkumpadath",
"author_id": 182216,
"author_profile": "https://Stackoverflow.com/users/182216",
"pm_score": -1,
"selected": false,
"text": "#define Swap( a, b ) (a)^=(b)^=(a)^=(b)\n"
},
{
"answer_id": 15006580,
"author": "SugarD",
"author_id": 2092613,
"author_profile": "https://Stackoverflow.com/users/2092613",
"pm_score": 3,
"selected": false,
"text": "SWAP(a++, b++); #define SWAP(type, a, b) \\\n do { type t=(a);(a)=(b);(b)=t; } while (0)\n\nvoid swap(size_t esize, void* a, void* b)\n{\n char* x = (char*) a;\n char* y = (char*) b;\n char* z = x + esize;\n\n for ( ; x < z; x++, y++ )\n SWAP(char, *x, *y);\n}\n"
},
{
"answer_id": 21131338,
"author": "herohuyongtao",
"author_id": 2589776,
"author_profile": "https://Stackoverflow.com/users/2589776",
"pm_score": 3,
"selected": false,
"text": "+/- void swap(int* a, int* b)\n{\n if (a != b) // important to handle a/b share the same reference\n {\n *a = *a+*b;\n *b = *a-*b;\n *a = *a-*b;\n }\n}\n"
},
{
"answer_id": 33602527,
"author": "Ashwin Balaji Kuppuraj",
"author_id": 4477632,
"author_profile": "https://Stackoverflow.com/users/4477632",
"pm_score": -1,
"selected": false,
"text": " x = x ^ y;\n y = x ^ y;\n x = x ^ y;\n"
},
{
"answer_id": 45844392,
"author": "Marcin Snieg",
"author_id": 6093812,
"author_profile": "https://Stackoverflow.com/users/6093812",
"pm_score": 2,
"selected": false,
"text": "float x; cout << \"X:\"; cin >> x;\nfloat y; cout << \"Y:\" ; cin >> y;\n\ncout << \"---------------------\" << endl;\ncout << \"X=\" << x << \", Y=\" << y << endl;\nx=x+y-(y=x);\ncout << \"X=\" << x << \", Y=\" << y << endl;\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3869/"
] |
36,915 |
<p>We have been working with CVS for years, and frequently find it useful to "sticky" a single file here and there.</p>
<p>Is there any way to do this in subversion, specifically from TortoiseSVN?</p>
|
[
{
"answer_id": 36948,
"author": "Tim Ring",
"author_id": 3685,
"author_profile": "https://Stackoverflow.com/users/3685",
"pm_score": 0,
"selected": false,
"text": "PUSH A\nA=B\nPOP B\n"
},
{
"answer_id": 44911,
"author": "paperhorse",
"author_id": 4498,
"author_profile": "https://Stackoverflow.com/users/4498",
"pm_score": -1,
"selected": false,
"text": "\nacopy=a;\nbcopy=b;\na=bcopy;\nb=acopy;\n"
},
{
"answer_id": 45512,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 5,
"selected": false,
"text": "void swap (int *a, int *b)\n{\n for (int i = 1 ; i ; i <<= 1)\n {\n if ((*a & i) != (*b & i))\n {\n *a ^= i;\n *b ^= i;\n }\n }\n}\n"
},
{
"answer_id": 45551,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 3,
"selected": false,
"text": "#define swap(a, b) \\\ndo { \\\n int temp = a; \\\n a = b; \\\n b = temp; \\\n} while(0)\n"
},
{
"answer_id": 46123,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 4,
"selected": false,
"text": "float a=1.5f,b=4.2f;\nswap (a,b);\n int a=1,temp=3;\nswap (a,temp);\n int &f1 ();\nint &f2 ();\nvoid func ()\n{\n swap (f1 (), f2 ());\n}\n int a[10], b[10], i=0, j=0;\nswap (a[i++], b[j++]);\n bytes = C(p) + C(f)\n size = C(p) + C(f) + n.C(c)\n size = n.C(f)\n void GetValue () { return m_value; }\n mov eax,[ecx + offsetof (m_value)]\n"
},
{
"answer_id": 155888,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 2,
"selected": false,
"text": "typeof() #define swap(a,b) \\\n do { \\\n typeof(a) temp; \\\n temp = a; \\\n a = b; \\\n b = temp; \\\n } while (0)\n\n... \n{\n int a, b;\n swap(a, b);\n unsigned char x, y;\n swap(x, y); /* works with any type */\n}\n"
},
{
"answer_id": 615995,
"author": "Trevor Boyd Smith",
"author_id": 52074,
"author_profile": "https://Stackoverflow.com/users/52074",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n#include <stdlib.h>\n\nvoid swap_traditional(int * restrict a, int * restrict b)\n{\n int temp = *a;\n *a = *b;\n *b = temp;\n}\n\nvoid swap_xor(int * restrict a, int * restrict b)\n{\n *a ^= *b;\n *b ^= *a;\n *a ^= *b;\n}\n\nint main() {\n int a = 5;\n int b = 6;\n swap_traditional(&a,&b);\n swap_xor(&a,&b);\n}\n .globl swap_traditional\n .type swap_traditional, @function\nswap_traditional:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %edx\n movl 12(%ebp), %ecx\n pushl %ebx\n movl (%edx), %ebx\n movl (%ecx), %eax\n movl %ebx, (%ecx)\n movl %eax, (%edx)\n popl %ebx\n popl %ebp\n ret\n .size swap_traditional, .-swap_traditional\n .p2align 4,,15\n .globl swap_xor\n .type swap_xor, @function\nswap_xor:\n pushl %ebp\n movl %esp, %ebp\n movl 8(%ebp), %ecx\n movl 12(%ebp), %edx\n movl (%ecx), %eax\n xorl (%edx), %eax\n movl %eax, (%ecx)\n xorl (%edx), %eax\n xorl %eax, (%ecx)\n movl %eax, (%edx)\n popl %ebp\n ret\n .size swap_xor, .-swap_xor\n .p2align 4,,15\n"
},
{
"answer_id": 671298,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": -1,
"selected": false,
"text": "#include <stdio.h>\n\n#define exchange(a,b) __asm mov eax, a \\\n __asm xchg eax, b \\\n __asm mov a, eax \n\nint main(int arg, char** argv)\n{\n int a = 1, b = 2;\n printf(\"%d %d --> \", a, b);\n exchange(a,b)\n printf(\"%d %d\\r\\n\", a, b);\n return 0;\n}\n"
},
{
"answer_id": 1013116,
"author": "Theofanis Pantelides",
"author_id": 70317,
"author_profile": "https://Stackoverflow.com/users/70317",
"pm_score": -1,
"selected": false,
"text": "void swap(int* a, int* b)\n{\n *a = (*b - *a) + (*b = *a);\n}\n"
},
{
"answer_id": 1533223,
"author": "Vadakkumpadath",
"author_id": 182216,
"author_profile": "https://Stackoverflow.com/users/182216",
"pm_score": -1,
"selected": false,
"text": "#define Swap( a, b ) (a)^=(b)^=(a)^=(b)\n"
},
{
"answer_id": 15006580,
"author": "SugarD",
"author_id": 2092613,
"author_profile": "https://Stackoverflow.com/users/2092613",
"pm_score": 3,
"selected": false,
"text": "SWAP(a++, b++); #define SWAP(type, a, b) \\\n do { type t=(a);(a)=(b);(b)=t; } while (0)\n\nvoid swap(size_t esize, void* a, void* b)\n{\n char* x = (char*) a;\n char* y = (char*) b;\n char* z = x + esize;\n\n for ( ; x < z; x++, y++ )\n SWAP(char, *x, *y);\n}\n"
},
{
"answer_id": 21131338,
"author": "herohuyongtao",
"author_id": 2589776,
"author_profile": "https://Stackoverflow.com/users/2589776",
"pm_score": 3,
"selected": false,
"text": "+/- void swap(int* a, int* b)\n{\n if (a != b) // important to handle a/b share the same reference\n {\n *a = *a+*b;\n *b = *a-*b;\n *a = *a-*b;\n }\n}\n"
},
{
"answer_id": 33602527,
"author": "Ashwin Balaji Kuppuraj",
"author_id": 4477632,
"author_profile": "https://Stackoverflow.com/users/4477632",
"pm_score": -1,
"selected": false,
"text": " x = x ^ y;\n y = x ^ y;\n x = x ^ y;\n"
},
{
"answer_id": 45844392,
"author": "Marcin Snieg",
"author_id": 6093812,
"author_profile": "https://Stackoverflow.com/users/6093812",
"pm_score": 2,
"selected": false,
"text": "float x; cout << \"X:\"; cin >> x;\nfloat y; cout << \"Y:\" ; cin >> y;\n\ncout << \"---------------------\" << endl;\ncout << \"X=\" << x << \", Y=\" << y << endl;\nx=x+y-(y=x);\ncout << \"X=\" << x << \", Y=\" << y << endl;\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
36,932 |
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p>
<p>How can I represent the equivalent of an Enum in Python? </p>
|
[
{
"answer_id": 36937,
"author": "Alexandru Nedelcu",
"author_id": 3280,
"author_profile": "https://Stackoverflow.com/users/3280",
"pm_score": 10,
"selected": false,
"text": "class Animal:\n DOG = 1\n CAT = 2\n\nx = Animal.DOG\n name value from enum import Enum\n\nclass Animal(Enum):\n DOG = 1\n CAT = 2\n\nprint(Animal.DOG)\n# <Animal.DOG: 1>\n\nprint(Animal.DOG.value)\n# 1\n\nprint(Animal.DOG.name)\n# \"DOG\"\n class Animal(Enum):\n DOG, CAT = range(2)\n Enum class Animal(Enum):\n DOG = 1\n CAT = 2\n COW = 0\n\nlist(Animal)\n# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]\n\n[animal.value for animal in Animal]\n# [1, 2, 0]\n\nAnimal.CAT in Animal\n# True\n"
},
{
"answer_id": 36940,
"author": "dguaraglia",
"author_id": 2384,
"author_profile": "https://Stackoverflow.com/users/2384",
"pm_score": 5,
"selected": false,
"text": "months = {\n 'January': 1,\n 'February': 2,\n ...\n}\n months = dict(\n January=1,\n February=2,\n ...\n)\n mymonth = months['January']\n"
},
{
"answer_id": 37000,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 6,
"selected": false,
"text": "enum enum ANIMALS = ['cat', 'dog', 'python']\n\ndef take_for_a_walk(animal):\n assert animal in ANIMALS\n ...\n"
},
{
"answer_id": 37081,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 8,
"selected": false,
"text": "dog, cat, rabbit = range(3)\n dog, cat, rabbit, horse, *_ = range(100)\n"
},
{
"answer_id": 38092,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 6,
"selected": false,
"text": "class Animal:\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return \"<Animal: %s>\" % self\n\nAnimal.DOG = Animal(\"dog\")\nAnimal.CAT = Animal(\"cat\")\n\n>>> x = Animal.DOG\n>>> x\n<Animal: dog>\n>>> x == 1\nFalse\n"
},
{
"answer_id": 38762,
"author": "tuxedo",
"author_id": 3286,
"author_profile": "https://Stackoverflow.com/users/3286",
"pm_score": 4,
"selected": false,
"text": "months = set('January', 'February', ..., 'December')\n if m in months:\n"
},
{
"answer_id": 99347,
"author": "Rick Harris",
"author_id": 18460,
"author_profile": "https://Stackoverflow.com/users/18460",
"pm_score": 3,
"selected": false,
"text": "class Animal: \n TYPE_DOG = 1\n TYPE_CAT = 2\n\n type2str = {\n TYPE_DOG: \"dog\",\n TYPE_CAT: \"cat\"\n }\n\n def __init__(self, type_):\n assert type_ in self.type2str.keys()\n self._type = type_\n\n def __repr__(self):\n return \"<%s type=%s>\" % (\n self.__class__.__name__, self.type2str[self._type].upper())\n"
},
{
"answer_id": 107973,
"author": "user18695",
"author_id": 18695,
"author_profile": "https://Stackoverflow.com/users/18695",
"pm_score": 5,
"selected": false,
"text": "def M_add_class_attribs(attribs):\n def foo(name, bases, dict_):\n for v, k in attribs:\n dict_[k] = v\n return type(name, bases, dict_)\n return foo\n\ndef enum(*names):\n class Foo(object):\n __metaclass__ = M_add_class_attribs(enumerate(names))\n def __setattr__(self, name, value): # this makes it read-only\n raise NotImplementedError\n return Foo()\n Animal = enum('DOG', 'CAT')\nAnimal.DOG # returns 0\nAnimal.CAT # returns 1\nAnimal.DOG = 2 # raises NotImplementedError\n __metaclass__ = M_add_class_attribs(enumerate(names))\n __metaclass__ = M_add_class_attribs((object(), name) for name in names)\n"
},
{
"answer_id": 220537,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 2,
"selected": false,
"text": "import functools\n\nclass EnumValue(object):\n def __init__(self,name,value,type):\n self.__value=value\n self.__name=name\n self.Type=type\n def __str__(self):\n return self.__name\n def __repr__(self):#2.6 only... so change to what ever you need...\n return '{cls}({0!r},{1!r},{2})'.format(self.__name,self.__value,self.Type.__name__,cls=type(self).__name__)\n\n def __hash__(self):\n return hash(self.__value)\n def __nonzero__(self):\n return bool(self.__value)\n def __cmp__(self,other):\n if isinstance(other,EnumValue):\n return cmp(self.__value,other.__value)\n else:\n return cmp(self.__value,other)#hopefully their the same type... but who cares?\n def __or__(self,other):\n if other is None:\n return self\n elif type(self) is not type(other):\n raise TypeError()\n return EnumValue('{0.Name} | {1.Name}'.format(self,other),self.Value|other.Value,self.Type)\n def __and__(self,other):\n if other is None:\n return self\n elif type(self) is not type(other):\n raise TypeError()\n return EnumValue('{0.Name} & {1.Name}'.format(self,other),self.Value&other.Value,self.Type)\n def __contains__(self,other):\n if self.Value==other.Value:\n return True\n return bool(self&other)\n def __invert__(self):\n enumerables=self.Type.__enumerables__\n return functools.reduce(EnumValue.__or__,(enum for enum in enumerables.itervalues() if enum not in self))\n\n @property\n def Name(self):\n return self.__name\n\n @property\n def Value(self):\n return self.__value\n\nclass EnumMeta(type):\n @staticmethod\n def __addToReverseLookup(rev,value,newKeys,nextIter,force=True):\n if value in rev:\n forced,items=rev.get(value,(force,()) )\n if forced and force: #value was forced, so just append\n rev[value]=(True,items+newKeys)\n elif not forced:#move it to a new spot\n next=nextIter.next()\n EnumMeta.__addToReverseLookup(rev,next,items,nextIter,False)\n rev[value]=(force,newKeys)\n else: #not forcing this value\n next = nextIter.next()\n EnumMeta.__addToReverseLookup(rev,next,newKeys,nextIter,False)\n rev[value]=(force,newKeys)\n else:#set it and forget it\n rev[value]=(force,newKeys)\n return value\n\n def __init__(cls,name,bases,atts):\n classVars=vars(cls)\n enums = classVars.get('__enumerables__',None)\n nextIter = getattr(cls,'__nextitr__',itertools.count)()\n reverseLookup={}\n values={}\n\n if enums is not None:\n #build reverse lookup\n for item in enums:\n if isinstance(item,(tuple,list)):\n items=list(item)\n value=items.pop()\n EnumMeta.__addToReverseLookup(reverseLookup,value,tuple(map(str,items)),nextIter)\n else:\n value=nextIter.next()\n value=EnumMeta.__addToReverseLookup(reverseLookup,value,(str(item),),nextIter,False)#add it to the reverse lookup, but don't force it to that value\n\n #build values and clean up reverse lookup\n for value,fkeys in reverseLookup.iteritems():\n f,keys=fkeys\n for key in keys:\n enum=EnumValue(key,value,cls)\n setattr(cls,key,enum)\n values[key]=enum\n reverseLookup[value]=tuple(val for val in values.itervalues() if val.Value == value)\n setattr(cls,'__reverseLookup__',reverseLookup)\n setattr(cls,'__enumerables__',values)\n setattr(cls,'_Max',max([key for key in reverseLookup] or [0]))\n return super(EnumMeta,cls).__init__(name,bases,atts)\n\n def __iter__(cls):\n for enum in cls.__enumerables__.itervalues():\n yield enum\n def GetEnumByName(cls,name):\n return cls.__enumerables__.get(name,None)\n def GetEnumByValue(cls,value):\n return cls.__reverseLookup__.get(value,(None,))[0]\n\nclass Enum(object):\n __metaclass__=EnumMeta\n __enumerables__=None\n\nclass FlagEnum(Enum):\n @staticmethod\n def __nextitr__():\n yield 0\n for val in itertools.count():\n yield 2**val\n\ndef enum(name,*args):\n return EnumMeta(name,(Enum,),dict(__enumerables__=args))\n class Air(FlagEnum):\n __enumerables__=('None','Oxygen','Nitrogen','Hydrogen')\n\nclass Mammals(Enum):\n __enumerables__=('Bat','Whale',('Dog','Puppy',1),'Cat')\nBool = enum('Bool','Yes',('No',0))\n"
},
{
"answer_id": 505457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "class Enum(object):\n def __init__(self, names, separator=None):\n self.names = names.split(separator)\n for value, name in enumerate(self.names):\n setattr(self, name.upper(), value)\n def tuples(self):\n return tuple(enumerate(self.names))\n >>> state = Enum('draft published retracted')\n>>> state.DRAFT\n0\n>>> state.RETRACTED\n2\n>>> state.FOO\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'Enum' object has no attribute 'FOO'\n>>> state.tuples()\n((0, 'draft'), (1, 'published'), (2, 'retracted'))\n"
},
{
"answer_id": 1529241,
"author": "Ashwin Nanjappa",
"author_id": 1630,
"author_profile": "https://Stackoverflow.com/users/1630",
"pm_score": 7,
"selected": false,
"text": "enum enum Pen, Pencil, Eraser = range(0, 3)\n range Pen, Pencil, Eraser = range(9, 12)\n class Stationery:\n Pen, Pencil, Eraser = range(0, 3)\n stype = Stationery.Pen\n"
},
{
"answer_id": 1587932,
"author": "Natim",
"author_id": 186202,
"author_profile": "https://Stackoverflow.com/users/186202",
"pm_score": 2,
"selected": false,
"text": "TYPE = {'EAN13': u'EAN-13',\n 'CODE39': u'Code 39',\n 'CODE128': u'Code 128',\n 'i25': u'Interleaved 2 of 5',}\n\n>>> TYPE.items()\n[('EAN13', u'EAN-13'), ('i25', u'Interleaved 2 of 5'), ('CODE39', u'Code 39'), ('CODE128', u'Code 128')]\n>>> TYPE.keys()\n['EAN13', 'i25', 'CODE39', 'CODE128']\n>>> TYPE.values()\n[u'EAN-13', u'Interleaved 2 of 5', u'Code 39', u'Code 128']\n"
},
{
"answer_id": 1695250,
"author": "Alec Thomas",
"author_id": 7980,
"author_profile": "https://Stackoverflow.com/users/7980",
"pm_score": 13,
"selected": true,
"text": "enum34 __order__ enum34 $ pip install enum34 aenum $ pip install aenum enum from enum import Enum # for enum34, or the stdlib version\n# from aenum import Enum # for the aenum version\nAnimal = Enum('Animal', 'ant bee cat dog')\n\nAnimal.ant # returns <Animal.ant: 1>\nAnimal['ant'] # returns <Animal.ant: 1> (string lookup)\nAnimal.ant.name # returns 'ant' (inverse lookup)\n class Animal(Enum):\n ant = 1\n bee = 2\n cat = 3\n dog = 4\n def enum(**enums):\n return type('Enum', (), enums)\n >>> Numbers = enum(ONE=1, TWO=2, THREE='three')\n>>> Numbers.ONE\n1\n>>> Numbers.TWO\n2\n>>> Numbers.THREE\n'three'\n def enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)\n >>> Numbers = enum('ZERO', 'ONE', 'TWO')\n>>> Numbers.ZERO\n0\n>>> Numbers.ONE\n1\n def enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n reverse = dict((value, key) for key, value in enums.iteritems())\n enums['reverse_mapping'] = reverse\n return type('Enum', (), enums)\n KeyError >>> Numbers.reverse_mapping['three']\n'THREE'\n typing.Literal from typing import Literal #python >=3.8\nfrom typing_extensions import Literal #python 2.7, 3.4-3.7\n\n\nAnimal = Literal['ant', 'bee', 'cat', 'dog']\n\ndef hello_animal(animal: Animal):\n print(f\"hello {animal}\")\n\nhello_animal('rock') # error\nhello_animal('bee') # passes\n\n"
},
{
"answer_id": 1751697,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 2,
"selected": false,
"text": "# an internal class, not intended to be seen by client code\nclass _Constants(object):\n pass\n\n\n# an enumeration of constants for operator associativity\nopAssoc = _Constants()\nopAssoc.LEFT = object()\nopAssoc.RIGHT = object()\n import opAssoc from pyparsing\n"
},
{
"answer_id": 1753340,
"author": "steveha",
"author_id": 166949,
"author_profile": "https://Stackoverflow.com/users/166949",
"pm_score": 4,
"selected": false,
"text": "def cmp(a,b):\n if a < b: return -1\n if b < a: return 1\n return 0\n\n\ndef Enum(*names):\n ##assert names, \"Empty enums are not supported\" # <- Don't like empty enums? Uncomment!\n\n class EnumClass(object):\n __slots__ = names\n def __iter__(self): return iter(constants)\n def __len__(self): return len(constants)\n def __getitem__(self, i): return constants[i]\n def __repr__(self): return 'Enum' + str(names)\n def __str__(self): return 'enum ' + str(constants)\n\n class EnumValue(object):\n __slots__ = ('__value')\n def __init__(self, value): self.__value = value\n Value = property(lambda self: self.__value)\n EnumType = property(lambda self: EnumType)\n def __hash__(self): return hash(self.__value)\n def __cmp__(self, other):\n # C fans might want to remove the following assertion\n # to make all enums comparable by ordinal value {;))\n assert self.EnumType is other.EnumType, \"Only values from the same enum are comparable\"\n return cmp(self.__value, other.__value)\n def __lt__(self, other): return self.__cmp__(other) < 0\n def __eq__(self, other): return self.__cmp__(other) == 0\n def __invert__(self): return constants[maximum - self.__value]\n def __nonzero__(self): return bool(self.__value)\n def __repr__(self): return str(names[self.__value])\n\n maximum = len(names) - 1\n constants = [None] * len(names)\n for i, each in enumerate(names):\n val = EnumValue(i)\n setattr(EnumClass, each, val)\n constants[i] = val\n constants = tuple(constants)\n EnumType = EnumClass()\n return EnumType\n\n\nif __name__ == '__main__':\n print( '\\n*** Enum Demo ***')\n print( '--- Days of week ---')\n Days = Enum('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su')\n print( Days)\n print( Days.Mo)\n print( Days.Fr)\n print( Days.Mo < Days.Fr)\n print( list(Days))\n for each in Days:\n print( 'Day:', each)\n print( '--- Yes/No ---')\n Confirmation = Enum('No', 'Yes')\n answer = Confirmation.No\n print( 'Your answer is not', ~answer)\n"
},
{
"answer_id": 2182437,
"author": "shahjapan",
"author_id": 144408,
"author_profile": "https://Stackoverflow.com/users/144408",
"pm_score": 8,
"selected": false,
"text": "class Enum(set):\n def __getattr__(self, name):\n if name in self:\n return name\n raise AttributeError\n Animals = Enum([\"DOG\", \"CAT\", \"HORSE\"])\n\nprint(Animals.DOG)\n"
},
{
"answer_id": 2389722,
"author": "iobaixas",
"author_id": 287423,
"author_profile": "https://Stackoverflow.com/users/287423",
"pm_score": 2,
"selected": false,
"text": "class Enum:\n #'''\n #Java like implementation for enums.\n #\n #Usage:\n #class Tool(Enum): name = 'Tool'\n #Tool.DRILL = Tool.register('drill')\n #Tool.HAMMER = Tool.register('hammer')\n #Tool.WRENCH = Tool.register('wrench')\n #'''\n\n name = 'Enum' # Enum name\n _reg = dict([]) # Enum registered values\n\n @classmethod\n def register(cls, value):\n #'''\n #Registers a new value in this enum.\n #\n #@param value: New enum value.\n #\n #@return: New value wrapper instance.\n #'''\n inst = cls(value)\n cls._reg[value] = inst\n return inst\n\n @classmethod\n def parse(cls, value):\n #'''\n #Parses a value, returning the enum instance.\n #\n #@param value: Enum value.\n #\n #@return: Value corresp instance. \n #'''\n return cls._reg.get(value) \n\n def __init__(self, value):\n #'''\n #Constructor (only for internal use).\n #'''\n self.value = value\n\n def __str__(self):\n #'''\n #str() overload.\n #'''\n return self.value\n\n def __repr__(self):\n #'''\n #repr() overload.\n #'''\n return \"<\" + self.name + \": \" + self.value + \">\"\n"
},
{
"answer_id": 2458660,
"author": "pythonic metaphor",
"author_id": 189456,
"author_profile": "https://Stackoverflow.com/users/189456",
"pm_score": 3,
"selected": false,
"text": ">>> from enum import Enum\n>>> Colors = Enum('red', 'blue', 'green')\n>>> shirt_color = Colors.green\n>>> shirt_color = Colors[2]\n>>> shirt_color > Colors.red\nTrue\n>>> shirt_color.index\n2\n>>> str(shirt_color)\n'green'\n"
},
{
"answer_id": 2785738,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 2,
"selected": false,
"text": "class Enumerator(object):\n def __init__(self, name):\n self.name = name\n\n def __eq__(self, other):\n if self.name == other:\n return True\n return self is other\n\n def __ne__(self, other):\n if self.name != other:\n return False\n return self is other\n\n def __repr__(self):\n return 'Enumerator({0})'.format(self.name)\n\n def __str__(self):\n return self.name\n\nclass Enum(object):\n def __init__(self, *enumerators):\n for e in enumerators:\n setattr(self, e, Enumerator(e))\n def __getitem__(self, key):\n return getattr(self, key)\n class Cow(object):\n State = Enum(\n 'standing',\n 'walking',\n 'eating',\n 'mooing',\n 'sleeping',\n 'dead',\n 'dying'\n )\n state = State.standing\n\nIn [1]: from enum import Enum\n\nIn [2]: c = Cow()\n\nIn [3]: c2 = Cow()\n\nIn [4]: c.state, c2.state\nOut[4]: (Enumerator(standing), Enumerator(standing))\n\nIn [5]: c.state == c2.state\nOut[5]: True\n\nIn [6]: c.State.mooing\nOut[6]: Enumerator(mooing)\n\nIn [7]: c.State['mooing']\nOut[7]: Enumerator(mooing)\n\nIn [8]: c.state = Cow.State.dead\n\nIn [9]: c.state == c2.state\nOut[9]: False\n\nIn [10]: c.state == Cow.State.dead\nOut[10]: True\n\nIn [11]: c.state == 'dead'\nOut[11]: True\n\nIn [12]: c.state == Cow.State['dead']\nOut[11]: True\n"
},
{
"answer_id": 2913233,
"author": "Denis Ryzhkov",
"author_id": 350937,
"author_profile": "https://Stackoverflow.com/users/350937",
"pm_score": 1,
"selected": false,
"text": "def enum( *names ):\n\n '''\n Makes enum.\n Usage:\n E = enum( 'YOUR', 'KEYS', 'HERE' )\n print( E.HERE )\n '''\n\n class Enum():\n pass\n for index, name in enumerate( names ):\n setattr( Enum, name, index )\n return Enum\n"
},
{
"answer_id": 2976036,
"author": "daegga",
"author_id": 358665,
"author_profile": "https://Stackoverflow.com/users/358665",
"pm_score": 2,
"selected": false,
"text": "def enum(clsdef):\n class Enum(object):\n __slots__=tuple([var for var in clsdef.__dict__ if isinstance((getattr(clsdef, var)), tuple) and not var.startswith('__')])\n\n def __new__(cls, *args, **kwargs):\n if not '_the_instance' in cls.__dict__:\n cls._the_instance = object.__new__(cls, *args, **kwargs)\n return cls._the_instance\n\n def __init__(self):\n clsdef.values=lambda cls, e=Enum: e.values()\n clsdef.valueOf=lambda cls, n, e=self: e.valueOf(n)\n for ordinal, key in enumerate(self.__class__.__slots__):\n args=getattr(clsdef, key)\n instance=clsdef(*args)\n instance._name=key\n instance._ordinal=ordinal\n setattr(self, key, instance)\n\n @classmethod\n def values(cls):\n if not hasattr(cls, '_values'):\n cls._values=[getattr(cls, name) for name in cls.__slots__]\n return cls._values\n\n def valueOf(self, name):\n return getattr(self, name)\n\n def __repr__(self):\n return ''.join(['<class Enum (', clsdef.__name__, ') at ', str(hex(id(self))), '>'])\n\n return Enum()\n i=2\n@enum\nclass Test(object):\n A=(\"a\",1)\n B=(\"b\",)\n C=(\"c\",2)\n D=tuple()\n E=(\"e\",3)\n\n while True:\n try:\n F, G, H, I, J, K, L, M, N, O=[tuple() for _ in range(i)]\n break;\n except ValueError:\n i+=1\n\n def __init__(self, name=\"default\", aparam=0):\n self.name=name\n self.avalue=aparam\n"
},
{
"answer_id": 4092436,
"author": "royal",
"author_id": 133934,
"author_profile": "https://Stackoverflow.com/users/133934",
"pm_score": 6,
"selected": false,
"text": "class Animal(object):\n values = ['Horse','Dog','Cat']\n\n class __metaclass__(type):\n def __getattr__(self, name):\n return self.values.index(name)\n >>> Animal.Cat\n2\n def name_of(self, i):\n return self.values[i]\n"
},
{
"answer_id": 4300343,
"author": "mbac32768",
"author_id": 18446,
"author_profile": "https://Stackoverflow.com/users/18446",
"pm_score": 5,
"selected": false,
"text": "class Animal:\n class Dog: pass\n class Cat: pass\n\nx = Animal.Dog\n class SymbolClass(type):\n def __repr__(self): return self.__qualname__\n def __str__(self): return self.__name__\n\nclass Symbol(metaclass=SymbolClass): pass\n\n\nclass Animal:\n class Dog(Symbol): pass\n class Cat(Symbol): pass\n >>> mydict = {Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n>>> mydict\n{Animal.Dog: 'Wan Wan', Animal.Cat: 'Nyaa'}\n"
},
{
"answer_id": 6347576,
"author": "Roy Hyunjin Han",
"author_id": 192092,
"author_profile": "https://Stackoverflow.com/users/192092",
"pm_score": 2,
"selected": false,
"text": "def enum(*args, **kwargs):\n return type('Enum', (), dict((y, x) for x, y in enumerate(args), **kwargs)) \n\nx = enum('POOH', 'TIGGER', 'EEYORE', 'ROO', 'PIGLET', 'RABBIT', 'OWL')\nassert x.POOH == 0\nassert x.TIGGER == 1\n"
},
{
"answer_id": 6971002,
"author": "agf",
"author_id": 500584,
"author_profile": "https://Stackoverflow.com/users/500584",
"pm_score": 5,
"selected": false,
"text": "namedtuple from collections import namedtuple\n\ndef enum(*keys):\n return namedtuple('Enum', keys)(*keys)\n\nMyEnum = enum('FOO', 'BAR', 'BAZ')\n # With sequential number values\ndef enum(*keys):\n return namedtuple('Enum', keys)(*range(len(keys)))\n\n# From a dict / keyword args\ndef enum(**kwargs):\n return namedtuple('Enum', kwargs.keys())(*kwargs.values())\n\n\n\n\n# Example for dictionary param:\nvalues = {\"Salad\": 20, \"Carrot\": 99, \"Tomato\": \"No i'm not\"} \nVegetables= enum(**values)\n\n# >>> print(Vegetables.Tomato) 'No i'm not'\n\n\n# Example for keyworded params: \nFruits = enum(Apple=\"Steve Jobs\", Peach=1, Banana=2)\n\n# >>> print(Fruits.Apple) 'Steve Jobs'\n set 'FOO' in MyEnum\nother = MyEnum.FOO\nassert other == MyEnum.FOO\n MyEnum.FOO < MyEnum.BAR\n"
},
{
"answer_id": 7458935,
"author": "Michael Truog",
"author_id": 950809,
"author_profile": "https://Stackoverflow.com/users/950809",
"pm_score": 2,
"selected": false,
"text": "import new\n\ndef create(class_name, names):\n return new.classobj(\n class_name, (object,), dict((y, x) for x, y in enumerate(names))\n )\n import enumeration\n\nColors = enumeration.create('Colors', (\n 'red',\n 'orange',\n 'yellow',\n 'green',\n 'blue',\n 'violet',\n))\n"
},
{
"answer_id": 8598742,
"author": "SingleNegationElimination",
"author_id": 65696,
"author_profile": "https://Stackoverflow.com/users/65696",
"pm_score": 4,
"selected": false,
"text": "repr >>> class Enum(int):\n... def __new__(cls, value):\n... if isinstance(value, str):\n... return getattr(cls, value)\n... elif isinstance(value, int):\n... return cls.__index[value]\n... def __str__(self): return self.__name\n... def __repr__(self): return \"%s.%s\" % (type(self).__name__, self.__name)\n... class __metaclass__(type):\n... def __new__(mcls, name, bases, attrs):\n... attrs['__slots__'] = ['_Enum__name']\n... cls = type.__new__(mcls, name, bases, attrs)\n... cls._Enum__index = _index = {}\n... for base in reversed(bases):\n... if hasattr(base, '_Enum__index'):\n... _index.update(base._Enum__index)\n... # create all of the instances of the new class\n... for attr in attrs.keys():\n... value = attrs[attr]\n... if isinstance(value, int):\n... evalue = int.__new__(cls, value)\n... evalue._Enum__name = attr\n... _index[value] = evalue\n... setattr(cls, attr, evalue)\n... return cls\n... \n >>> class Citrus(Enum):\n... Lemon = 1\n... Lime = 2\n... \n>>> Citrus.Lemon\nCitrus.Lemon\n>>> \n>>> Citrus(1)\nCitrus.Lemon\n>>> Citrus(5)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 6, in __new__\nKeyError: 5\n>>> class Fruit(Citrus):\n... Apple = 3\n... Banana = 4\n... \n>>> Fruit.Apple\nFruit.Apple\n>>> Fruit.Lemon\nCitrus.Lemon\n>>> Fruit(1)\nCitrus.Lemon\n>>> Fruit(3)\nFruit.Apple\n>>> \"%d %s %r\" % ((Fruit.Apple,)*3)\n'3 Apple Fruit.Apple'\n>>> Fruit(1) is Citrus.Lemon\nTrue\n str() int() repr() is"
},
{
"answer_id": 8905914,
"author": "bj0",
"author_id": 618895,
"author_profile": "https://Stackoverflow.com/users/618895",
"pm_score": 4,
"selected": false,
"text": "def enum(**enums):\n '''simple constant \"enums\"'''\n return type('Enum', (object,), enums)\n def enum_base(t, **enums):\n '''enums with a base class'''\n T = type('Enum', (t,), {})\n for key,val in enums.items():\n setattr(T, key, T(val))\n\n return T\n >>> Numbers = enum_base(int, ONE=1, TWO=2, THREE=3)\n>>> Numbers.ONE\n1\n>>> x = Numbers.TWO\n>>> 10 + x\n12\n>>> type(Numbers)\n<type 'type'>\n>>> type(Numbers.ONE)\n<class 'Enum'>\n>>> isinstance(x, Numbers)\nTrue\n def enum_repr(t, **enums):\n '''enums with a base class and repr() output'''\n class Enum(t):\n def __repr__(self):\n return '<enum {0} of type Enum({1})>'.format(self._name, t.__name__)\n\n for key,val in enums.items():\n i = Enum(val)\n i._name = key\n setattr(Enum, key, i)\n\n return Enum\n\n\n\n>>> Numbers = enum_repr(int, ONE=1, TWO=2, THREE=3)\n>>> repr(Numbers.ONE)\n'<enum ONE of type Enum(int)>'\n>>> str(Numbers.ONE)\n'1'\n"
},
{
"answer_id": 9201329,
"author": "Zoetic",
"author_id": 653048,
"author_profile": "https://Stackoverflow.com/users/653048",
"pm_score": 6,
"selected": false,
"text": "class Enum(tuple): __getattr__ = tuple.index\n >>> State = Enum(['Unclaimed', 'Claimed'])\n>>> State.Claimed\n1\n>>> State[1]\n'Claimed'\n>>> State\n('Unclaimed', 'Claimed')\n>>> range(len(State))\n[0, 1]\n>>> [(k, State[k]) for k in range(len(State))]\n[(0, 'Unclaimed'), (1, 'Claimed')]\n>>> [(k, getattr(State, k)) for k in State]\n[('Unclaimed', 0), ('Claimed', 1)]\n"
},
{
"answer_id": 10004274,
"author": "jianpx",
"author_id": 544251,
"author_profile": "https://Stackoverflow.com/users/544251",
"pm_score": 2,
"selected": false,
"text": "class ConstMeta(type):\n '''\n Metaclass for some class that store constants\n '''\n def __init__(cls, name, bases, dct):\n '''\n init class instance\n '''\n def static_attrs():\n '''\n @rtype: (static_attrs, static_val_set)\n @return: Static attributes in dict format and static value set\n '''\n import types\n attrs = {}\n val_set = set()\n #Maybe more\n filter_names = set(['__doc__', '__init__', '__metaclass__', '__module__', '__main__'])\n for key, value in dct.iteritems():\n if type(value) != types.FunctionType and key not in filter_names:\n if len(value) != 2:\n raise NotImplementedError('not support for values that is not 2 elements!')\n #Check value[0] duplication.\n if value[0] not in val_set:\n val_set.add(value[0])\n else:\n raise KeyError(\"%s 's key: %s is duplicated!\" % (dict([(key, value)]), value[0]))\n attrs[key] = value\n return attrs, val_set\n\n attrs, val_set = static_attrs()\n #Set STATIC_ATTRS to class instance so that can reuse\n setattr(cls, 'STATIC_ATTRS', attrs)\n setattr(cls, 'static_val_set', val_set)\n super(ConstMeta, cls).__init__(name, bases, dct)\n\n def __getattribute__(cls, name):\n '''\n Rewrite the special function so as to get correct attribute value\n '''\n static_attrs = object.__getattribute__(cls, 'STATIC_ATTRS')\n if name in static_attrs:\n return static_attrs[name][0]\n return object.__getattribute__(cls, name)\n\n def static_values(cls):\n '''\n Put values in static attribute into a list, use the function to validate value.\n @return: Set of values\n '''\n return cls.static_val_set\n\n def __getitem__(cls, key):\n '''\n Rewrite to make syntax SomeConstClass[key] works, and return desc string of related static value.\n @return: Desc string of related static value\n '''\n for k, v in cls.STATIC_ATTRS.iteritems():\n if v[0] == key:\n return v[1]\n raise KeyError('Key: %s does not exists in %s !' % (str(key), repr(cls)))\n\n\nclass Const(object):\n '''\n Base class for constant class.\n\n @usage:\n\n Definition: (must inherit from Const class!\n >>> class SomeConst(Const):\n >>> STATUS_NAME_1 = (1, 'desc for the status1')\n >>> STATUS_NAME_2 = (2, 'desc for the status2')\n\n Invoke(base upper SomeConst class):\n 1) SomeConst.STATUS_NAME_1 returns 1\n 2) SomeConst[1] returns 'desc for the status1'\n 3) SomeConst.STATIC_ATTRS returns {'STATUS_NAME_1': (1, 'desc for the status1'), 'STATUS_NAME_2': (2, 'desc for the status2')}\n 4) SomeConst.static_values() returns set([1, 2])\n\n Attention:\n SomeCosnt's value 1, 2 can not be duplicated!\n If WrongConst is like this, it will raise KeyError:\n class WrongConst(Const):\n STATUS_NAME_1 = (1, 'desc for the status1')\n STATUS_NAME_2 = (1, 'desc for the status2')\n '''\n __metaclass__ = ConstMeta\n##################################################################\n#Const Base Class ends\n##################################################################\n\n\ndef main():\n class STATUS(Const):\n ERROR = (-3, '??')\n OK = (0, '??')\n\n print STATUS.ERROR\n print STATUS.static_values()\n print STATUS.STATIC_ATTRS\n\n #Usage sample:\n user_input = 1\n #Validate input:\n print user_input in STATUS.static_values()\n #Template render like:\n print '<select>'\n for key, value in STATUS.STATIC_ATTRS.items():\n print '<option value=\"%s\">%s</option>' % (value[0], value[1])\n print '</select>'\n\n\nif __name__ == '__main__':\n main()\n"
},
{
"answer_id": 11147900,
"author": "Oxdeadbeef",
"author_id": 545299,
"author_profile": "https://Stackoverflow.com/users/545299",
"pm_score": 2,
"selected": false,
"text": "class EnumBase(type):\n def __init__(self, name, base, fields):\n super(EnumBase, self).__init__(name, base, fields)\n self.__mapping = dict((v, k) for k, v in fields.iteritems())\n def __getitem__(self, val):\n return self.__mapping[val]\n\ndef enum(*seq, **named):\n enums = dict(zip(seq, range(len(seq))), **named)\n return EnumBase('Enum', (), enums)\n\nNumbers = enum(ONE=1, TWO=2, THREE='three')\nprint Numbers.TWO\nprint Numbers[Numbers.ONE]\nprint Numbers[2]\nprint Numbers['three']\n"
},
{
"answer_id": 13474078,
"author": "Jah",
"author_id": 1207615,
"author_profile": "https://Stackoverflow.com/users/1207615",
"pm_score": 2,
"selected": false,
"text": ">>> packet_types = ['INIT', 'FINI', 'RECV', 'SEND']\n>>> packet_types.index('INIT')\n0\n>>> packet_types.index('FINI')\n1\n>>>\n"
},
{
"answer_id": 14628126,
"author": "Noctis Skytower",
"author_id": 216356,
"author_profile": "https://Stackoverflow.com/users/216356",
"pm_score": 2,
"selected": false,
"text": "def enum(names):\n \"Create a simple enumeration having similarities to C.\"\n return type('enum', (), dict(map(reversed, enumerate(\n names.replace(',', ' ').split())), __slots__=()))()\n grade = enum('A B C D F')\nstate = enum('awake, sleeping, dead')\n >>> grade.A\n0\n>>> grade.B\n1\n>>> grade.F == 4\nTrue\n>>> state.dead == 2\nTrue\n"
},
{
"answer_id": 15886819,
"author": "FDS",
"author_id": 823602,
"author_profile": "https://Stackoverflow.com/users/823602",
"pm_score": 2,
"selected": false,
"text": "def Enum(*sequential, **named):\n \"\"\"Generate a new enum type. Usage example:\n\n ErrorClass = Enum('STOP','GO')\n print ErrorClass.find_name(ErrorClass.STOP)\n = \"STOP\"\n print ErrorClass.find_val(\"STOP\")\n = 0\n ErrorClass.FOO # Raises AttributeError\n \"\"\"\n enums = { v:k for k,v in enumerate(sequential) } if not named else named\n\n @classmethod\n def find_name(cls, val):\n result = [ k for k,v in cls.__dict__.iteritems() if v == val ]\n if not len(result):\n raise ValueError(\"Value %s not found in Enum\" % val)\n return result[0]\n\n @classmethod\n def find_val(cls, n):\n return getattr(cls, n)\n\n enums['find_val'] = find_val\n enums['find_name'] = find_name\n return type('Enum', (), enums)\n"
},
{
"answer_id": 16095707,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 3,
"selected": false,
"text": "flufl.enum"
},
{
"answer_id": 16486444,
"author": "Danilo Bargen",
"author_id": 284318,
"author_profile": "https://Stackoverflow.com/users/284318",
"pm_score": 5,
"selected": false,
"text": ">>> from enum import Enum\n>>> class Color(Enum):\n... red = 1\n... green = 2\n... blue = 3\n >>> print(Color.red)\nColor.red\n>>> print(repr(Color.red))\n<Color.red: 1>\n >>> for color in Color:\n... print(color)\n...\nColor.red\nColor.green\nColor.blue\n >>> Color(1)\nColor.red\n>>> Color['blue']\nColor.blue\n"
},
{
"answer_id": 16486681,
"author": "Riaz Rizvi",
"author_id": 213307,
"author_profile": "https://Stackoverflow.com/users/213307",
"pm_score": 4,
"selected": false,
"text": ">>> from enum import Enum\n>>> class Colors(Enum):\n... red = 1\n... green = 2\n... blue = 3\n>>> for color in Colors: print color\nColors.red\nColors.green\nColors.blue\n"
},
{
"answer_id": 17201727,
"author": "Chris Johnson",
"author_id": 763269,
"author_profile": "https://Stackoverflow.com/users/763269",
"pm_score": 3,
"selected": false,
"text": "def enum(*names):\n \"\"\"\nSYNOPSIS\n Well-behaved enumerated type, easier than creating custom classes\n\nDESCRIPTION\n Create a custom type that implements an enumeration. Similar in concept\n to a C enum but with some additional capabilities and protections. See\n http://code.activestate.com/recipes/413486-first-class-enums-in-python/.\n\nPARAMETERS\n names Ordered list of names. The order in which names are given\n will be the sort order in the enum type. Duplicate names\n are not allowed. Unicode names are mapped to ASCII.\n\nRETURNS\n Object of type enum, with the input names and the enumerated values.\n\nEXAMPLES\n >>> letters = enum('a','e','i','o','u','b','c','y','z')\n >>> letters.a < letters.e\n True\n\n ## index by property\n >>> letters.a\n a\n\n ## index by position\n >>> letters[0]\n a\n\n ## index by name, helpful for bridging string inputs to enum\n >>> letters['a']\n a\n\n ## sorting by order in the enum() create, not character value\n >>> letters.u < letters.b\n True\n\n ## normal slicing operations available\n >>> letters[-1]\n z\n\n ## error since there are not 100 items in enum\n >>> letters[99]\n Traceback (most recent call last):\n ...\n IndexError: tuple index out of range\n\n ## error since name does not exist in enum\n >>> letters['ggg']\n Traceback (most recent call last):\n ...\n ValueError: tuple.index(x): x not in tuple\n\n ## enums must be named using valid Python identifiers\n >>> numbers = enum(1,2,3,4)\n Traceback (most recent call last):\n ...\n AssertionError: Enum values must be string or unicode\n\n >>> a = enum('-a','-b')\n Traceback (most recent call last):\n ...\n TypeError: Error when calling the metaclass bases\n __slots__ must be identifiers\n\n ## create another enum\n >>> tags = enum('a','b','c')\n >>> tags.a\n a\n >>> letters.a\n a\n\n ## can't compare values from different enums\n >>> letters.a == tags.a\n Traceback (most recent call last):\n ...\n AssertionError: Only values from the same enum are comparable\n\n >>> letters.a < tags.a\n Traceback (most recent call last):\n ...\n AssertionError: Only values from the same enum are comparable\n\n ## can't update enum after create\n >>> letters.a = 'x'\n Traceback (most recent call last):\n ...\n AttributeError: 'EnumClass' object attribute 'a' is read-only\n\n ## can't update enum after create\n >>> del letters.u\n Traceback (most recent call last):\n ...\n AttributeError: 'EnumClass' object attribute 'u' is read-only\n\n ## can't have non-unique enum values\n >>> x = enum('a','b','c','a')\n Traceback (most recent call last):\n ...\n AssertionError: Enums must not repeat values\n\n ## can't have zero enum values\n >>> x = enum()\n Traceback (most recent call last):\n ...\n AssertionError: Empty enums are not supported\n\n ## can't have enum values that look like special function names\n ## since these could collide and lead to non-obvious errors\n >>> x = enum('a','b','c','__cmp__')\n Traceback (most recent call last):\n ...\n AssertionError: Enum values beginning with __ are not supported\n\nLIMITATIONS\n Enum values of unicode type are not preserved, mapped to ASCII instead.\n\n \"\"\"\n ## must have at least one enum value\n assert names, 'Empty enums are not supported'\n ## enum values must be strings\n assert len([i for i in names if not isinstance(i, types.StringTypes) and not \\\n isinstance(i, unicode)]) == 0, 'Enum values must be string or unicode'\n ## enum values must not collide with special function names\n assert len([i for i in names if i.startswith(\"__\")]) == 0,\\\n 'Enum values beginning with __ are not supported'\n ## each enum value must be unique from all others\n assert names == uniquify(names), 'Enums must not repeat values'\n\n class EnumClass(object):\n \"\"\" See parent function for explanation \"\"\"\n\n __slots__ = names\n\n def __iter__(self):\n return iter(constants)\n\n def __len__(self):\n return len(constants)\n\n def __getitem__(self, i):\n ## this makes xx['name'] possible\n if isinstance(i, types.StringTypes):\n i = names.index(i)\n ## handles the more normal xx[0]\n return constants[i]\n\n def __repr__(self):\n return 'enum' + str(names)\n\n def __str__(self):\n return 'enum ' + str(constants)\n\n def index(self, i):\n return names.index(i)\n\n class EnumValue(object):\n \"\"\" See parent function for explanation \"\"\"\n\n __slots__ = ('__value')\n\n def __init__(self, value):\n self.__value = value\n\n value = property(lambda self: self.__value)\n\n enumtype = property(lambda self: enumtype)\n\n def __hash__(self):\n return hash(self.__value)\n\n def __cmp__(self, other):\n assert self.enumtype is other.enumtype, 'Only values from the same enum are comparable'\n return cmp(self.value, other.value)\n\n def __invert__(self):\n return constants[maximum - self.value]\n\n def __nonzero__(self):\n ## return bool(self.value)\n ## Original code led to bool(x[0])==False, not correct\n return True\n\n def __repr__(self):\n return str(names[self.value])\n\n maximum = len(names) - 1\n constants = [None] * len(names)\n for i, each in enumerate(names):\n val = EnumValue(i)\n setattr(EnumClass, each, val)\n constants[i] = val\n constants = tuple(constants)\n enumtype = EnumClass()\n return enumtype\n"
},
{
"answer_id": 18627613,
"author": "David",
"author_id": 926217,
"author_profile": "https://Stackoverflow.com/users/926217",
"pm_score": 2,
"selected": false,
"text": "class EnumTypeError(TypeError):\n pass\n\nclass Enum(object):\n \"\"\"\n Minics enum type from different languages\n Usage:\n Letters = Enum(list('abc'))\n a = Letters.a\n print(a in Letters) # True\n print(54 in Letters) # False\n \"\"\"\n def __init__(self, enums):\n if isinstance(enums, dict):\n self.__dict__.update(enums)\n elif isinstance(enums, list) or isinstance(enums, tuple):\n self.__dict__.update(**dict((v,k) for k,v in enumerate(enums)))\n else:\n raise EnumTypeError\n\n def __contains__(self, key):\n return key in self.__dict__.values()\n\n def __len__(self):\n return len(self.__dict__.values())\n\n\nif __name__ == '__main__':\n print('Using a dictionary to create Enum:')\n Letters = Enum(dict((v,k) for k,v in enumerate(list('abcde'))))\n a = Letters.a\n print('\\tIs a in e?', a in Letters)\n print('\\tIs 54 in e?', 54 in Letters)\n print('\\tLength of Letters enum:', len(Letters))\n\n print('\\nUsing a list to create Enum:')\n Letters = Enum(list('abcde'))\n a = Letters.a\n print('\\tIs a in e?', a in Letters)\n print('\\tIs 54 in e?', 54 in Letters)\n print('\\tLength of Letters enum:', len(Letters))\n\n try:\n # make sure we raise an exception if we pass an invalid arg\n Failure = Enum('This is a Failure')\n print('Failure')\n except EnumTypeError:\n print('Success!')\n Using a dictionary to create Enum:\n Is a in e? True\n Is 54 in e? False\n Length of Letters enum: 5\n\nUsing a list to create Enum:\n Is a in e? True\n Is 54 in e? False\n Length of Letters enum: 5\nSuccess!\n"
},
{
"answer_id": 20520884,
"author": "Saša Šijak",
"author_id": 257501,
"author_profile": "https://Stackoverflow.com/users/257501",
"pm_score": 5,
"selected": false,
"text": "from enum import Enum\nclass Color(Enum):\n red = 1\n green = 2\n blue = 3\n"
},
{
"answer_id": 22461315,
"author": "Rafay",
"author_id": 569085,
"author_profile": "https://Stackoverflow.com/users/569085",
"pm_score": 3,
"selected": false,
"text": "def enum(typename, field_names):\n \"Create a new enumeration type\"\n\n if isinstance(field_names, str):\n field_names = field_names.replace(',', ' ').split()\n d = dict((reversed(nv) for nv in enumerate(field_names)), __slots__ = ())\n return type(typename, (object,), d)()\n STATE = enum('STATE', 'GET_QUIZ, GET_VERSE, TEACH')\n"
},
{
"answer_id": 22723724,
"author": "Melroy van den Berg",
"author_id": 518879,
"author_profile": "https://Stackoverflow.com/users/518879",
"pm_score": 5,
"selected": false,
"text": "class Enum(object): \n def __init__(self, tupleList):\n self.tupleList = tupleList\n \n def __getattr__(self, name):\n return self.tupleList.index(name)\n DIRECTION = Enum(('UP', 'DOWN', 'LEFT', 'RIGHT'))\nDIRECTION.DOWN\n1\n from enum import Enum\nclass MyEnum(Enum):\n UP = 1\n DOWN = 2\n LEFT = 3\n RIGHT = 4\n MyEnum.DOWN\n"
},
{
"answer_id": 26861507,
"author": "estani",
"author_id": 1182464,
"author_profile": "https://Stackoverflow.com/users/1182464",
"pm_score": 4,
"selected": false,
"text": "def enum(*sequential, **named):\n enums = dict(zip(sequential, [object() for _ in range(len(sequential))]), **named)\n return type('Enum', (), enums)\n >>> DOG = enum('BARK', 'WALK', 'SIT')\n>>> CAT = enum('MEOW', 'WALK', 'SIT')\n>>> DOG.WALK == CAT.WALK\nFalse\n >>> DOG = enum('BARK'=1, 'WALK'=2, 'SIT'=3)\n>>> CAT = enum('WALK'=1, 'SIT'=2)\n>>> pet1_state = DOG.BARK\n>>> pet2_state = CAT.WALK\n>>> pet1_state == pet2_state\nTrue\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3880/"
] |
36,953 |
<p>Can people point me to resources on lexing, parsing and tokenising with Python?</p>
<p>I'm doing a little hacking on an open source project (<a href="http://www.hotwire-shell.org/" rel="noreferrer">hotwire</a>) and wanted to do a few changes to the code that <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/externals/shlex.py" rel="noreferrer">lexes</a>, <a href="http://code.google.com/p/hotwire-shell/source/browse/trunk/hotwire/command.py" rel="noreferrer">parses and tokenises</a> the commands entered into it. As it is real working code it is fairly complex and a bit hard to work out.</p>
<p>I haven't worked on code to lex/parse/tokenise before, so I was thinking one approach would be to work through a tutorial or two on this aspect. I would hope to learn enough to navigate around the code I actually want to alter. Is there anything suitable out there? (Ideally it could be done in an afternoon without having to buy and read the dragon book first ...)</p>
<p><strong>Edit:</strong> (7 Oct 2008) None of the below answers quite give what I want. With them I could generate parsers from scratch, but I want to learn how to write my own basic parser from scratch, not using lex and yacc or similar tools. Having done that I can then understand the existing code better. </p>
<p>So could someone point me to a tutorial where I can build a basic parser from scratch, using just python?</p>
|
[
{
"answer_id": 137207,
"author": "Torsten Marek",
"author_id": 9567,
"author_profile": "https://Stackoverflow.com/users/9567",
"pm_score": 4,
"selected": false,
"text": ">>> from pyparsing import Word, alphas\n>>> greet = Word( alphas ) + \",\" + Word( alphas ) + \"!\" # <-- grammar defined here\n>>> hello = \"Hello, World!\"\n>>>> print hello, \"->\", greet.parseString( hello )\nHello, World! -> ['Hello', ',', 'World', '!']\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3189/"
] |
36,956 |
<p>A Windows Forms application of ours pulls records from a view on SQL Server through ADO.NET and a SOAP web service, displaying them in a data grid. We have had several cases with ~25,000 rows, which works relatively smoothly, but a potential customer needs to have many times that much in a single list.</p>
<p>To figure out how well we scale right now, and how (and how far) we can realistically improve, I'd like to implement a simulation: instead of displaying actual data, have the SQL Server send fictional, random data. The client and transport side would be mostly the same; the view (or at least the underlying table) would of course work differently. The user specifies the amount of fictional rows (e.g. 100,000).</p>
<p>For the time being, I just want to know how long it takes for the client to retrieve and process the data and is just about ready to display it.</p>
<p>What I'm trying to figure out is this: how do I make the SQL Server send such data?</p>
<p>Do I:</p>
<ol>
<li>Create a stored procedure that has to be run beforehand to fill an actual table?</li>
<li>Create a function that I point the view to, thus having the server generate the data 'live'?</li>
<li>Somehow replicate and/or randomize existing data?</li>
</ol>
<p>The first option sounds to me like it would yield the results closest to the real world. Because the data is actually 'physically there', the <code>SELECT</code> query would be quite similar performance-wise to one on real data. However, it taxes the server with an otherwise meaningless operation. The fake data would also be backed up, as it would live in one and the same database — unless, of course, I delete the data after each benchmark run.</p>
<p>The second and third option tax the server <em>while</em> running the actual simulation, thus potentially giving unrealistically slow results.</p>
<hr>
<p>In addition, I'm unsure how to create those rows, short of using a loop or cursor. I can use <code>SELECT top <n> random1(), random2(), […] FROM foo</code> if <code>foo</code> actually happens to have <code><n></code> entries, but otherwise I'll (obviously) only get as many rows as <code>foo</code> happens to have. A <code>GROUP BY newid()</code> or similar doesn't appear to do the trick.</p>
|
[
{
"answer_id": 37004,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "WHILE (SELECT count(1) FROM benchmark) < 100000\n INSERT INTO benchmark\n SELECT TOP 100000 * FROM actualData\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1600/"
] |
36,959 |
<p>In MS SQL Server, I create my scripts to use customizable variables:</p>
<pre><code>DECLARE @somevariable int
SELECT @somevariable = -1
INSERT INTO foo VALUES ( @somevariable )
</code></pre>
<p>I'll then change the value of <code>@somevariable</code> at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.</p>
<p>How do I do the same with the PostgreSQL client <code>psql</code>?</p>
|
[
{
"answer_id": 36989,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 6,
"selected": false,
"text": "SELECT * FROM foo WHERE bar = ':myvariable'\n \\set myvariable '\\'somestring\\'' \nSELECT * FROM foo WHERE bar = :myvariable\n \\set myvariable somestring\nSELECT * FROM foo WHERE bar = :'myvariable'\n"
},
{
"answer_id": 3588796,
"author": "crowmagnumb",
"author_id": 433432,
"author_profile": "https://Stackoverflow.com/users/433432",
"pm_score": 9,
"selected": true,
"text": "\\set myvariable value\n SELECT * FROM :myvariable.table1;\n SELECT * FROM table1 WHERE :myvariable IS NULL;\n \\set myvariable value \n\nSELECT * FROM table1 WHERE column1 = :'myvariable';\n SELECT * FROM table1 WHERE column1 = ':myvariable';\n \\set myvariable 'value'\n \\set quoted_myvariable '\\'' :myvariable '\\''\n INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable;\n"
},
{
"answer_id": 9910705,
"author": "Nate",
"author_id": 1085691,
"author_profile": "https://Stackoverflow.com/users/1085691",
"pm_score": 2,
"selected": false,
"text": "\\set deployment_user username -- username\n\\set deployment_pass '\\'string_password\\''\nALTER USER :deployment_user WITH PASSWORD :deployment_pass;\n"
},
{
"answer_id": 13318869,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 5,
"selected": false,
"text": "psql psql -v $ psql -v filepath=/path/to/my/directory/mydatafile.data regress\nregress=> SELECT :'filepath';\n ?column? \n---------------------------------------\n /path/to/my/directory/mydatafile.data\n(1 row)\n :'filepath' :'filepath'"
},
{
"answer_id": 13318876,
"author": "Craig Ringer",
"author_id": 398670,
"author_profile": "https://Stackoverflow.com/users/398670",
"pm_score": 3,
"selected": false,
"text": "postgresql.conf SET current_setting(...)"
},
{
"answer_id": 13961901,
"author": "Kaiko Kaur",
"author_id": 1306381,
"author_profile": "https://Stackoverflow.com/users/1306381",
"pm_score": 2,
"selected": false,
"text": " CREATE FUNCTION var(name text, val text) RETURNS void AS $$\n $_SHARED{$_[0]} = $_[1];\n $$ LANGUAGE plperl;\n CREATE FUNCTION var(name text) RETURNS text AS $$\n return $_SHARED{$_[0]};\n $$ LANGUAGE plperl;\n CREATE TABLE var (\n sess bigint NOT NULL,\n key varchar NOT NULL,\n val varchar,\n CONSTRAINT var_pkey PRIMARY KEY (sess, key)\n);\nCREATE FUNCTION var(key varchar, val anyelement) RETURNS void AS $$\n DELETE FROM var WHERE sess = pg_backend_pid() AND key = $1;\n INSERT INTO var (sess, key, val) VALUES (sessid(), $1, $2::varchar);\n$$ LANGUAGE 'sql';\n\nCREATE FUNCTION var(varname varchar) RETURNS varchar AS $$\n SELECT val FROM var WHERE sess = pg_backend_pid() AND key = $1;\n$$ LANGUAGE 'sql';\n"
},
{
"answer_id": 15296222,
"author": "skaurus",
"author_id": 320345,
"author_profile": "https://Stackoverflow.com/users/320345",
"pm_score": 6,
"selected": false,
"text": "WITH vars AS (SELECT 42 AS answer, 3.14 AS appr_pi)\nSELECT t.*, vars.answer, t.radius*vars.appr_pi\nFROM table AS t, vars;\n"
},
{
"answer_id": 26588299,
"author": "geon",
"author_id": 446536,
"author_profile": "https://Stackoverflow.com/users/446536",
"pm_score": 3,
"selected": false,
"text": "CREATE TEMP TABLE temp_session_variables (\n \"sessionSalt\" TEXT\n);\nINSERT INTO temp_session_variables (\"sessionSalt\") VALUES (current_timestamp || RANDOM()::TEXT);\n"
},
{
"answer_id": 37150314,
"author": "Jasen",
"author_id": 471930,
"author_profile": "https://Stackoverflow.com/users/471930",
"pm_score": 4,
"selected": false,
"text": "DO '\nDECLARE somevariable int = -1;\nBEGIN\nINSERT INTO foo VALUES ( somevariable );\nEND\n' ;\n"
},
{
"answer_id": 53235522,
"author": "Alexander Kleinhans",
"author_id": 3049865,
"author_profile": "https://Stackoverflow.com/users/3049865",
"pm_score": 2,
"selected": false,
"text": "psql my_var test test thedatabase=# \\d test;\n Table \"public.test\"\n Column | Type | Modifiers \n--------+---------+---------------------------------------------------\n id | integer | not null default nextval('test_id_seq'::regclass)\nIndexes:\n \"test_pkey\" PRIMARY KEY, btree (id)\n thedatabase=# select * from test;\n id \n----\n(0 rows)\n thedatabase=# \\set my_var 999\nthedatabase=# ;\n :'' thedatabase=# insert into test(id) values (:'my_var');\nINSERT 0 1\n thedatabase=# select * from test;\n id \n-----\n 999\n(1 row)\n my_var thedatabase=# \\set my_var 999;\n my_var thedatabase=# select :'my_var';\n ?column? \n----------\n 999;\n(1 row)\n 999; thedatabase=# select 999;\n ?column? \n----------\n 999\n(1 row)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] |
36,984 |
<p>So right now my project has a few custom dialogs that do things like prompt the user for his birthday, or whatever. Right now they're just doing things like setting a <code>this.Birthday</code> property once they get an answer (which is of type <code>DateTime?</code>, with the null indicating a "Cancel"). Then the caller inspects the <code>Birthday</code> property of the dialog it created to figure out what the user answered.</p>
<p>My question is, <em>is there a more standard pattern for doing stuff like this?</em> I know we can set <code>this.DialogResult</code> for basic OK/Cancel stuff, but is there a more general way in Windows Forms for a form to indicate "here's the data I collected"?</p>
|
[
{
"answer_id": 37008,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 2,
"selected": false,
"text": "if (Dialog == Ok)\n{\n // Do Stuff with the entered values\n}\nelse\n{\n // Respond appropriately to the user cancelling the dialog\n}\n"
},
{
"answer_id": 37037,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "DialogResult ShowDialog(out datetime birthday)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
36,991 |
<p>So, I am a total beginner in any kind of <code>Windows</code> related programming. I have been playing around with the <code>Windows</code> <code>API</code> and came across a couple of examples on how to initialize create windows and such. </p>
<p>One example creates a regular window (I abbreviated some of the code):</p>
<pre><code>int WINAPI WinMain( [...] )
{
[...]
// Windows Class setup
wndClass.cbSize = sizeof( wndClass );
wndClass.style = CS_HREDRAW | CS_VREDRAW;
[...]
// Register class
RegisterClassEx( &wndClass );
// Create window
hWnd = CreateWindow( szAppName, "Win32 App",
WS_OVERLAPPEDWINDOW,
0, 0, 512, 384,
NULL, NULL, hInstance, NULL );
[...]
}
</code></pre>
<p>The second example creates a dialog box (no abbreviations except the WinMain arguments):</p>
<pre><code>int WINAPI WinMain( [...] )
{
// Create dialog box
DialogBox(hInstance,
MAKEINTRESOURCE(IDD_MAIN_DLG),
NULL,
(DLGPROC)DialogProc);
}
</code></pre>
<p>The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached. </p>
<p>This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible). </p>
|
[
{
"answer_id": 37008,
"author": "Murph",
"author_id": 1070,
"author_profile": "https://Stackoverflow.com/users/1070",
"pm_score": 2,
"selected": false,
"text": "if (Dialog == Ok)\n{\n // Do Stuff with the entered values\n}\nelse\n{\n // Respond appropriately to the user cancelling the dialog\n}\n"
},
{
"answer_id": 37037,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 1,
"selected": false,
"text": "DialogResult ShowDialog(out datetime birthday)\n"
}
] |
2008/08/31
|
[
"https://Stackoverflow.com/questions/36991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2386/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.